Esempio n. 1
0
        public static (Entity, List <string>) Main()
        {
            var fileTree = new List <KeyValuePair <int, object> >();
            var values   = new List <string>();

            var crimes     = new NativeList <EntityWrapper>(Allocator.Temp);
            var crimeNames = new List <string>();

            var em = World.Active.EntityManager;

            FileUnpacker.ParseFile(Path.Combine(Application.streamingAssetsPath, "Common", "crime.txt"), fileTree,
                                   values, CrimeMagicOverride);

            using (var parentLocation = new NativeMultiHashMap <int, int>(1, Allocator.Temp))
            {
                foreach (var crimeKvp in fileTree)
                {
                    var crimeRanges  = new List <DataRange>();
                    var crimeActions = new List <DataValue>();

                    parentLocation.Add(crimeKvp.Key, crimeRanges.Count);
                    crimeRanges.Add(new DataRange(crimeKvp.Key, -1, -1));

                    FileUnpacker.ProcessQueue(crimeKvp, crimeActions, crimeRanges, parentLocation, values,
                                              (s, pair) => false);

                    var currentCrime = crimes[crimeKvp.Key - (int)MagicUnifiedNumbers.Placeholder];

                    using (var tempRange = new NativeArray <DataRange>(crimeRanges.ToArray(), Allocator.TempJob))
                    {
                        em.AddBuffer <DataRange>(currentCrime).AddRange(tempRange);
                    }

                    using (var tempValues = new NativeArray <DataValue>(crimeActions.ToArray(), Allocator.TempJob))
                    {
                        em.AddBuffer <DataValue>(currentCrime).AddRange(tempValues);
                    }
                }
            }

            var crimeCollector = FileUnpacker.GetCollector <CrimeCollector>(crimes);

            crimes.Dispose();

            return(crimeCollector, crimeNames);

            int CrimeMagicOverride(int parent, string str)
            {
                if (parent != -1)
                {
                    return((int)MagicUnifiedNumbers.ContinueMagicNumbers);
                }

                crimes.Add(em.CreateEntity(typeof(CrimeEntity)));
                crimeNames.Add(str);
                return((int)MagicUnifiedNumbers.Placeholder + crimeNames.Count - 1);
            }
        }
Esempio n. 2
0
        public static (List <string>, List <(Color Palette, int Index)>) Main(bool cache)
        {
            var(terrainNames, terrainEntities, terrainData,
                paletteLookups) = cache ? JsonUtility.FromJson <TerrainOutput>(
                LoadMethods.Unzip(File.ReadAllBytes(Path.Combine(Application.streamingAssetsPath, "JsonData", "terrain.txt"))))
                : ParseParadoxFile();

            var em = World.DefaultGameObjectInjectionWorld.EntityManager;

            for (var index = 0; index < terrainEntities.Count; index++)
            {
                var terrain = em.CreateEntity(typeof(TerrainEntity));
                var data    = terrainEntities[index];
                data.SetName(terrainNames[index]);
                em.SetComponentData(terrain, data);

                using (var currentCoreActions = new NativeArray <FirstLevelCore>(
                           ((List <FirstLevelCore>)terrainData[index]).ToArray(), Allocator.Temp))
                {
                    em.AddBuffer <FirstLevelCore>(terrain).AddRange(currentCoreActions);
                }
            }

            // Creating collection entity.
            FileUnpacker.GetCollector <TerrainEntity>();

            /* DEBUG
             * var test = em.GetBuffer<Terrains>(terrainCollectorEntity);
             * var test1 = test.AsNativeArray();
             * for (var index = 0; index < test1.Length; index++)
             * {
             *  var terrainType = test1[index];
             *  var color = em.GetComponentData<TerrainEntity>(terrainType.TerrainEntity).Color;
             *  Debug.Log(terrainNames[index] + " color: " + color);
             *  var coreActions = em.GetBuffer<TerrainValues>(terrainType.TerrainEntity).AsNativeArray();
             *  foreach (var action in coreActions)
             *      Debug.Log(action);
             * }
             */
            return(terrainNames,
                   paletteLookups.ConvertAll(input => ((Color, int))input));
        }
Esempio n. 3
0
        public static (List <(int, int)>, List <string>) Main(bool cache, NativeHashMap <int, int> idIndex)
        {
            var provinces         = new List <(int, int)>();
            var continentNames    = new List <string>();
            var continentEntities = new List <ContinentEntity>();

            if (cache)
            {
                (provinces, continentEntities, continentNames) = JsonUtility.FromJson <ContinentOutput>(
                    LoadMethods.Unzip(File.ReadAllBytes(Path.Combine(Application.streamingAssetsPath, "JsonData", "continent.txt"))));

                LoadMethods.GenerateCacheEntities <ContinentEntity, ContinentCollection>(continentEntities, continentNames);

                return(provinces, continentNames);
            }

            var em = World.DefaultGameObjectInjectionWorld.EntityManager;

            var continents = new NativeList <EntityWrapper>(Allocator.Temp);

            var outerToggle = false;
            var provToggle  = false;
            var currentCont = new ContinentEntity();

            foreach (var rawLine in File.ReadLines(Path.Combine(Application.streamingAssetsPath, "map", "continent.txt")))
            {
                if (LoadMethods.CommentDetector(rawLine, out var line))
                {
                    continue;
                }

                var equalSplit = Regex.Match(line, @"^.*?(?=\=)");

                if (line.Contains("{"))
                {
                    var newLine = line.Substring(equalSplit.Length + 1).Replace("{", "").Trim();
                    if (!outerToggle)
                    {
                        outerToggle = true;
                        var name = equalSplit.Value.Trim();
                        currentCont = new ContinentEntity {
                            Name = name
                        };                                               // {Index = continentNames.Count};
                        continentNames.Add(name);

                        if (newLine == string.Empty)
                        {
                            continue;
                        }

                        equalSplit = Regex.Match(newLine, @"^.*?(?=\=)");
                    }

                    if (!equalSplit.Value.Contains("provinces"))
                    {
                        throw new Exception("Unknown nested value: " + equalSplit);
                    }

                    provToggle = true;

                    if (newLine == string.Empty)
                    {
                        continue;
                    }

                    line = newLine;
                }

                if (provToggle)
                {
                    var numbers = Regex.Match(line, @"[\d\s]+");
                    if (numbers.Success)
                    {
                        var individualProv = numbers.Value.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (var provId in individualProv)
                        {
                            if (!int.TryParse(provId, out var num))
                            {
                                continue;
                            }

                            provinces.Add((idIndex[num], continents.Length));
                        }
                    }
                }
                else
                {
                    var newLine = line.Substring(equalSplit.Length + 1).Replace("}", "").Trim();
                    switch (equalSplit.Value.Trim())
                    {
                    case "assimilation_rate":
                        if (!float.TryParse(newLine, out var assimilationRate))
                        {
                            throw new Exception("Unknown assimilation rate: " + newLine);
                        }
                        currentCont.AssimilationRate = assimilationRate;
                        break;

                    case "farm_rgo_size":
                        if (!float.TryParse(newLine, out var farmSize))
                        {
                            throw new Exception("Unknown farm RGO size: " + newLine);
                        }
                        currentCont.FarmRgoSize = farmSize;
                        break;

                    case "mine_rgo_size":
                        if (!float.TryParse(newLine, out var mineSize))
                        {
                            throw new Exception("Unknown mine RGO size: " + newLine);
                        }
                        currentCont.MineRgoSize = mineSize;
                        break;
                    }
                }

                if (!line.Contains("}"))
                {
                    continue;
                }

                if (provToggle)
                {
                    provToggle = false;
                }
                else
                {
                    outerToggle = false;
                    var target = em.CreateEntity(typeof(ContinentEntity));
                    em.SetComponentData(target, currentCont);
                    continents.Add(target);
                    continentEntities.Add(currentCont);
                }
            }

            FileUnpacker.GetCollector <ContinentCollection>();
            continents.Dispose();

            //File.WriteAllText(Path.Combine(Application.streamingAssetsPath, "JsonData", "continent.txt"),
            //JsonUtility.ToJson(new ContinentOutput(continentNames, provinces, continentEntities), true));

            File.WriteAllBytes(Path.Combine(Application.streamingAssetsPath, "JsonData", "continent.txt"),
                               LoadMethods.Zip(JsonUtility.ToJson(new ContinentOutput(continentNames, provinces, continentEntities))));

            return(provinces, continentNames);
        }
Esempio n. 4
0
        private static TerrainOutput ParseParadoxFile()
        {
            var fileTree = new List <(int Key, object Value)>();

            var terrainNames   = new List <string>();
            var terrains       = new List <TerrainEntity>();
            var terrainCache   = new List <List <FirstLevelCore> >();
            var paletteLookups = new List <(Color Palette, int Index)>();

            // Generating file tree representation.
            FileUnpacker.ParseFile(Path.Combine(Application.streamingAssetsPath, "map", "terrain.txt"),
                                   fileTree, TerrainMagicOverride);

            for (var index = 0; index < fileTree.Count; index++)
            {
                var currentTerrain = terrains[index];

                var(breakCores, _) = FileUnpacker.AssignFirstLevelDistributeWorkload(ref currentTerrain, fileTree[index],
                                                                                     TerrainOverride);

                terrainCache.Add(breakCores);

                bool TerrainOverride((int Key, object Value) target)
                {
                    switch ((LoadVariables)target.Key)
                    {
                    case LoadVariables.Palette:
                        if (!ColorUtility.TryParseHtmlString("#" + (string)target.Value, out var paletteColor))
                        {
                            throw new Exception("Unknown hex color. " + (string)target.Value);
                        }

                        paletteLookups.Add((paletteColor, index));
                        return(true);

                    default:
                        return(false);
                    }
                }
            }

            int TerrainMagicOverride(int parent, string str)
            {
                if (parent != -1)
                {
                    return((int)MagicUnifiedNumbers.ContinueMagicNumbers);
                }

                terrainNames.Add(str);

                terrains.Add(new TerrainEntity {
                    Name = str
                });
                return((int)MagicUnifiedNumbers.Terrain + terrainNames.Count - 1);
            }

            var output = new TerrainOutput(terrainNames, terrains, terrainCache, paletteLookups);

            //File.WriteAllText(Path.Combine(Application.streamingAssetsPath, "JsonData", "terrain.txt"),
            //JsonUtility.ToJson(output, true));

            File.WriteAllBytes(Path.Combine(Application.streamingAssetsPath, "JsonData", "terrain.txt"),
                               LoadMethods.Zip(JsonUtility.ToJson(output)));

            return(output);
        }
Esempio n. 5
0
        public static (Entity, List <string>) Main()
        {
            var popFiles = Directory.GetFiles(Path.Combine(Application.streamingAssetsPath, "PopTypes"), "*.txt");

            // Output arrays
            var popTypes = new NativeList <EntityWrapper>(Allocator.Temp);
            var popNames = new List <string>();

            popNames.AddRange(popFiles.Select(Path.GetFileNameWithoutExtension));

            var em = World.Active.EntityManager;

            using (var needsList = new NativeList <DataGood>(Allocator.Temp))
                using (var popRebels = new NativeList <DataValue>(Allocator.Temp))
                {
                    for (var index = 0; index < popTypes.Length; index++)
                    {
                        // Generating file tree
                        var fileTree = new List <KeyValuePair <int, object> >();
                        var values   = new List <string>();

                        FileUnpacker.ParseFile(popFiles[index], fileTree, values,
                                               (i, s) => (int)MagicUnifiedNumbers.ContinueMagicNumbers);

                        var currentEntity  = em.CreateEntity(typeof(PopTypeEntity));
                        var currentPopType = new PopTypeEntity {
                            Index = index
                        };

                        foreach (var topLevel in fileTree)
                        {
                            switch ((LoadVariables)topLevel.Key)
                            {
                            case LoadVariables.Sprite:
                                // Skipping sprite
                                break;

                            case LoadVariables.Color:
                                currentPopType.Color = LoadMethods.ParseColor32(values[(int)topLevel.Value]);
                                break;

                            case LoadVariables.Strata:
                                if (!Enum.TryParse(values[(int)topLevel.Value], true,
                                                   out PopTypeEntity.Standing strata))
                                {
                                    throw new Exception("Strata unknown: " + values[(int)topLevel.Value]);
                                }
                                currentPopType.Strata = strata;
                                break;

                            case LoadVariables.StateCapitalOnly:
                                currentPopType.StateCapitalOnly =
                                    LoadMethods.YesNoConverter(values[(int)topLevel.Value]);
                                break;

                            case LoadVariables.Rebel:
                                RebelParser(topLevel);
                                em.AddBuffer <DataValue>(currentEntity).AddRange(popRebels);
                                popRebels.Clear();
                                break;

                            case LoadVariables.CountryMigrationTarget:
                            case LoadVariables.MigrationTarget:
                            case LoadVariables.PromoteTo:
                            case LoadVariables.Ideologies:
                                var collapsedList = new List <float2>();
                                RestParser(topLevel, collapsedList);
                                break;

                            case LoadVariables.LifeNeeds:
                            case LoadVariables.EverydayNeeds:
                            case LoadVariables.LuxuryNeeds:
                                NeedsParser(topLevel);
                                break;
                            }
                        }

                        em.AddBuffer <DataGood>(currentEntity).AddRange(needsList);
                        em.SetComponentData(currentEntity, currentPopType);
                        popTypes.Add(currentEntity);
                        needsList.Clear();

                        // DEBUG
                        //break;

                        void RestParser(KeyValuePair <int, object> currentBranch, List <float2> targetList)
                        {
                        }

                        void NeedsParser(KeyValuePair <int, object> currentBranch)
                        {
                            // There should be no nested values within needs.
                            var startingNeeds = needsList.Length;

                            foreach (var goodsKvp in (List <KeyValuePair <int, object> >)currentBranch.Value)
                            {
                                if (!float.TryParse(values[(int)goodsKvp.Value], out var goodsNeeded))
                                {
                                    throw new Exception("Unknown goods needed: " + values[(int)goodsKvp.Value]);
                                }

                                needsList.Add(new DataGood(goodsKvp.Key - (int)MagicUnifiedNumbers.Goods, goodsNeeded));
                            }

                            switch ((LoadVariables)currentBranch.Key)
                            {
                            case LoadVariables.LifeNeeds:
                                currentPopType.lifeRange = new int2(startingNeeds, needsList.Length);
                                break;

                            case LoadVariables.EverydayNeeds:
                                currentPopType.everydayRange = new int2(startingNeeds, needsList.Length);
                                break;

                            case LoadVariables.LuxuryNeeds:
                                currentPopType.luxuryRange = new int2(startingNeeds, needsList.Length);
                                break;
                            }
                        }

                        void RebelParser(KeyValuePair <int, object> currentBranch)
                        {
                            foreach (var armyKvp in (List <KeyValuePair <int, object> >)currentBranch.Value)
                            {
                                if (!float.TryParse(values[(int)armyKvp.Value], out var armyRatio))
                                {
                                    throw new Exception("Unknown army ratio: " + values[(int)armyKvp.Value]);
                                }

                                if (armyRatio < 0.001)
                                {
                                    continue;
                                }

                                popRebels.Add(new DataValue(armyKvp.Key - (int)MagicUnifiedNumbers.Unit, armyRatio));
                            }
                        }
                    }
                }

            var popTypeCollectorEntity = FileUnpacker.GetCollector <PopTypeCollection>(popTypes);

            popTypes.Dispose();

            return(popTypeCollectorEntity, popNames);
        }
Esempio n. 6
0
        public static Entity Main(Entity technologies, ref StringBox stringBox)
        {
            var inventions              = new NativeList <EntityWrapper>(Allocator.Temp);
            var inventionNames          = new List <string>();
            var allIncompleteInventions = new List <List <IncompleteInventions> >();

            var em = World.Active.EntityManager;

            using (var technologyList = em.GetBuffer <EntityWrapper>(technologies).ToNativeArray(Allocator.Temp))
                using (var parentLocation = new NativeMultiHashMap <int, int>(1, Allocator.Temp))
                {
                    foreach (var inventPath in Directory.EnumerateFiles(
                                 Path.Combine(Application.streamingAssetsPath, "Inventions"), "*.txt"))
                    {
                        var fileTree = new List <KeyValuePair <int, object> >();
                        var values   = new List <string>();

                        FileUnpacker.ParseFile(inventPath, fileTree, values, InventMagicOverride);

                        foreach (var inventionKvP in fileTree)
                        {
                            var targetInvention = new InventionEntity
                            {
                                Index = inventionKvP.Key - (int)MagicUnifiedNumbers.Invention
                            };
                            var inventionEntity = inventions[targetInvention.Index];

                            var inventValues   = new List <DataValue>();
                            var inventRanges   = new List <DataRange>();
                            var tempInventions = new List <IncompleteInventions>();

                            parentLocation.Add(inventionKvP.Key, inventRanges.Count);
                            inventRanges.Add(new DataRange(inventionKvP.Key, -1, -1));

                            FileUnpacker.ProcessQueue(inventionKvP, inventValues, inventRanges,
                                                      parentLocation, values, InventSwitchOverride);

                            em.SetComponentData(inventionEntity, targetInvention);

                            allIncompleteInventions.Add(tempInventions);

                            using (var tempRange = new NativeArray <DataRange>(inventRanges.ToArray(), Allocator.Temp))
                            {
                                em.AddBuffer <DataRange>(inventionEntity).AddRange(tempRange);
                            }

                            using (var tempValues = new NativeArray <DataValue>(inventValues.ToArray(), Allocator.Temp))
                            {
                                em.AddBuffer <DataValue>(inventionEntity).AddRange(tempValues);
                            }

                            bool InventSwitchOverride(string targetStr, KeyValuePair <int, object> target)
                            {
                                switch ((MagicUnifiedNumbers)(target.Key / 10000 * 10000))
                                {
                                case MagicUnifiedNumbers.Placeholder:
                                    var targetTech = technologyList[target.Key - (int)MagicUnifiedNumbers.Placeholder];
                                    targetInvention.Technology = targetTech;

                                    em.GetBuffer <EntityWrapper>(targetTech).Add(inventionEntity);
                                    return(true);
                                }

                                if (target.Key != (int)LoadVariables.Invention)
                                {
                                    return(false);
                                }

                                tempInventions.Add(new IncompleteInventions(targetStr, inventValues.Count));
                                inventValues.Add(new DataValue((int)LoadVariables.Invention, -1));
                                return(true);
                            }
                        }
                    }
                }

            stringBox.InventionNames = inventionNames;

            var inventionCollector = FileUnpacker.GetCollector <InventionCollection>(inventions);

            inventions.Dispose();

            CompleteInventions(inventionCollector, allIncompleteInventions);

            return(inventionCollector);

            int InventMagicOverride(int parent, string raw)
            {
                if (parent == (int)LoadVariables.Limit)
                {
                    // God damn C# trash pointers.
                    if (LookupDictionaries.Techs.TryGetValue(raw, out var techIndex))
                    {
                        return((int)MagicUnifiedNumbers.Placeholder + techIndex);
                    }
                }

                if (parent != -1)
                {
                    return((int)MagicUnifiedNumbers.ContinueMagicNumbers);
                }

                inventions.Add(em.CreateEntity(typeof(InventionEntity)));
                inventionNames.Add(raw);
                return((int)MagicUnifiedNumbers.Invention + inventionNames.Count - 1);
            }
        }
Esempio n. 7
0
        public static Entity Main(NativeHashMap <int, int> idIndex)
        {
            // Assuming start date of only 1836.1.1

            var provinces = new NativeArray <EntityWrapper>(idIndex.Length, Allocator.Temp);

            var em = World.Active.EntityManager;

            using (var cores = new NativeList <DataInt>(Allocator.Temp))
            {
                foreach (var continent in Directory.GetDirectories(Path.Combine(Application.streamingAssetsPath,
                                                                                "History", "provinces")))
                {
                    foreach (var filePath in Directory.GetFiles(continent, "*.txt"))
                    {
                        var fileTree = new List <KeyValuePair <int, object> >();
                        var values   = new List <string>();

                        FileUnpacker.ParseFile(filePath, fileTree, values, ProvinceMagicOverride);

                        var idString = Regex.Match(Path.GetFileNameWithoutExtension(filePath), @"\d+").Value;
                        if (!int.TryParse(idString, out var provId))
                        {
                            throw new Exception("Invalid province file name. Must include province ID. " + filePath);
                        }

                        var provIndex       = idIndex[provId];
                        var currentProvince = new ProvinceEntity {
                            Owner = -1, Controller = -1, Terrain = -1, Colonial = -1
                        };

                        foreach (var property in fileTree)
                        {
                            if (!(property.Value is int))
                            {
                                continue;
                            }

                            var targetStr = values[(int)property.Value];
                            switch ((LoadVariables)property.Key)
                            {
                            case LoadVariables.Owner: // initial color
                                if (!LookupDictionaries.CountryTags.TryGetValue(targetStr, out var ownerIndex))
                                {
                                    throw new Exception("Unknown owner. " + targetStr);
                                }

                                currentProvince.Owner = ownerIndex;
                                break;

                            case LoadVariables.Controller: // siege ownership
                                if (!LookupDictionaries.CountryTags.TryGetValue(targetStr, out var controllerIndex))
                                {
                                    throw new Exception("Unknown controller. " + targetStr);
                                }

                                currentProvince.Controller = controllerIndex;
                                break;

                            case LoadVariables.AddCore: // cores on province
                                if (!LookupDictionaries.CountryTags.TryGetValue(targetStr, out var coreIndex))
                                {
                                    throw new Exception("Unknown core. " + targetStr);
                                }

                                cores.Add(coreIndex);
                                break;

                            case LoadVariables.TradeGoods: // good produced
                                if (!LookupDictionaries.Goods.TryGetValue(targetStr, out var goodIndex))
                                {
                                    throw new Exception("Unknown good. " + targetStr);
                                }

                                currentProvince.Production = goodIndex;
                                break;

                            case LoadVariables.LifeRating:
                                if (!int.TryParse(targetStr, out var lifeRating))
                                {
                                    throw new Exception("Unknown life rating. " + targetStr);
                                }

                                currentProvince.LifeRating = lifeRating;
                                break;

                            case LoadVariables.Terrain:
                                if (!LookupDictionaries.Terrain.TryGetValue(targetStr, out var terrainIndex))
                                {
                                    throw new Exception("Unknown terrain. " + targetStr);
                                }

                                currentProvince.Terrain = terrainIndex;
                                break;

                            case LoadVariables.Colonial:
                                if (!int.TryParse(targetStr, out var colonialLevel))
                                {
                                    throw new Exception("Unknown colonialLevel. " + targetStr);
                                }

                                currentProvince.Colonial = colonialLevel;
                                break;
                            }
                        }

                        if (currentProvince.Owner == -1)
                        {
                            if (currentProvince.LifeRating < 1)
                            {
                                currentProvince.Owner = LookupDictionaries.CountryTags["ocn"];
                            }
                            else
                            {
                                currentProvince.Owner = LookupDictionaries.CountryTags["ucn"];
                                if (currentProvince.Colonial < 1)
                                {
                                    currentProvince.Colonial = 0;
                                }
                            }
                        }

                        var targetProvince = em.CreateEntity(typeof(ProvinceEntity));
                        em.SetComponentData(targetProvince, currentProvince);
                        em.AddBuffer <DataInt>(targetProvince).AddRange(cores);
                        em.AddBuffer <ProvPopInfo>(targetProvince); // Used for populations.
                        cores.Clear();

                        provinces[provIndex] = targetProvince;

                        int ProvinceMagicOverride(int parent, string target)
                        {
                            // Skipping other start dates
                            return(Regex.IsMatch(target, @"\d+")
                            ? (int)MagicUnifiedNumbers.Placeholder
                            : (int)MagicUnifiedNumbers.ContinueMagicNumbers);
                        }
                    }
                }
            }

            var provinceCollection = FileUnpacker.GetCollector <ProvinceCollection>(provinces);

            provinces.Dispose();

            return(provinceCollection);
        }
Esempio n. 8
0
        public static IdeologyOutput ParseParadoxFile()
        {
            var fileTree = new List <(int, object)>();

            var ideologyNames       = new List <string>();
            var groupNames          = new List <string>();
            var ideologies          = new List <IdeologyEntity>();
            var ideologyFirstLevels = new List <List <FirstLevelCore> >();

            var em = World.DefaultGameObjectInjectionWorld.EntityManager;

            FileUnpacker.ParseFile(Path.Combine(Application.streamingAssetsPath, "common", "ideologies.txt"),
                                   fileTree, IdeologyMagicOverride);


            for (var index = 0; index < fileTree.Count; index++)
            {
                var currentIdeology = ideologies[index];

                var(breakCores, reformModifiers) =
                    FileUnpacker.AssignFirstLevelDistributeWorkload(ref currentIdeology, fileTree[index], IdeologyOverride);

                ideologyFirstLevels.Add(breakCores);


                bool IdeologyOverride((int Key, object Value) target)
                {
                    return(false);
                }
            }

            return(ideologyNames, groupNames);

            int IdeologyMagicOverride(int parent, string str)
            {
                if (parent == -1)
                {
                    groupNames.Add(str);

                    return((int)MagicUnifiedNumbers.IdeologyGroup + groupNames.Count - 1);
                }

                if (parent / 10000 == (int)MagicUnifiedNumbers.IdeologyGroup / 10000)
                {
                    ideologies.Add(new IdeologyEntity {
                        Name = str, Group = groupNames.Last()
                    });
                    ideologyNames.Add(str);

                    return((int)MagicUnifiedNumbers.Ideology + ideologyNames.Count - 1);
                }

                return((int)MagicUnifiedNumbers.ContinueMagicNumbers);
            }

            /*
             * var counter = 0;
             *
             * using (var parentLocation = new NativeMultiHashMap<int, int>(10, Allocator.Temp))
             * {
             *  foreach (var ideologyGroup in fileTree)
             *  foreach (var ideKvp in (List<KeyValuePair<int, object>>) ideologyGroup.Value)
             *  {
             *      var currentEntity = ideologies[counter++];
             *      var currentIdeology = em.GetComponentData<IdeologyEntity>(currentEntity);
             *
             *      var ideologyRanges = new List<DataRange>();
             *      var ideologyActions = new List<DataValue>();
             *
             *      FileUnpacker.ProcessQueue(ideKvp, ideologyActions, ideologyRanges, parentLocation, values,
             *          IdeologySwitchOverride);
             *
             *      using (var tempRange = new NativeArray<DataRange>(ideologyRanges.ToArray(), Allocator.Temp))
             *      {
             *          em.AddBuffer<DataRange>(currentEntity).AddRange(tempRange);
             *      }
             *
             *      using (var tempAction = new NativeArray<DataValue>(ideologyActions.ToArray(), Allocator.Temp))
             *      {
             *          em.AddBuffer<DataValue>(currentEntity).AddRange(tempAction);
             *      }
             *
             *      em.SetComponentData(currentEntity, currentIdeology);
             *
             *      bool IdeologySwitchOverride(string targetStr, KeyValuePair<int, object> subSection)
             *      {
             *          switch ((LoadVariables) subSection.Key)
             *          {
             *              case LoadVariables.CanReduceMilitancy:
             *              case LoadVariables.Uncivilized:
             *                  currentIdeology.Uncivilized =
             *                      LoadMethods.YesNoConverter(values[(int) subSection.Value]);
             *                  return true;
             *              case LoadVariables.Color:
             *                  currentIdeology.Color = LoadMethods.ParseColor32(values[(int) subSection.Value]);
             *                  return true;
             *              case LoadVariables.Date:
             *                  if (!DateTime.TryParse(values[(int) subSection.Value], out var date))
             *                      throw new Exception("Unknown date: " + values[(int) subSection.Value]);
             *
             *                  int.TryParse(date.ToString("yyyyMMdd"), out var dateInt);
             *                  currentIdeology.Date = dateInt;
             *                  return true;
             *              case LoadVariables.AddPoliticalReform:
             *                  currentIdeology.AddPolitical = ideologyRanges.Count;
             *                  return false;
             *              case LoadVariables.RemovePoliticalReform:
             *                  currentIdeology.RemovePolitical = ideologyRanges.Count;
             *                  return false;
             *              case LoadVariables.AddSocialReform:
             *                  currentIdeology.AddSocial = ideologyRanges.Count;
             *                  return false;
             *              case LoadVariables.RemoveSocialReform:
             *                  currentIdeology.RemoveSocial = ideologyRanges.Count;
             *                  return false;
             *              case LoadVariables.AddMilitaryReform:
             *                  currentIdeology.AddMilitary = ideologyRanges.Count;
             *                  return false;
             *              case LoadVariables.AddEconomicReform:
             *                  currentIdeology.AddEconomic = ideologyRanges.Count;
             *                  return false;
             *              default:
             *                  return false;
             *          }
             *      }
             *  }
             * }
             *
             * var ideologyCollectorEntity = FileUnpacker.GetCollector<IdeologyCollection>(ideologies);
             * ideologies.Dispose();
             *
             * var groupCollectorEntity = FileUnpacker.GetCollector<IdeologyGroupCollection>(groups);
             * groups.Dispose();
             *
             * return (ideologyCollectorEntity, groupCollectorEntity, ideologyNames, groupNames);
             *
             * // Special file parsing instructions.
             * // Assigns magic numbers.
             * int IdeMagicOverride(int parent, string str)
             * {
             *  if (parent == -1)
             *  {
             *      var targetGroup = em.CreateEntity(typeof(IdeologyGroupEntity));
             *      em.SetComponentData(targetGroup, new IdeologyGroupEntity {Index = groupNames.Count});
             *
             *      currentGroup = targetGroup;
             *
             *      groups.Add(targetGroup);
             *      groupNames.Add(str);
             *
             *      return (int) MagicUnifiedNumbers.IdeologyGroup + groupNames.Count - 1;
             *  }
             *
             *  if (parent / 10000 == (int) MagicUnifiedNumbers.IdeologyGroup / 10000)
             *  {
             *      var targetIdeology = em.CreateEntity(typeof(IdeologyEntity));
             *      em.SetComponentData(targetIdeology,
             *          new IdeologyEntity {Index = ideologyNames.Count, Group = currentGroup});
             *
             *      ideologies.Add(targetIdeology);
             *      ideologyNames.Add(str);
             *
             *      return (int) MagicUnifiedNumbers.Ideology + ideologyNames.Count - 1;
             *  }
             *
             *  return (int) MagicUnifiedNumbers.ContinueMagicNumbers;
             * }
             */
        }
Esempio n. 9
0
        public static (List <string>, List <string>) Main(bool cache)
        {
            var groupNames       = new List <string>();
            var religionNames    = new List <string>();
            var religionEntities = new List <ReligionEntity>();

            if (cache)
            {
                (religionNames, groupNames, religionEntities) = JsonUtility.FromJson <ReligionsOutput>(
                    LoadMethods.Unzip(File.ReadAllBytes(Path.Combine(Application.streamingAssetsPath, "JsonData", "religion.txt"))));

                LoadMethods.GenerateCacheEntities <ReligionEntity, ReligionCollection>(religionEntities, religionNames, groupNames);

                return(religionNames, groupNames);
            }

            var em = World.DefaultGameObjectInjectionWorld.EntityManager;

            bool groupToggle = false, religionToggle = false, colorToggle = false;
            var  currentReligion = new ReligionEntity();

            foreach (var line in File.ReadLines(Path.Combine(Application.streamingAssetsPath, "Common",
                                                             "religion.txt")))
            {
                if (LoadMethods.CommentDetector(line, out var commentSplit))
                {
                    continue;
                }

                var equalsSplit = commentSplit.Split(new[] { "=" }, StringSplitOptions.RemoveEmptyEntries);

                if (commentSplit.Contains("{"))
                {
                    if (!groupToggle)
                    {
                        groupToggle = true;

                        groupNames.Add(equalsSplit[0].Trim());
                        continue;
                    }

                    if (!religionToggle)
                    {
                        religionToggle  = true;
                        currentReligion = new ReligionEntity {
                            Group = groupNames.Last()
                        };
                        religionNames.Add(equalsSplit[0].Trim());
                        continue;
                    }

                    if (!colorToggle)
                    {
                        colorToggle = true;
                    }
                }

                switch (equalsSplit[0].Trim())
                {
                case "color":
                    // Why religion colors are in float, I have absolutely no idea.
                    currentReligion.Color = LoadMethods.ParseColor32(equalsSplit[1]);
                    break;
                }

                if (!commentSplit.Contains("}"))
                {
                    continue;
                }

                if (colorToggle)
                {
                    colorToggle = false;
                    continue;
                }

                if (religionToggle)
                {
                    religionToggle = false;

                    var targetEntity = em.CreateEntity(typeof(ReligionEntity));
                    em.SetComponentData(targetEntity, currentReligion);
                    religionEntities.Add(currentReligion);

                    continue;
                }

                groupToggle = false;
            }

            FileUnpacker.GetCollector <ReligionCollection>();

            File.WriteAllBytes(Path.Combine(Application.streamingAssetsPath, "JsonData", "religion.txt"),
                               LoadMethods.Zip(JsonUtility.ToJson(new ReligionsOutput(groupNames, religionNames, religionEntities))));

            /*
             * var test = em.GetBuffer<EntityWrapper>(religionCollectorEntity);
             * foreach (var religion in test.AsNativeArray())
             * {
             *  var religionEntity = em.GetComponentData<ReligionEntity>(religion.Entity);
             *  Debug.Log(religionNames[religionEntity.Index]
             + " of group " + groupNames[em.GetComponentData<ReligionGroupEntity>(religionEntity.Group).Index]);
             + }
             */

            return(religionNames, groupNames);
        }
Esempio n. 10
0
        public static (List <string>, List <string>) Main(bool cache)
        {
            var cultures          = new List <CultureEntity>();
            var cultureNames      = new List <string>();
            var cultureGroupNames = new List <string>();

            if (cache)
            {
                (cultureNames, cultureGroupNames, cultures) = JsonUtility.FromJson <CulturesOutput>(
                    LoadMethods.Unzip(File.ReadAllBytes(Path.Combine(Application.streamingAssetsPath, "JsonData", "cultures.txt"))));

                LoadMethods.GenerateCacheEntities <CultureEntity, CultureCollection>(cultures, cultureNames, cultureGroupNames);

                return(cultureNames, cultureGroupNames);
            }

            var em = World.DefaultGameObjectInjectionWorld.EntityManager;

            bool groupToggle   = false,
                 cultureToggle = false,
                 ignoreToggle  = false;
            var currentCulture = new CultureEntity();

            foreach (var line in File.ReadLines(Path.Combine(Application.streamingAssetsPath, "common",
                                                             "cultures.txt")))
            {
                if (LoadMethods.CommentDetector(line, out var commentSplit))
                {
                    continue;
                }

                if (ignoreToggle)
                {
                    if (commentSplit.Contains("}"))
                    {
                        ignoreToggle = false;
                    }

                    // Assuming no values defined after end brackets
                    continue;
                }

                var equalsSplit = Regex.Match(commentSplit, @"^.+?(?=\=)");
                var preEquals   = equalsSplit.Success ? equalsSplit.Value.Trim() : "";

                if (commentSplit.Contains("{"))
                {
                    if (!groupToggle)
                    {
                        groupToggle = true;
                        cultureGroupNames.Add(preEquals);
                        continue;
                    }

                    if (!commentSplit.Contains("_names") && !commentSplit.Contains("color"))
                    {
                        cultureToggle = true;
                        var name = preEquals.Trim();
                        cultureNames.Add(name);
                        currentCulture = new CultureEntity {
                            Group = cultureGroupNames.Last(), Name = name
                        };
                    }
                }

                switch (preEquals)
                {
                case "union":
                    currentCulture.Union =
                        LookupDictionaries.CountryTags[commentSplit.Substring(equalsSplit.Length + 1).Trim()];
                    continue;

                case "first_names":
                case "last_names":
                    // TODO: Implement names generation, someday.
                    if (!commentSplit.Contains("}"))
                    {
                        ignoreToggle = true;
                    }
                    continue;

                case "color":
                    currentCulture.Color =
                        LoadMethods.ParseColor32(commentSplit.Substring(equalsSplit.Length + 1));
                    continue;

                case "leader":
                case "unit":
                    continue;

                case "radicalism":
                    if (!float.TryParse(commentSplit.Substring(equalsSplit.Length + 1), out var radical))
                    {
                        throw new Exception("Unknown radicalism: " +
                                            commentSplit.Substring(equalsSplit.Length + 1));
                    }

                    currentCulture.Radicalism = radical;
                    continue;

                case "primary":
                    currentCulture.Primary =
                        LookupDictionaries.CountryTags[commentSplit.Substring(equalsSplit.Length + 1).Trim()];
                    continue;
                }

                if (!commentSplit.Contains("}"))
                {
                    continue;
                }

                if (cultureToggle)
                {
                    cultureToggle = false;
                    var targetCulture = em.CreateEntity(typeof(CultureEntity));
                    em.SetComponentData(targetCulture, currentCulture);

                    cultures.Add(currentCulture);
                    continue;
                }

                groupToggle = false;
            }

            File.WriteAllBytes(Path.Combine(Application.streamingAssetsPath, "JsonData", "cultures.txt"),
                               LoadMethods.Zip(JsonUtility.ToJson(
                                                   new CulturesOutput(cultureNames, cultureGroupNames, cultures))));

            FileUnpacker.GetCollector <CultureCollection>();

            return(cultureNames, cultureGroupNames);
        }
Esempio n. 11
0
        public static (Entity, Entity, Entity, List <List <IncompleteInventions> >) Main(ref StringBox stringBox)
        {
            var folderNames     = new List <string>();
            var areaNames       = new List <string>();
            var schoolNames     = new List <string>();
            var technologyNames = new List <string>();

            var techLookup              = new Dictionary <string, int>();
            var areaLookup              = new Dictionary <string, int>();
            var foldersLookup           = new Dictionary <string, int>();
            var schoolReadBeforeFolders = new Queue <string>();
            var schoolQueueing          = false;

            var folders      = new NativeList <EntityWrapper>(Allocator.Temp);
            var schools      = new NativeList <EntityWrapper>(Allocator.Temp);
            var areas        = new NativeList <EntityWrapper>(Allocator.Temp);
            var technologies = new NativeList <EntityWrapper>(Allocator.Temp);

            var currentUpper  = CurrentUpper.None;
            var lowerToggle   = false;
            var em            = World.Active.EntityManager;
            var currentFolder = new Entity();
            var currentSchool = new Entity();

            using (var tempAreas = new NativeList <EntityWrapper>(Allocator.Temp))
                using (var tempSchoolValues = new NativeList <DataValue>(Allocator.Temp))
                {
                    foreach (var rawLine in File.ReadLines(Path.Combine(Application.streamingAssetsPath,
                                                                        "Common", "technology.txt")))
                    {
                        if (LoadMethods.CommentDetector(rawLine, out var line))
                        {
                            continue;
                        }

                        ParseCommonTechFile(line);
                    }

                    while (schoolReadBeforeFolders.Any())
                    {
                        ParseCommonTechFile(schoolReadBeforeFolders.Dequeue());
                    }

                    void ParseCommonTechFile(string line)
                    {
                        if (schoolQueueing)
                        {
                            // Buffer school section until exit.
                            // Folder section contains critical info needed for schools parsing.

                            if (line.Contains("{"))
                            {
                                if (!lowerToggle)
                                {
                                    lowerToggle = true;
                                }
                                else
                                {
                                    throw new Exception("Exceeded maximum nesting in Common/technology.txt.");
                                }
                            }

                            if (line.Contains("}"))
                            {
                                if (lowerToggle)
                                {
                                    lowerToggle = false;
                                }
                                else
                                {
                                    schoolQueueing = false;
                                }
                            }

                            schoolReadBeforeFolders.Enqueue(line);
                            return;
                        }

                        var preEquals = Regex.Match(line, @"^.+?(?=\=)");

                        switch (currentUpper)
                        {
                        case CurrentUpper.None:
                            switch (preEquals.Value.Trim())
                            {
                            case "folders":
                                currentUpper = CurrentUpper.Folder;
                                break;

                            case "schools":
                                if (folders.Length < 1)
                                {
                                    schoolQueueing = true;
                                    schoolReadBeforeFolders.Enqueue(line);
                                    return;
                                }

                                for (var i = 0; i < folders.Length; i++)
                                {
                                    foldersLookup.Add(folderNames[i], i);
                                }

                                currentUpper = CurrentUpper.Schools;
                                break;

                            default:
                                throw new NotImplementedException("Unknown tech type: " + line);
                            }

                            break;

                        case CurrentUpper.Folder:
                            if (!lowerToggle)
                            {
                                if (line.Contains("}"))
                                {
                                    break;
                                }

                                lowerToggle   = true;
                                currentFolder = em.CreateEntity(typeof(FolderEntity));
                                em.SetComponentData(currentFolder, new FolderEntity {
                                    Index = folderNames.Count
                                });
                                folderNames.Add(preEquals.Value.Trim());
                                break;
                            }

                            if (preEquals.Success)
                            {
                                throw new Exception("Invalid equals detected! " + line);
                            }

                            var newFolderEntry = line.Replace("}", "").Trim();

                            if (newFolderEntry == string.Empty)
                            {
                                break;
                            }

                            areaLookup.Add(newFolderEntry, areaNames.Count);
                            var targetArea = em.CreateEntity(typeof(AreaEntity));
                            em.SetComponentData(targetArea,
                                                new AreaEntity {
                                Index = areaNames.Count, Folder = currentFolder
                            });
                            tempAreas.Add(targetArea);
                            areas.Add(targetArea);
                            areaNames.Add(newFolderEntry);
                            break;

                        case CurrentUpper.Schools:
                            if (!lowerToggle)
                            {
                                if (line.Contains("}"))
                                {
                                    break;
                                }

                                lowerToggle = true;

                                currentSchool = em.CreateEntity(typeof(SchoolEntity));
                                em.SetComponentData(currentSchool, new SchoolEntity {
                                    Index = schoolNames.Count
                                });
                                schoolNames.Add(preEquals.Value.Trim());
                                break;
                            }

                            var newSchoolEntry = preEquals.Value.Replace("}", "").Trim();

                            if (newSchoolEntry == string.Empty)
                            {
                                break;
                            }

                            int assignedNumber;
                            if (!Enum.TryParse(newSchoolEntry.Replace("_", ""),
                                               true, out LoadVariables foundVar))
                            {
                                if (!foldersLookup.TryGetValue(
                                        Regex.Match(newSchoolEntry, @"^.+?(?=_research_bonus)").Value,
                                        out var folderIndex))
                                {
                                    throw new Exception("Unknown folder _research_bonus: " + newSchoolEntry);
                                }
                                assignedNumber = folderIndex + (int)MagicUnifiedNumbers.ResearchBonus;
                            }
                            else
                            {
                                assignedNumber = (int)foundVar;
                            }

                            if (!float.TryParse(line.Substring(preEquals.Length + 1), out var schoolValue))
                            {
                                throw new Exception("Unknown float value. " + line.Substring(preEquals.Length + 1));
                            }

                            if (math.abs(schoolValue) < 0.01)
                            {
                                break;
                            }

                            tempSchoolValues.Add(new DataValue(assignedNumber, schoolValue));
                            break;
                        }

                        if (!line.Contains("}"))
                        {
                            return;
                        }

                        if (lowerToggle)
                        {
                            lowerToggle = false;
                            if (currentUpper == CurrentUpper.Schools)
                            {
                                em.AddBuffer <DataValue>(currentSchool).AddRange(tempSchoolValues);
                                tempSchoolValues.Clear();
                                schools.Add(currentSchool);
                            }
                            else
                            {
                                // Folders
                                em.AddBuffer <EntityWrapper>(currentFolder).AddRange(tempAreas);
                                tempAreas.Clear();
                                folders.Add(currentFolder);
                            }
                        }
                        else
                        {
                            currentUpper = CurrentUpper.None;
                        }
                    }
                }

            // Actual tech parsing now
            stringBox.SchoolNames = schoolNames;
            stringBox.FolderNames = folderNames;
            stringBox.AreaNames   = areaNames;

            var allTechInventions = new List <List <IncompleteInventions> >();

            foreach (var techPath in Directory.GetFiles(Path.Combine(Application.streamingAssetsPath, "Technologies"),
                                                        "*.txt"))
            {
                if (!foldersLookup.TryGetValue(Path.GetFileNameWithoutExtension(techPath), out _))
                {
                    throw new Exception("Unknown tech folder type! " + techPath);
                }

                var fileTree = new List <KeyValuePair <int, object> >();
                var values   = new List <string>();

                FileUnpacker.ParseFile(techPath, fileTree, values, TechMagicOverride);

                using (var parentLocation = new NativeMultiHashMap <int, int>(10, Allocator.TempJob))
                {
                    foreach (var technology in fileTree)
                    {
                        var techRanges     = new List <DataRange>();
                        var techActions    = new List <DataValue>();
                        var passInventions = new List <IncompleteInventions>();

                        parentLocation.Add(technology.Key, techRanges.Count);
                        techRanges.Add(new DataRange(technology.Key, -1, -1));

                        var currentTechnology = new TechnologyEntity
                        {
                            Index = technologyNames.Count,
                            Year  = -1
                        };

                        technologyNames.Add(values[technology.Key - (int)MagicUnifiedNumbers.Technology]);

                        FileUnpacker.ProcessQueue(technology, techActions, techRanges,
                                                  parentLocation, values, TechSwitchOverride);

                        var targetTechnology = em.CreateEntity(typeof(TechnologyEntity));
                        em.SetComponentData(targetTechnology, currentTechnology);
                        em.AddBuffer <EntityWrapper>(targetTechnology); // Inventions associated with technology.
                        technologies.Add(targetTechnology);

                        using (var tempRange = new NativeArray <DataRange>(techRanges.ToArray(), Allocator.Temp))
                        {
                            em.AddBuffer <DataRange>(targetTechnology).AddRange(tempRange);
                        }

                        using (var tempValues = new NativeArray <DataValue>(techActions.ToArray(), Allocator.Temp))
                        {
                            em.AddBuffer <DataValue>(targetTechnology).AddRange(tempValues);
                        }

                        allTechInventions.Add(passInventions);

                        bool TechSwitchOverride(string targetStr, KeyValuePair <int, object> target)
                        {
                            switch ((LoadVariables)target.Key)
                            {
                            case LoadVariables.Area:
                                if (!areaLookup.TryGetValue(targetStr, out var areaIndex))
                                {
                                    throw new Exception("Unknown area. " + targetStr);
                                }

                                currentTechnology.Area = areas[areaIndex];
                                return(true);

                            case LoadVariables.Year:
                                if (!int.TryParse(targetStr, out var year))
                                {
                                    throw new Exception("Unknown year. " + targetStr);
                                }

                                if (currentTechnology.Year == -1)
                                {
                                    currentTechnology.Year = year;
                                }
                                else
                                {
                                    techActions.Add(new DataValue(target.Key, year));
                                }

                                return(true);

                            case LoadVariables.Cost:
                                if (!int.TryParse(targetStr, out var cost))
                                {
                                    throw new Exception("Unknown cost. " + targetStr);
                                }

                                currentTechnology.Cost = cost;
                                return(true);

                            case LoadVariables.Invention:     // Inventions are completed after inventions are parsed
                                passInventions.Add(new IncompleteInventions(targetStr, techActions.Count));
                                techActions.Add(new DataValue((int)LoadVariables.Invention, -1));
                                return(true);

                            default:
                                return(false);
                            }
                        }
                    }
                }

                int TechMagicOverride(int parent, string str)
                {
                    if (parent == -1)
                    {
                        values.Add(str);
                        techLookup.Add(str, values.Count - 1);
                        return((int)MagicUnifiedNumbers.Technology + values.Count - 1);
                    }

                    // Previous technology
                    if (techLookup.TryGetValue(str, out var techIndex))
                    {
                        return(techIndex + (int)MagicUnifiedNumbers.Technology);
                    }

                    return((int)MagicUnifiedNumbers.ContinueMagicNumbers);
                }
            }

            stringBox.TechNames = technologyNames;

            var techCollector = FileUnpacker.GetCollector <TechnologyCollection>(technologies);

            technologies.Dispose();

            var schoolCollector = FileUnpacker.GetCollector <SchoolCollection>(schools);

            schools.Dispose();

            var folderCollector = FileUnpacker.GetCollector <FolderCollection>(folders);

            folders.Dispose();

            return(techCollector, schoolCollector, folderCollector, allTechInventions);
        }
Esempio n. 12
0
        public static (Entity, List <string>) Main()
        {
            // Output Arrays
            var unitNames = new List <string>();
            var units     = new NativeList <EntityWrapper>(Allocator.Temp);

            var em = World.Active.EntityManager;

            using (var generalList = new NativeList <DataValue>(Allocator.Temp))
                using (var goodsList = new NativeList <DataGood>(Allocator.Temp))
                {
                    foreach (var unitPaths in Directory.EnumerateFiles(Path.Combine(Application.streamingAssetsPath,
                                                                                    "Units")))
                    {
                        // Resetting fileTree and values
                        var fileTree = new List <KeyValuePair <int, object> >();
                        var values   = new List <string>();

                        FileUnpacker.ParseFile(unitPaths, fileTree, values, UnitsMagicOverride);

                        foreach (var unit in fileTree)
                        {
                            var currentEntity = units[unit.Key - (int)MagicUnifiedNumbers.Unit];
                            var currentUnit   = new UnitEntity {
                                Index = unit.Key - (int)MagicUnifiedNumbers.Unit
                            };

                            foreach (var quality in (List <KeyValuePair <int, object> >)unit.Value)
                            {
                                // TODO: Possible conversion to UnifiedVariables?
                                switch ((LoadVariables)quality.Key)
                                {
                                case LoadVariables.UnitType:
                                case LoadVariables.Type:
                                    if (!Enum.TryParse(values[(int)quality.Value].Replace("_", ""), true,
                                                       out UnitTypes unitType))
                                    {
                                        throw new Exception("Unknown unit type: " + values[(int)quality.Value]);
                                    }
                                    generalList.Add(new DataValue(quality.Key, (int)unitType));
                                    break;

                                case LoadVariables.Capital:
                                    generalList.Add(new DataValue(quality.Key,
                                                                  LoadMethods.YesNoConverter(values[(int)quality.Value]) ? 1f : 0f));
                                    break;

                                case LoadVariables.Priority:
                                case LoadVariables.MaxStrength:
                                case LoadVariables.DefaultOrganisation:
                                case LoadVariables.WeightedValue:
                                case LoadVariables.MaximumSpeed:
                                case LoadVariables.ColonialPoints:
                                    if (!float.TryParse(values[(int)quality.Value], out var coreFloat))
                                    {
                                        throw new Exception("Unknown core float: " + values[(int)quality.Value]);
                                    }
                                    generalList.Add(new DataValue(quality.Key, coreFloat));
                                    break;

                                case LoadVariables.LimitPerPort:
                                case LoadVariables.MinPortLevel:
                                case LoadVariables.BuildTime:
                                    if (!float.TryParse(values[(int)quality.Value], out var buildFloat))
                                    {
                                        throw new Exception("Unknown build float: " + values[(int)quality.Value]);
                                    }
                                    generalList.Add(new DataValue(quality.Key, buildFloat));
                                    break;

                                case LoadVariables.CanBuildOverseas:
                                    generalList.Add(new DataValue(quality.Key,
                                                                  LoadMethods.YesNoConverter(values[(int)quality.Value]) ? 1f : 0f));
                                    break;

                                case LoadVariables.PrimaryCulture:
                                    generalList.Add(new DataValue(quality.Key,
                                                                  LoadMethods.YesNoConverter(values[(int)quality.Value]) ? 1f : 0f));
                                    generalList.Add(new DataValue(quality.Key,
                                                                  LoadMethods.YesNoConverter(values[(int)quality.Value]) ? 1f : 0f));
                                    break;

                                case LoadVariables.SupplyConsumptionScore:
                                case LoadVariables.SupplyConsumption:
                                    if (!float.TryParse(values[(int)quality.Value], out var supplyFloat))
                                    {
                                        throw new Exception("Unknown supply float: " + values[(int)quality.Value]);
                                    }
                                    generalList.Add(new DataValue(quality.Key, supplyFloat));
                                    break;

                                case LoadVariables.Reconnaissance:
                                case LoadVariables.Attack:
                                case LoadVariables.Defence:
                                case LoadVariables.Discipline:
                                case LoadVariables.Support:
                                case LoadVariables.Maneuver:
                                case LoadVariables.Siege:
                                case LoadVariables.Hull:
                                case LoadVariables.GunPower:
                                case LoadVariables.FireRange:
                                case LoadVariables.Evasion:
                                case LoadVariables.TorpedoAttack:
                                    if (!float.TryParse(values[(int)quality.Value], out var abilityFloat))
                                    {
                                        throw new Exception("Unknown ability float: " + values[(int)quality.Value]);
                                    }
                                    generalList.Add(new DataValue(quality.Key, abilityFloat));
                                    break;

                                case LoadVariables.BuildCost:
                                    if (!(quality.Value is List <KeyValuePair <int, object> > buildCostActual))
                                    {
                                        throw new Exception("Unknown build cost.");
                                    }

                                    foreach (var goodKvp in buildCostActual)
                                    {
                                        if (!float.TryParse(values[(int)goodKvp.Value], out var buildCostFloat))
                                        {
                                            throw new Exception(
                                                      "Unknown buildCost float: " + values[(int)goodKvp.Value]);
                                        }
                                        goodsList.Add(new DataGood(goodKvp.Key, buildCostFloat));
                                    }

                                    currentUnit.BuildCost = goodsList.Length;
                                    break;

                                case LoadVariables.SupplyCost:
                                    if (!(quality.Value is List <KeyValuePair <int, object> > supplyCostActual))
                                    {
                                        throw new Exception("Unknown supply cost.");
                                    }

                                    foreach (var goodKvp in supplyCostActual)
                                    {
                                        if (!float.TryParse(values[(int)goodKvp.Value], out var supplyCostFloat))
                                        {
                                            throw new Exception(
                                                      "Unknown supplyCost float: " + values[(int)goodKvp.Value]);
                                        }
                                        goodsList.Add(new DataGood(goodKvp.Key, supplyCostFloat));
                                    }

                                    currentUnit.SupplyCost = goodsList.Length;
                                    break;
                                }
                            }

                            em.AddBuffer <DataValue>(currentEntity).AddRange(generalList);
                            generalList.Clear();

                            em.AddBuffer <DataGood>(currentEntity).AddRange(goodsList);
                            goodsList.Clear();

                            em.SetComponentData(currentEntity, currentUnit);
                        }

                        int UnitsMagicOverride(int parent, string str)
                        {
                            if (parent != -1)
                            {
                                return((int)MagicUnifiedNumbers.ContinueMagicNumbers);
                            }

                            units.Add(em.CreateEntity(typeof(UnitEntity)));

                            unitNames.Add(str);
                            return((int)MagicUnifiedNumbers.Unit + unitNames.Count - 1);
                        }
                    }
                }

            var unitCollectorEntity = FileUnpacker.GetCollector <UnitCollection>(units);

            units.Dispose();

            return(unitCollectorEntity, unitNames);
        }
Esempio n. 13
0
        PolicyNames()
        {
            // Exports first policy names
            var fileTree = new List <KeyValuePair <int, object> >();
            var values   = new List <string>();

            var policyGroups      = new NativeList <EntityWrapper>(Allocator.Temp);
            var subPolicies       = new NativeList <EntityWrapper>(Allocator.Temp);
            var policyGroupNames  = new List <string>();
            var subPolicyNames    = new List <string>();
            var policyGroupLookup = new Dictionary <string, int>();

            var em = World.Active.EntityManager;

            FileUnpacker.ParseFile(Path.Combine(Application.streamingAssetsPath, "Common", "issues.txt"),
                                   fileTree, values, IssueMagicOverride);

            var policyGroupCollectorEntity = FileUnpacker.GetCollector <SubPolicyCollection>(policyGroups);

            policyGroups.Dispose();

            var subPolicyCollectorEntity = FileUnpacker.GetCollector <PolicyGroupCollection>(subPolicies);

            subPolicies.Dispose();

            return(fileTree, values, subPolicyCollectorEntity, policyGroupCollectorEntity, subPolicyNames,
                   policyGroupNames);

            // Assigns magic numbers.
            int IssueMagicOverride(int parent, string str)
            {
                // Following passes into SubPolicies due to being in same level as actual sub policies
                if (str.Equals("next_step_only") || str.Equals("administrative"))
                {
                    return((int)MagicUnifiedNumbers.ContinueMagicNumbers);
                }

                if (policyGroupLookup.TryGetValue(str, out var policyIndex))
                {
                    return(policyIndex + (int)MagicUnifiedNumbers.PolicyGroup);
                }

                if (parent < (int)LoadVariables.BreakPoliciesEnd && parent > (int)LoadVariables.BreakPoliciesStart)
                {
                    policyGroupLookup.Add(str, policyGroupNames.Count);
                    // Entity setting is done in Main().
                    policyGroups.Add(em.CreateEntity(typeof(PolicyGroupEntity)));
                    policyGroupNames.Add(str);
                    return((int)MagicUnifiedNumbers.PolicyGroup + policyGroupNames.Count - 1);
                }

                if (parent / 10000 == (int)MagicUnifiedNumbers.PolicyGroup / 10000)
                {
                    subPolicies.Add(em.CreateEntity(typeof(SubPolicyEntity)));
                    subPolicyNames.Add(str);
                    return((int)MagicUnifiedNumbers.SubPolicy + subPolicyNames.Count - 1);
                }

                return((int)MagicUnifiedNumbers.ContinueMagicNumbers);
            }
        }
Esempio n. 14
0
        public static (Entity, string[]) Main(Entity technologies, Entity inventions,
                                              Entity cultures, Entity ideologies, Entity subPolicies, Entity governments,
                                              Entity nationalValues)
        {
            var allCountries     = new NativeArray <EntityWrapper>(LookupDictionaries.CountryTags.Count, Allocator.Temp);
            var em               = World.Active.EntityManager;
            var countryArchetype = em.CreateArchetype(typeof(CountryPopulationComponent),
                                                      typeof(CountryPoliticsComponent), typeof(CountryTechnologyComponent));
            var rulingParties = new string[LookupDictionaries.CountryTags.Count];

            var countryPolicies =
                new NativeArray <CountryPolicies>(LookupDictionaries.PolicyGroups.Count, Allocator.Temp);

            using (var nationalValueList = em.GetBuffer <EntityWrapper>(nationalValues).ToNativeArray(Allocator.Temp))
                using (var governmentList = em.GetBuffer <EntityWrapper>(governments).ToNativeArray(Allocator.Temp))
                    using (var subPolicyList = em.GetBuffer <EntityWrapper>(subPolicies).ToNativeArray(Allocator.Temp))
                        using (var ideologyList = em.GetBuffer <EntityWrapper>(ideologies).ToNativeArray(Allocator.Temp))
                            using (var inventionList = em.GetBuffer <EntityWrapper>(inventions).ToNativeArray(Allocator.Temp))
                                using (var cultureList = em.GetBuffer <EntityWrapper>(cultures).ToNativeArray(Allocator.Temp))
                                    using (var technologyList = em.GetBuffer <EntityWrapper>(technologies).ToNativeArray(Allocator.Temp))
                                        using (var countryUpperHouse = new NativeList <CountryUpperHouse>(Allocator.Temp))
                                            using (var countryInventions = new NativeList <CountryInventions>(Allocator.Temp))
                                                using (var countryTechnologies = new NativeList <CountryTechnologies>(Allocator.Temp))
                                                    using (var countryCultures = new NativeList <CountryCultures>(Allocator.Temp))
                                                    {
                                                        foreach (var countryFile in Directory.EnumerateFiles(
                                                                     Path.Combine(Application.streamingAssetsPath, "History", "countries"), "*.txt"))
                                                        {
                                                            var fileTree = new List <KeyValuePair <int, object> >();
                                                            var values   = new List <string>();

                                                            FileUnpacker.ParseFile(countryFile, fileTree, values, CountryHistoryMagicOverride);

                                                            var countryTag = Regex.Match(Path.GetFileNameWithoutExtension(countryFile) ?? "", @"^.+?(?=\-)")
                                                                             .Value
                                                                             .Trim().ToLower();
                                                            if (!LookupDictionaries.CountryTags.TryGetValue(countryTag, out var countryIndex))
                                                            {
                                                                continue;
                                                            }

                                                            var countryEntity = em.CreateEntity(countryArchetype);

                                                            var currentCountry = new CountryEntity {
                                                                Index = countryIndex
                                                            };
                                                            var currentPopulation = new CountryPopulationComponent();
                                                            var currentPolitics   = new CountryPoliticsComponent();
                                                            var currentTechnology = new CountryTechnologyComponent();
                                                            // Resetting polices
                                                            for (var index = 0; index < countryPolicies.Length; index++)
                                                            {
                                                                countryPolicies[index] = Entity.Null;
                                                            }

                                                            foreach (var target in fileTree)
                                                            {
                                                                var targetStr = target.Key < (int)LoadVariables.BreakCore
                            ? values[(int)target.Value]
                            : string.Empty;

                                                                switch ((LoadVariables)target.Key)
                                                                {
                                                                case LoadVariables.Capital:
                                                                    currentPolitics.Capital = int.Parse(targetStr);
                                                                    break;

                                                                case LoadVariables.RulingParty:
                                                                    rulingParties[countryIndex] = targetStr;
                                                                    break;

                                                                case LoadVariables.UpperHouse:
                                                                    foreach (var ideology in (List <KeyValuePair <int, object> >)target.Value)
                                                                    {
                                                                        if (!float.TryParse(values[(int)ideology.Value], out var ideologyPercentage))
                                                                        {
                                                                            throw new Exception("Country ideology parsing failed! " +
                                                                                                values[(int)ideology.Value]);
                                                                        }

                                                                        if (ideologyPercentage > 0.01)
                                                                        {
                                                                            countryUpperHouse.Add(
                                                                                new CountryUpperHouse(
                                                                                    ideologyList[ideology.Key - (int)MagicUnifiedNumbers.Ideology],
                                                                                    ideologyPercentage));
                                                                        }
                                                                    }

                                                                    break;

                                                                case LoadVariables.Government:
                                                                    if (!LookupDictionaries.Governments.TryGetValue(targetStr, out var governmentIndex))
                                                                    {
                                                                        throw new Exception("Unknown government. " + targetStr);
                                                                    }

                                                                    currentPolitics.Government = governmentList[governmentIndex];
                                                                    break;

                                                                case LoadVariables.Prestige:
                                                                    currentPolitics.Prestige = int.Parse(targetStr);
                                                                    break;

                                                                case LoadVariables.Civilized:
                                                                    currentTechnology.Civilized = LoadMethods.YesNoConverter(targetStr);
                                                                    break;

                                                                case LoadVariables.NonStateCultureLiteracy:
                                                                    currentTechnology.NonStateCultureLiteracy = int.Parse(targetStr);
                                                                    break;

                                                                case LoadVariables.Literacy:
                                                                    currentTechnology.Literacy = int.Parse(targetStr);
                                                                    break;

                                                                case LoadVariables.Plurality:
                                                                    currentTechnology.Plurality = int.Parse(targetStr);
                                                                    break;

                                                                case LoadVariables.Consciousness:
                                                                    currentPopulation.Consciousness = int.Parse(targetStr);
                                                                    break;

                                                                case LoadVariables.NonStateConsciousness:
                                                                    currentPopulation.NonStateConsciousness = int.Parse(targetStr);
                                                                    break;

                                                                case LoadVariables.PrimaryCulture:
                                                                    if (!LookupDictionaries.Cultures.TryGetValue(targetStr, out var primaryCultureIndex))
                                                                    {
                                                                        throw new Exception("Unknown primary culture. " + targetStr);
                                                                    }

                                                                    currentPopulation.PrimaryCulture = cultureList[primaryCultureIndex];
                                                                    break;

                                                                case LoadVariables.NationalValue:
                                                                    if (!LookupDictionaries.NationalValues.TryGetValue(targetStr, out var natValIndex))
                                                                    {
                                                                        throw new Exception("Unknown national value. " + targetStr);
                                                                    }

                                                                    currentPopulation.NationalValue = nationalValueList[natValIndex];
                                                                    break;

                                                                case LoadVariables.Culture:
                                                                    if (!LookupDictionaries.Cultures.TryGetValue(targetStr, out var cultureIndex))
                                                                    {
                                                                        throw new Exception("Unknown culture. " + targetStr);
                                                                    }

                                                                    countryCultures.Add(cultureList[cultureIndex]);
                                                                    break;

                                                                case LoadVariables.ForeignInvestment:
                                                                case LoadVariables.Oob:
                                                                case LoadVariables.Decision:
                                                                    // Skipping
                                                                    break;

                                                                default:
                                                                    switch ((MagicUnifiedNumbers)(target.Key / 10000 * 10000))
                                                                    {
                                                                    case MagicUnifiedNumbers.Placeholder:
                                                                        break;

                                                                    case MagicUnifiedNumbers.Invention:
                                                                        countryInventions.Add(
                                                                            new CountryInventions(
                                                                                inventionList[target.Key - (int)MagicUnifiedNumbers.Invention],
                                                                                LoadMethods.YesNoConverter(values[(int)target.Value])));
                                                                        break;

                                                                    case MagicUnifiedNumbers.Technology:
                                                                        countryTechnologies.Add(technologyList[target.Key - (int)MagicUnifiedNumbers.Technology]);
                                                                        break;

                                                                    case MagicUnifiedNumbers.PolicyGroup:
                                                                        if (!LookupDictionaries.SubPolicies.TryGetValue(values[(int)target.Value],
                                                                                                                        out var subPolicyIndex))
                                                                        {
                                                                            throw new Exception("Unknown policy group. " + values[(int)target.Value]);
                                                                        }

                                                                        countryPolicies[countryIndex * LookupDictionaries.PolicyGroups.Count
                                                                                        + (target.Key - (int)MagicUnifiedNumbers.PolicyGroup)]
                                                                            = subPolicyList[subPolicyIndex];
                                                                        break;
                                                                    }

                                                                    Debug.LogWarning("Uncaught load variable on country history load "
                                                                                     + (LoadVariables)target.Key);
                                                                    break;
                                                                }
                                                            }

                                                            em.SetComponentData(countryEntity, currentCountry);
                                                            em.SetComponentData(countryEntity, currentPopulation);
                                                            em.SetComponentData(countryEntity, currentPolitics);
                                                            em.SetComponentData(countryEntity, currentTechnology);

                                                            em.AddBuffer <CountryUpperHouse>(countryEntity).AddRange(countryUpperHouse);
                                                            countryUpperHouse.Clear();
                                                            em.AddBuffer <CountryTechnologies>(countryEntity).AddRange(countryTechnologies);
                                                            countryTechnologies.Clear();
                                                            em.AddBuffer <CountryInventions>(countryEntity).AddRange(countryInventions);
                                                            countryInventions.Clear();
                                                            em.AddBuffer <CountryCultures>(countryEntity).AddRange(countryCultures);
                                                            countryCultures.Clear();
                                                            em.AddBuffer <CountryPolicies>(countryEntity).AddRange(countryPolicies);

                                                            allCountries[countryIndex] = countryEntity;
                                                        }
                                                    }
            // Not in using statement as the values are mutable.
            countryPolicies.Dispose();

            var countryCollector = FileUnpacker.GetCollector <CountryCollection>(allCountries);

            allCountries.Dispose();

            return(countryCollector, rulingParties);

            int CountryHistoryMagicOverride(int parent, string target)
            {
                // Skipping other start dates
                return(Regex.IsMatch(target, @"\d+")
                    ? (int)MagicUnifiedNumbers.Placeholder
                    : (int)MagicUnifiedNumbers.ContinueMagicNumbers);
            }
        }
Esempio n. 15
0
        public static (Entity, List <string>) Main()
        {
            var governments     = new NativeList <EntityWrapper>(Allocator.Temp);
            var governmentNames = new List <string>();

            var fileTree = new List <KeyValuePair <int, object> >();
            var values   = new List <string>();

            var em = World.Active.EntityManager;

            FileUnpacker.ParseFile(Path.Combine(Application.streamingAssetsPath, "Common", "governments.txt"), fileTree,
                                   values, GovernmentMagicOverride);

            using (var governIdeologies = new NativeList <DataInt>(Allocator.Temp))
            {
                for (var index = 0; index < fileTree.Count; index++)
                {
                    var currentEntity     = governments[index];
                    var currentGovernment = new GovernmentEntity
                    {
                        Index = fileTree[index].Key - (int)MagicUnifiedNumbers.Placeholder
                    };

                    foreach (var govProp in (List <KeyValuePair <int, object> >)fileTree[index].Value)
                    {
                        var targetStr = values[(int)govProp.Value];
                        switch (govProp.Key / 10000)
                        {
                        case 0:
                            switch ((LoadVariables)govProp.Key)
                            {
                            case LoadVariables.AppointRulingParty:
                                currentGovernment.AppointRulingParty = LoadMethods.YesNoConverter(targetStr);
                                break;

                            case LoadVariables.Election:
                                currentGovernment.Election = LoadMethods.YesNoConverter(targetStr);
                                break;

                            case LoadVariables.Duration:         // Election cycle
                                if (!int.TryParse(targetStr, out var duration))
                                {
                                    throw new Exception("Unknown government duration. " + targetStr);
                                }

                                currentGovernment.Duration = duration;
                                break;

                            case LoadVariables.FlagType:
                                if (!Enum.TryParse(targetStr, true, out GovernmentEntity.Flag flagType))
                                {
                                    throw new Exception("Unknown government flag type. " + targetStr);
                                }

                                currentGovernment.FlagType = flagType;
                                break;

                            default:
                                throw new Exception("Invalid government file structure. " +
                                                    (LoadVariables)govProp.Key);
                            }

                            break;

                        case (int)MagicUnifiedNumbers.Ideology / 10000:
                            if (LoadMethods.YesNoConverter(targetStr))
                            {
                                governIdeologies.Add(govProp.Key - (int)MagicUnifiedNumbers.Ideology);
                            }
                            break;

                        default:
                            throw new Exception("Invalid magic number detected in governments.");
                        }
                    }

                    em.AddBuffer <DataInt>(currentEntity).AddRange(governIdeologies);
                    governIdeologies.Clear();
                    em.SetComponentData(currentEntity, currentGovernment);
                }
            }

            var governmentCollectorEntity = FileUnpacker.GetCollector <GovernmentCollection>(governments);

            governments.Dispose();

            return(governmentCollectorEntity, governmentNames);

            int GovernmentMagicOverride(int parent, string raw)
            {
                if (parent != -1)
                {
                    return((int)MagicUnifiedNumbers.ContinueMagicNumbers);
                }

                governments.Add(em.CreateEntity(typeof(GovernmentEntity)));

                governmentNames.Add(raw);
                // Government is used as a color override.
                return((int)MagicUnifiedNumbers.Placeholder + governmentNames.Count - 1);
            }
        }
Esempio n. 16
0
        // Used by event modifiers and national values.
        public static (Entity, List <string>) Main <TEntity, TCollection>(IEnumerable <string> paths,
                                                                          Action <Entity, int> setEntityIndex)
        {
            var fileTree = new List <KeyValuePair <int, object> >();
            var values   = new List <string>();

            var names    = new List <string>();
            var entities = new NativeList <EntityWrapper>(Allocator.Temp);

            var em = World.Active.EntityManager;

            foreach (var path in paths)
            {
                FileUnpacker.ParseFile(path, fileTree, values, NationalValueMagicOverride);
            }

            using (var parentLocation = new NativeMultiHashMap <int, int>(1, Allocator.Temp))
            {
                foreach (var nodeKvP in fileTree)
                {
                    var ranges  = new List <DataRange>();
                    var actions = new List <DataValue>();

                    parentLocation.Add(nodeKvP.Key, ranges.Count);
                    ranges.Add(new DataRange(nodeKvP.Key, -1, -1));

                    FileUnpacker.ProcessQueue(nodeKvP, actions, ranges,
                                              parentLocation, values, (s, pair) => false);

                    if (ranges.Count > 2) // 1 is throwaway. 2 is BreakCore. There can not be a third.
                    {
                        throw new Exception("Invalid nested value in Event Modifiers or National Values!"
                                            + (LoadVariables)ranges[2].Type);
                    }

                    var currentValue = em.CreateEntity(typeof(TEntity));
                    setEntityIndex(currentValue, nodeKvP.Key - (int)MagicUnifiedNumbers.Placeholder);

                    using (var tempValue = new NativeArray <DataValue>(actions.ToArray(), Allocator.Temp))
                    {
                        em.AddBuffer <DataValue>(currentValue).AddRange(tempValue);
                    }

                    entities.Add(currentValue);
                }
            }

            var collector = FileUnpacker.GetCollector <TCollection>(entities);

            entities.Dispose();

            return(collector, names);

            int NationalValueMagicOverride(int parent, string str)
            {
                if (parent != -1)
                {
                    return((int)MagicUnifiedNumbers.ContinueMagicNumbers);
                }

                names.Add(str);
                return((int)MagicUnifiedNumbers.Placeholder + names.Count - 1);
            }
        }
Esempio n. 17
0
        public static void Main()
        {
            // TODO: Needs policies and ideologies.

            // Output events list.
            var events = new List <GameEventInfo>();

            // Collapse tree into arrays
            var eventRanges = new List <int3>(); // x: type. z: start index, inclusive. w: end index, exclusive
            // If type == random_list, x is replaced with chance.
            // Value arrays
            var eventActions = new List <float2>(); // x: type. z: threshold
            var stringValues = new List <string>();

            // TODO: Possibly convert all disposes of parent location to using?
            var parentLocation = new NativeMultiHashMap <int, int>(10, Allocator.TempJob);

            foreach (var eventFile in Directory.EnumerateFiles(Path.Combine(Application.streamingAssetsPath, "Events"),
                                                               "*.txt"))
            {
                var fileTree = new List <KeyValuePair <int, object> >();
                var values   = new List <string>();

                FileUnpacker.ParseFile(eventFile, fileTree, values, EventMagicOverride);

                GameEventInfo currentEvent;

                foreach (var parsedEvent in fileTree)
                {
                    currentEvent = new GameEventInfo {
                        Fired = false, Index = eventRanges.Count
                    };
                    parentLocation.Add(parsedEvent.Key, eventRanges.Count);
                    eventRanges.Add(new int3(parsedEvent.Key, -1, -1));

                    //FileUnpacker.ProcessQueue(parsedEvent, eventActions, eventRanges,
                    //parentLocation, values, EventSwitchOverride);

                    events.Add(currentEvent);
                }

                bool EventSwitchOverride(string targetStr, KeyValuePair <int, object> kvpObject)
                {
                    switch ((LoadVariables)kvpObject.Key)
                    {
                    case LoadVariables.FireOnlyOnce:
                        currentEvent.FireOnlyOnce = LoadMethods.YesNoConverter(targetStr);
                        return(true);

                    case LoadVariables.ChangeRegionName:
                    case LoadVariables.ChangeProvinceName:
                    case LoadVariables.Title:
                    case LoadVariables.Desc:
                    case LoadVariables.Picture:
                    case LoadVariables.Name:
                        eventActions.Add(new float2(kvpObject.Key, stringValues.Count));
                        stringValues.Add(targetStr.Replace("\"", ""));
                        return(true);

                    case LoadVariables.HasLeader:     // String
                        // Skipping
                        return(true);

                    default:
                        return(false);
                    }
                }

                // Assigns magic numbers.
                int EventMagicOverride(int parent, string str)
                {
                    if ((parent == (int)LoadVariables.AddCasusBelli ||
                         parent == (int)LoadVariables.CasusBelli) &&
                        str.Equals("type"))
                    {
                        return((int)LoadVariables.TypeCasusBelli);
                    }

                    if (parent != (int)LoadVariables.RandomList)
                    {
                        return((int)MagicUnifiedNumbers.ContinueMagicNumbers);
                    }

                    if (!int.TryParse(str, out var probability))
                    {
                        throw new Exception("Random list probability unknown! " + str);
                    }
                    return((int)MagicUnifiedNumbers.Probabilities + probability);
                }
            }

            parentLocation.Dispose();
        }
Esempio n. 18
0
        public static (Entity, Entity, List <string>, List <string>) Main()
        {
            var goods             = new NativeList <EntityWrapper>(Allocator.Temp);
            var goodsCategory     = new NativeList <EntityWrapper>(Allocator.Temp);
            var goodNames         = new List <string>();
            var goodCategoryNames = new List <string>();

            var fileTree = new List <KeyValuePair <int, object> >();
            var values   = new List <string>();

            var em = World.Active.EntityManager;
            var currentCategory = new Entity();

            FileUnpacker.ParseFile(Path.Combine(Application.streamingAssetsPath, "Common", "goods.txt"), fileTree,
                                   values, GoodsMagicOverride);

            foreach (var category in fileTree)
            {
                foreach (var goodKvp in (List <KeyValuePair <int, object> >)category.Value)
                {
                    var currentEntity = goods[goodKvp.Key - (int)MagicUnifiedNumbers.Goods];
                    var currentGood   = em.GetComponentData <GoodsEntity>(currentEntity);

                    foreach (var goodProperty in (List <KeyValuePair <int, object> >)goodKvp.Value)
                    {
                        var targetStr = values[(int)goodProperty.Value];
                        switch ((LoadVariables)goodProperty.Key)
                        {
                        case LoadVariables.Cost:
                            float.TryParse(targetStr, out var cost);
                            currentGood.Cost = cost;
                            break;

                        case LoadVariables.Color:
                            currentGood.Color = LoadMethods.ParseColor32(targetStr);
                            break;

                        case LoadVariables.AvailableFromStart:
                            currentGood.Availability = LoadMethods.YesNoConverter(targetStr);
                            break;

                        case LoadVariables.OverseasPenalty:
                            currentGood.OverseasPenalty = LoadMethods.YesNoConverter(targetStr);
                            break;

                        case LoadVariables.Money:
                            currentGood.Money = LoadMethods.YesNoConverter(targetStr);
                            break;

                        case LoadVariables.Tradeable:
                            currentGood.Tradable = LoadMethods.YesNoConverter(targetStr);
                            break;
                        }
                    }

                    em.SetComponentData(currentEntity, currentGood);
                }
            }

            var goodCollectorEntity = FileUnpacker.GetCollector <GoodsCollection>(goods);

            goods.Dispose();

            var categoryCollectorEntity = FileUnpacker.GetCollector <GoodsCategoryCollection>(goodsCategory);

            goodsCategory.Dispose();

            return(goodCollectorEntity, categoryCollectorEntity, goodNames, goodCategoryNames);

            int GoodsMagicOverride(int parent, string target)
            {
                switch (parent)
                {
                case -1:
                    var targetCategory = em.CreateEntity(typeof(GoodsCategoryEntity));
                    em.SetComponentData(targetCategory, new GoodsCategoryEntity {
                        Index = goodCategoryNames.Count
                    });
                    goodsCategory.Add(targetCategory);
                    currentCategory = targetCategory;
                    goodCategoryNames.Add(target);
                    return((int)MagicUnifiedNumbers.Placeholder);

                case (int)MagicUnifiedNumbers.Placeholder:
                    var targetGood = em.CreateEntity(typeof(GoodsEntity));
                    em.SetComponentData(targetGood,
                                        new GoodsEntity {
                        Index = goodNames.Count, Category = currentCategory
                    });
                    goods.Add(targetGood);
                    goodNames.Add(target);
                    return((int)MagicUnifiedNumbers.Goods + goodNames.Count - 1);

                default:
                    return((int)MagicUnifiedNumbers.ContinueMagicNumbers);
                }
            }
        }
Esempio n. 19
0
        public static (Entity, List <string>) Main()
        {
            var fileTree = new List <KeyValuePair <int, object> >();
            var values   = new List <string>();

            var buildings     = new NativeList <EntityWrapper>(Allocator.Temp);
            var buildingNames = new List <string>();

            var em = World.Active.EntityManager;

            FileUnpacker.ParseFile(Path.Combine(Application.streamingAssetsPath, "Common", "buildings.txt"), fileTree,
                                   values, BuildingMagicOverride);

            foreach (var buildingKvp in fileTree)
            {
                var currentEntity = buildings[buildingKvp.Key - (int)MagicUnifiedNumbers.Building].Entity;
                // ReSharper disable once ConvertToUsingDeclaration
                using (var buildingActions = new NativeList <DataValue>(Allocator.Temp))
                {
                    foreach (var attribute in (List <KeyValuePair <int, object> >)buildingKvp.Value)
                    {
                        var targetStr = attribute.Key < (int)LoadVariables.BreakCore
                            ? values[(int)attribute.Value]
                            : "";
                        switch ((LoadVariables)attribute.Key)
                        {
                        case LoadVariables.MaxLevel:
                        case LoadVariables.Time:
                        case LoadVariables.FortLevel:
                        case LoadVariables.ColonialRange:
                        case LoadVariables.NavalCapacity:
                        case LoadVariables.LocalShipBuild:
                        case LoadVariables.Cost:
                        case LoadVariables.Infrastructure:
                        case LoadVariables.MovementCost:
                        case LoadVariables.ColonialMultiplier:
                        case LoadVariables.ColonialBase:
                            if (!float.TryParse(targetStr, out var floatValue))
                            {
                                throw new Exception("Unknown float: " + targetStr);
                            }

                            buildingActions.Add(new DataValue(attribute.Key, floatValue));
                            break;

                        case LoadVariables.DefaultEnabled:
                        case LoadVariables.Province:
                        case LoadVariables.PopBuildFactory:
                        case LoadVariables.OnePerState:
                            buildingActions.Add(
                                new DataValue(attribute.Key, LoadMethods.YesNoConverter(targetStr) ? 1 : 0));
                            break;

                        case LoadVariables.GoodsCost:
                            using (var buildingGoods = new NativeList <DataGood>(Allocator.Temp))
                            {
                                foreach (var goodKvp in (List <KeyValuePair <int, object> >)attribute.Value)
                                {
                                    if (goodKvp.Key / 10000 != (int)MagicUnifiedNumbers.Goods / 10000)
                                    {
                                        throw new Exception("Unknown good located in Goods Cost "
                                                            + buildingNames[
                                                                buildingKvp.Key -
                                                                (int)MagicUnifiedNumbers.Building]);
                                    }

                                    if (!float.TryParse(values[(int)goodKvp.Value], out var goodValue))
                                    {
                                        throw new Exception("Unknown goods float: " + values[(int)goodKvp.Value]);
                                    }

                                    buildingGoods.Add(
                                        new DataGood(goodKvp.Key - (int)MagicUnifiedNumbers.Goods, goodValue));
                                }

                                em.AddBuffer <DataGood>(currentEntity).AddRange(buildingGoods);
                            }

                            break;
                        }
                    }

                    em.AddBuffer <DataValue>(currentEntity).AddRange(buildingActions);
                }
            }

            var buildingCollectorEntity = FileUnpacker.GetCollector <BuildingCollection>(buildings);

            buildings.Dispose();

            return(buildingCollectorEntity, buildingNames);

            int BuildingMagicOverride(int parent, string str)
            {
                if (parent != -1)
                {
                    return((int)MagicUnifiedNumbers.ContinueMagicNumbers);
                }

                var targetBuilding = em.CreateEntity(typeof(BuildingEntity));

                em.SetComponentData(targetBuilding, new BuildingEntity {
                    Index = buildingNames.Count
                });
                buildings.Add(targetBuilding);

                buildingNames.Add(str);
                return((int)MagicUnifiedNumbers.Building + buildingNames.Count - 1);
            }
        }