Ejemplo n.º 1
0
 public static T ItemFromXmlString <T>(string xmlContent, string filePath, bool resolveCrossRefs = true) where T : new()
 {
     if (resolveCrossRefs && DirectXmlCrossRefLoader.LoadingInProgress)
     {
         Log.Error("Cannot call ItemFromXmlString with resolveCrossRefs=true while loading is already in progress (forgot to resolve or clear cross refs from previous loading?).");
     }
     try
     {
         XmlDocument xmlDocument = new XmlDocument();
         xmlDocument.LoadXml(xmlContent);
         T result = DirectXmlToObject.ObjectFromXml <T>(xmlDocument.DocumentElement, doPostLoad: false);
         if (resolveCrossRefs)
         {
             try
             {
                 DirectXmlCrossRefLoader.ResolveAllWantedCrossReferences(FailMode.LogErrors);
             }
             finally
             {
                 DirectXmlCrossRefLoader.Clear();
             }
         }
         return(result);
     }
     catch (Exception ex)
     {
         Log.Error("Exception loading file at " + filePath + ". Loading defaults instead. Exception was: " + ex.ToString());
         return(new T());
     }
 }
 public static void LoadAllPlayData(bool recovering = false)
 {
     if (PlayDataLoader.loadedInt)
     {
         Log.Error("Loading play data when already loaded. Call ClearAllPlayData first.");
     }
     else
     {
         DeepProfiler.Start("LoadAllPlayData");
         try
         {
             PlayDataLoader.DoPlayLoad();
         }
         catch (Exception arg)
         {
             if (!Prefs.ResetModsConfigOnCrash)
             {
                 throw;
             }
             if (recovering)
             {
                 Log.Warning("Could not recover from errors loading play data. Giving up.");
                 throw;
             }
             IEnumerable <ModMetaData> activeModsInLoadOrder = ModsConfig.ActiveModsInLoadOrder;
             if (activeModsInLoadOrder.Count() == 1 && activeModsInLoadOrder.First().IsCoreMod)
             {
                 throw;
             }
             Log.Warning("Caught exception while loading play data but there are active mods other than Core. Resetting mods config and trying again.\nThe exception was: " + arg);
             try
             {
                 PlayDataLoader.ClearAllPlayData();
             }
             catch
             {
                 Log.Warning("Caught exception while recovering from errors and trying to clear all play data. Ignoring it.\nThe exception was: " + arg);
             }
             ModsConfig.Reset();
             DirectXmlCrossRefLoader.Clear();
             PlayDataLoader.LoadAllPlayData(true);
             return;
         }
         finally
         {
             DeepProfiler.End();
         }
         PlayDataLoader.loadedInt = true;
         if (recovering)
         {
             Log.Message("Successfully recovered from errors and loaded play data.");
             DelayedErrorWindowRequest.Add("RecoveredFromErrorsText".Translate(), "RecoveredFromErrorsDialogTitle".Translate());
         }
     }
 }
Ejemplo n.º 3
0
        public static object Convert(object obj, Type to, object defaultValue)
        {
            if (obj == null)
            {
                return(defaultValue);
            }
            if (to.IsAssignableFrom(obj.GetType()))
            {
                return(obj);
            }
            if (to == typeof(string))
            {
                return(obj.ToString());
            }
            string text = obj as string;

            if (text != null && !to.IsPrimitive && ParseHelper.CanParse(to, (string)obj))
            {
                if (text == "")
                {
                    return(defaultValue);
                }
                return(ParseHelper.FromString(text, to));
            }
            if (text != null && typeof(Def).IsAssignableFrom(to))
            {
                if (text == "")
                {
                    return(defaultValue);
                }
                return(GenDefDatabase.GetDef(to, text));
            }
            if (text != null && to == typeof(Faction))
            {
                if (text == "")
                {
                    return(defaultValue);
                }
                List <Faction> allFactionsListForReading = Find.FactionManager.AllFactionsListForReading;
                for (int i = 0; i < allFactionsListForReading.Count; i++)
                {
                    if (allFactionsListForReading[i].GetUniqueLoadID() == text)
                    {
                        return(allFactionsListForReading[i]);
                    }
                }
                for (int j = 0; j < allFactionsListForReading.Count; j++)
                {
                    if (allFactionsListForReading[j].HasName && allFactionsListForReading[j].Name == text)
                    {
                        return(allFactionsListForReading[j]);
                    }
                }
                for (int k = 0; k < allFactionsListForReading.Count; k++)
                {
                    if (allFactionsListForReading[k].def.defName == text)
                    {
                        return(allFactionsListForReading[k]);
                    }
                }
                return(defaultValue);
            }
            if (CanConvertBetweenDataTypes(obj.GetType(), to))
            {
                return(ConvertBetweenDataTypes(obj, to));
            }
            if (IsXml(obj) && !to.IsPrimitive)
            {
                try
                {
                    Type type = to;
                    if (type == typeof(IEnumerable))
                    {
                        type = typeof(List <string>);
                    }
                    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable <>) && type.GetGenericArguments().Length >= 1)
                    {
                        type = typeof(List <>).MakeGenericType(type.GetGenericArguments()[0]);
                    }
                    XmlDocument xmlDocument = new XmlDocument();
                    xmlDocument.LoadXml("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root>\n" + text + "\n</root>");
                    object result = DirectXmlToObject.GetObjectFromXmlMethod(type)(xmlDocument.DocumentElement, arg2 : true);
                    DirectXmlCrossRefLoader.ResolveAllWantedCrossReferences(FailMode.LogErrors);
                    return(result);
                }
                finally
                {
                    DirectXmlCrossRefLoader.Clear();
                }
            }
            if (to.IsGenericType && (to.GetGenericTypeDefinition() == typeof(IEnumerable <>) || to.GetGenericTypeDefinition() == typeof(List <>)) && to.GetGenericArguments().Length >= 1 && (!(to.GetGenericArguments()[0] == typeof(string)) || !(obj is string)))
            {
                IEnumerable enumerable = obj as IEnumerable;
                if (enumerable != null)
                {
                    Type type2 = to.GetGenericArguments()[0];
                    bool flag  = true;
                    foreach (object item in enumerable)
                    {
                        if (!CanConvert(item, type2))
                        {
                            flag = false;
                            break;
                        }
                    }
                    if (flag)
                    {
                        IList list = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(type2));
                        {
                            foreach (object item2 in enumerable)
                            {
                                list.Add(Convert(item2, type2));
                            }
                            return(list);
                        }
                    }
                }
            }
            if (obj is IEnumerable && !(obj is string))
            {
                IEnumerable e = (IEnumerable)obj;
                if (GenCollection.Count_EnumerableBase(e) == 1)
                {
                    object obj2 = GenCollection.FirstOrDefault_EnumerableBase(e);
                    if (CanConvert(obj2, to))
                    {
                        return(Convert(obj2, to));
                    }
                }
            }
            if (typeof(IList).IsAssignableFrom(to))
            {
                IList  list2            = (IList)Activator.CreateInstance(to);
                Type[] genericArguments = to.GetGenericArguments();
                if (genericArguments.Length >= 1)
                {
                    list2.Add(Convert(obj, genericArguments[0]));
                }
                else
                {
                    list2.Add(obj);
                }
                return(list2);
            }
            if (to == typeof(IEnumerable))
            {
                return(Gen.YieldSingleNonGeneric(obj));
            }
            if (to.IsGenericType && to.GetGenericTypeDefinition() == typeof(IEnumerable <>))
            {
                Type[] genericArguments2 = to.GetGenericArguments();
                if (genericArguments2.Length >= 1)
                {
                    IList obj3 = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(genericArguments2[0]));
                    obj3.Add(Convert(obj, genericArguments2[0]));
                    return(obj3);
                }
                return(Gen.YieldSingleNonGeneric(obj));
            }
            IConvertible convertible = obj as IConvertible;

            if (convertible == null)
            {
                return(defaultValue);
            }
            try
            {
                return(ConvertToPrimitive(convertible, to, defaultValue));
            }
            catch (FormatException)
            {
                return(defaultValue);
            }
        }
Ejemplo n.º 4
0
        private static void DoPlayLoad()
        {
            DeepProfiler.Start("GraphicDatabase.Clear()");
            try
            {
                GraphicDatabase.Clear();
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Load all active mods.");
            try
            {
                LoadedModManager.LoadAllActiveMods();
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Load language metadata.");
            try
            {
                LanguageDatabase.InitAllMetadata();
            }
            finally
            {
                DeepProfiler.End();
            }
            LongEventHandler.SetCurrentEventText("LoadingDefs".Translate());
            DeepProfiler.Start("Copy all Defs from mods to global databases.");
            try
            {
                foreach (Type item in typeof(Def).AllSubclasses())
                {
                    GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase <>), item, "AddAllInMods");
                }
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Resolve cross-references between non-implied Defs.");
            try
            {
                DirectXmlCrossRefLoader.ResolveAllWantedCrossReferences(FailMode.Silent);
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Rebind defs (early).");
            try
            {
                DefOfHelper.RebindAllDefOfs(earlyTryMode: true);
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("TKeySystem.BuildMappings()");
            try
            {
                TKeySystem.BuildMappings();
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Inject selected language data into game data (early pass).");
            try
            {
                LanguageDatabase.activeLanguage.InjectIntoData_BeforeImpliedDefs();
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Generate implied Defs (pre-resolve).");
            try
            {
                DefGenerator.GenerateImpliedDefs_PreResolve();
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Resolve cross-references between Defs made by the implied defs.");
            try
            {
                DirectXmlCrossRefLoader.ResolveAllWantedCrossReferences(FailMode.LogErrors);
            }
            finally
            {
                DirectXmlCrossRefLoader.Clear();
                DeepProfiler.End();
            }
            DeepProfiler.Start("Rebind DefOfs (final).");
            try
            {
                DefOfHelper.RebindAllDefOfs(earlyTryMode: false);
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Other def binding, resetting and global operations (pre-resolve).");
            try
            {
                PlayerKnowledgeDatabase.ReloadAndRebind();
                LessonAutoActivator.Reset();
                CostListCalculator.Reset();
                Pawn.ResetStaticData();
                PawnApparelGenerator.Reset();
                RestUtility.Reset();
                ThoughtUtility.Reset();
                ThinkTreeKeyAssigner.Reset();
                ThingCategoryNodeDatabase.FinalizeInit();
                TrainableUtility.Reset();
                HaulAIUtility.Reset();
                GenConstruct.Reset();
                MedicalCareUtility.Reset();
                InspectPaneUtility.Reset();
                GraphicDatabaseHeadRecords.Reset();
                DateReadout.Reset();
                ResearchProjectDef.GenerateNonOverlappingCoordinates();
                BaseGen.Reset();
                ResourceCounter.ResetDefs();
                ApparelProperties.ResetStaticData();
                WildPlantSpawner.ResetStaticData();
                PawnGenerator.Reset();
                TunnelHiveSpawner.ResetStaticData();
                Hive.ResetStaticData();
                ExpectationsUtility.Reset();
                WealthWatcher.ResetStaticData();
                SkillUI.Reset();
                QuestNode_GetThingPlayerCanProduce.ResetStaticData();
                Pawn_PsychicEntropyTracker.ResetStaticData();
                ColoredText.ResetStaticData();
                QuestNode_GetRandomNegativeGameCondition.ResetStaticData();
                RoyalTitleUtility.ResetStaticData();
                RewardsGenerator.ResetStaticData();
                WorkGiver_FillFermentingBarrel.ResetStaticData();
                WorkGiver_DoBill.ResetStaticData();
                WorkGiver_InteractAnimal.ResetStaticData();
                WorkGiver_Warden_DoExecution.ResetStaticData();
                WorkGiver_GrowerSow.ResetStaticData();
                WorkGiver_Miner.ResetStaticData();
                WorkGiver_FixBrokenDownBuilding.ResetStaticData();
                WorkGiver_ConstructDeliverResources.ResetStaticData();
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Resolve references.");
            try
            {
                DeepProfiler.Start("ThingCategoryDef resolver");
                try
                {
                    DefDatabase <ThingCategoryDef> .ResolveAllReferences();
                }
                finally
                {
                    DeepProfiler.End();
                }
                DeepProfiler.Start("RecipeDef resolver");
                try
                {
                    DeepProfiler.enabled = false;
                    DefDatabase <RecipeDef> .ResolveAllReferences(onlyExactlyMyType : true, parallel : true);

                    DeepProfiler.enabled = true;
                }
                finally
                {
                    DeepProfiler.End();
                }
                DeepProfiler.Start("Static resolver calls");
                try
                {
                    foreach (Type item2 in typeof(Def).AllSubclasses())
                    {
                        if (!(item2 == typeof(ThingDef)) && !(item2 == typeof(ThingCategoryDef)) && !(item2 == typeof(RecipeDef)))
                        {
                            GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase <>), item2, "ResolveAllReferences", true, false);
                        }
                    }
                }
                finally
                {
                    DeepProfiler.End();
                }
                DeepProfiler.Start("ThingDef resolver");
                try
                {
                    DefDatabase <ThingDef> .ResolveAllReferences();
                }
                finally
                {
                    DeepProfiler.End();
                }
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Generate implied Defs (post-resolve).");
            try
            {
                DefGenerator.GenerateImpliedDefs_PostResolve();
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Other def binding, resetting and global operations (post-resolve).");
            try
            {
                PawnWeaponGenerator.Reset();
                BuildingProperties.FinalizeInit();
                ThingSetMakerUtility.Reset();
            }
            finally
            {
                DeepProfiler.End();
            }
            if (Prefs.DevMode)
            {
                DeepProfiler.Start("Error check all defs.");
                try
                {
                    foreach (Type item3 in typeof(Def).AllSubclasses())
                    {
                        GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase <>), item3, "ErrorCheckAllDefs");
                    }
                }
                finally
                {
                    DeepProfiler.End();
                }
            }
            LongEventHandler.SetCurrentEventText("Initializing".Translate());
            DeepProfiler.Start("Load keyboard preferences.");
            try
            {
                KeyPrefs.Init();
            }
            finally
            {
                DeepProfiler.End();
            }
            DeepProfiler.Start("Short hash giving.");
            try
            {
                ShortHashGiver.GiveAllShortHashes();
            }
            finally
            {
                DeepProfiler.End();
            }
            LongEventHandler.ExecuteWhenFinished(delegate
            {
                DeepProfiler.Start("Load backstories.");
                try
                {
                    BackstoryDatabase.ReloadAllBackstories();
                }
                finally
                {
                    DeepProfiler.End();
                }
            });
            LongEventHandler.ExecuteWhenFinished(delegate
            {
                DeepProfiler.Start("Inject selected language data into game data.");
                try
                {
                    LanguageDatabase.activeLanguage.InjectIntoData_AfterImpliedDefs();
                    GenLabel.ClearCache();
                }
                finally
                {
                    DeepProfiler.End();
                }
            });
            LongEventHandler.ExecuteWhenFinished(delegate
            {
                DeepProfiler.Start("Static constructor calls");
                try
                {
                    StaticConstructorOnStartupUtility.CallAll();
                    if (Prefs.DevMode)
                    {
                        StaticConstructorOnStartupUtility.ReportProbablyMissingAttributes();
                    }
                }
                finally
                {
                    DeepProfiler.End();
                }
                DeepProfiler.Start("Garbage Collection");
                try
                {
                    AbstractFilesystem.ClearAllCache();
                    GC.Collect(int.MaxValue, GCCollectionMode.Forced);
                }
                finally
                {
                    DeepProfiler.End();
                }
            });
        }