public static LoadedContentItem <T> LoadItem(string absFilePath, string contentDirPath = null) { string text = absFilePath; if (contentDirPath != null) { text = text.Substring(contentDirPath.ToString().Length); } text = text.Substring(0, text.Length - Path.GetExtension(text).Length); text = text.Replace('\\', '/'); try { if (typeof(T) == typeof(string)) { LoadedContentItem <T> result = new LoadedContentItem <T>(text, (T)((object)GenFile.TextFromRawFile(absFilePath))); return(result); } if (typeof(T) == typeof(Texture2D)) { LoadedContentItem <T> result = new LoadedContentItem <T>(text, (T)((object)ModContentLoader <T> .LoadPNG(absFilePath))); return(result); } if (typeof(T) == typeof(AudioClip)) { if (Prefs.LogVerbose) { DeepProfiler.Start("Loading file " + text); } T t; try { bool doStream = ModContentLoader <T> .ShouldStreamAudioClipFromPath(absFilePath); t = (T)((object)Manager.Load(absFilePath, doStream, true, true)); } finally { if (Prefs.LogVerbose) { DeepProfiler.End(); } } UnityEngine.Object @object = t as UnityEngine.Object; if (@object != null) { @object.name = Path.GetFileNameWithoutExtension(new FileInfo(absFilePath).Name); } LoadedContentItem <T> result = new LoadedContentItem <T>(text, t); return(result); } } catch (Exception ex) { Log.Error(string.Concat(new object[] { "Exception loading ", typeof(T), " from file.\nabsFilePath: ", absFilePath, "\ncontentDirPath: ", contentDirPath, "\nException: ", ex.ToString() }), false); } if (typeof(T) == typeof(Texture2D)) { return((LoadedContentItem <T>) new LoadedContentItem <Texture2D>(absFilePath, BaseContent.BadTex)); } return(null); }
public static void LoadAllActiveMods() { DeepProfiler.Start("XmlInheritance.Clear()"); try { XmlInheritance.Clear(); } finally { DeepProfiler.End(); } DeepProfiler.Start("InitializeMods()"); try { InitializeMods(); } finally { DeepProfiler.End(); } DeepProfiler.Start("LoadModContent()"); try { LoadModContent(); } finally { DeepProfiler.End(); } DeepProfiler.Start("CreateModClasses()"); try { CreateModClasses(); } finally { DeepProfiler.End(); } List <LoadableXmlAsset> xmls = null; DeepProfiler.Start("LoadModXML()"); try { xmls = LoadModXML(); } finally { DeepProfiler.End(); } Dictionary <XmlNode, LoadableXmlAsset> assetlookup = new Dictionary <XmlNode, LoadableXmlAsset>(); XmlDocument xmlDocument = null; DeepProfiler.Start("CombineIntoUnifiedXML()"); try { xmlDocument = CombineIntoUnifiedXML(xmls, assetlookup); } finally { DeepProfiler.End(); } TKeySystem.Clear(); DeepProfiler.Start("TKeySystem.Parse()"); try { TKeySystem.Parse(xmlDocument); } finally { DeepProfiler.End(); } DeepProfiler.Start("ApplyPatches()"); try { ApplyPatches(xmlDocument, assetlookup); } finally { DeepProfiler.End(); } DeepProfiler.Start("ParseAndProcessXML()"); try { ParseAndProcessXML(xmlDocument, assetlookup); } finally { DeepProfiler.End(); } DeepProfiler.Start("ClearCachedPatches()"); try { ClearCachedPatches(); } finally { DeepProfiler.End(); } DeepProfiler.Start("XmlInheritance.Clear()"); try { XmlInheritance.Clear(); } finally { DeepProfiler.End(); } }
public void LoadGame() { if (this.maps.Any()) { Log.Error("Called LoadGame() but there already is a map. There should be 0 maps..."); } else { MemoryUtility.UnloadUnusedUnityAssets(); Current.ProgramState = ProgramState.MapInitializing; this.ExposeSmallComponents(); BackCompatibility.AfterLoadingSmallGameClassComponents(this); LongEventHandler.SetCurrentEventText("LoadingWorld".Translate()); if (Scribe.EnterNode("world")) { try { this.World = new World(); this.World.ExposeData(); } finally { Scribe.ExitNode(); } this.World.FinalizeInit(); LongEventHandler.SetCurrentEventText("LoadingMap".Translate()); Scribe_Collections.Look <Map>(ref this.maps, "maps", LookMode.Deep, new object[0]); int num = -1; Scribe_Values.Look(ref num, "visibleMapIndex", -1, false); if (num < 0 && this.maps.Any()) { Log.Error("Visible map is null after loading but there are maps available. Setting visible map to [0]."); num = 0; } if (num >= this.maps.Count) { Log.Error("Visible map index out of bounds after loading."); num = ((!this.maps.Any()) ? (-1) : 0); } this.visibleMapIndex = -128; this.VisibleMap = ((num < 0) ? null : this.maps[num]); LongEventHandler.SetCurrentEventText("InitializingGame".Translate()); Find.CameraDriver.Expose(); DeepProfiler.Start("FinalizeLoading"); Scribe.loader.FinalizeLoading(); DeepProfiler.End(); LongEventHandler.SetCurrentEventText("SpawningAllThings".Translate()); for (int i = 0; i < this.maps.Count; i++) { this.maps[i].FinalizeLoading(); } this.FinalizeInit(); if (Prefs.PauseOnLoad) { LongEventHandler.ExecuteWhenFinished(delegate { Find.TickManager.DoSingleTick(); Find.TickManager.CurTimeSpeed = TimeSpeed.Paused; }); } GameComponentUtility.LoadedGame(); } else { Log.Error("Could not find world XML node."); } } }
public void FinalizeLoading() { List <Thing> list = this.compressor.ThingsToSpawnAfterLoad().ToList <Thing>(); this.compressor = null; DeepProfiler.Start("Merge compressed and non-compressed thing lists"); List <Thing> list2 = new List <Thing>(this.loadedFullThings.Count + list.Count); foreach (Thing current in this.loadedFullThings.Concat(list)) { list2.Add(current); } this.loadedFullThings.Clear(); DeepProfiler.End(); DeepProfiler.Start("Spawn everything into the map"); BackCompatibility.PreCheckSpawnBackCompatibleThingAfterLoading(this); foreach (Thing current2 in list2) { if (!(current2 is Building)) { try { if (!BackCompatibility.CheckSpawnBackCompatibleThingAfterLoading(current2, this)) { GenSpawn.Spawn(current2, current2.Position, this, current2.Rotation, WipeMode.FullRefund, true); } } catch (Exception ex) { Log.Error(string.Concat(new object[] { "Exception spawning loaded thing ", current2.ToStringSafe <Thing>(), ": ", ex }), false); } } } foreach (Building current3 in from t in list2.OfType <Building>() orderby t.def.size.Magnitude select t) { try { GenSpawn.SpawnBuildingAsPossible(current3, this, true); } catch (Exception ex2) { Log.Error(string.Concat(new object[] { "Exception spawning loaded thing ", current3.ToStringSafe <Building>(), ": ", ex2 }), false); } } BackCompatibility.PostCheckSpawnBackCompatibleThingAfterLoading(this); DeepProfiler.End(); this.FinalizeInit(); }
public static Map GenerateMap(IntVec3 mapSize, MapParent parent, MapGeneratorDef mapGenerator, IEnumerable <GenStepWithParams> extraGenStepDefs = null, Action <Map> extraInitBeforeContentGen = null) { ProgramState programState = Current.ProgramState; Current.ProgramState = ProgramState.MapInitializing; MapGenerator.playerStartSpotInt = IntVec3.Invalid; MapGenerator.rootsToUnfog.Clear(); MapGenerator.data.Clear(); MapGenerator.mapBeingGenerated = null; DeepProfiler.Start("InitNewGeneratedMap"); Rand.PushState(); int seed = Gen.HashCombineInt(Find.World.info.Seed, parent.Tile); Rand.Seed = seed; Map result; try { if (parent != null && parent.HasMap) { Log.Error("Tried to generate a new map and set " + parent + " as its parent, but this world object already has a map. One world object can't have more than 1 map.", false); parent = null; } DeepProfiler.Start("Set up map"); Map map = new Map(); map.uniqueID = Find.UniqueIDsManager.GetNextMapID(); MapGenerator.mapBeingGenerated = map; map.info.Size = mapSize; map.info.parent = parent; map.ConstructComponents(); DeepProfiler.End(); Current.Game.AddMap(map); if (extraInitBeforeContentGen != null) { extraInitBeforeContentGen(map); } if (mapGenerator == null) { Log.Error("Attempted to generate map without generator; falling back on encounter map", false); mapGenerator = MapGeneratorDefOf.Encounter; } IEnumerable <GenStepWithParams> enumerable = from x in mapGenerator.genSteps select new GenStepWithParams(x, default(GenStepParams)); if (extraGenStepDefs != null) { enumerable = enumerable.Concat(extraGenStepDefs); } map.areaManager.AddStartingAreas(); map.weatherDecider.StartInitialWeather(); DeepProfiler.Start("Generate contents into map"); MapGenerator.GenerateContentsIntoMap(enumerable, map, seed); DeepProfiler.End(); Find.Scenario.PostMapGenerate(map); DeepProfiler.Start("Finalize map init"); map.FinalizeInit(); DeepProfiler.End(); DeepProfiler.Start("MapComponent.MapGenerated()"); MapComponentUtility.MapGenerated(map); DeepProfiler.End(); if (parent != null) { parent.PostMapGenerate(); } result = map; } finally { DeepProfiler.End(); MapGenerator.mapBeingGenerated = null; Current.ProgramState = programState; Rand.PopState(); } return(result); }
private static void DoPlayLoad() { GraphicDatabase.Clear(); DeepProfiler.Start("Load all active mods."); try { LoadedModManager.LoadAllActiveMods(); } finally { DeepProfiler.End(); } DeepProfiler.Start("Load language metadata."); try { LanguageDatabase.LoadAllMetadata(); } 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("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 { 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(); PawnWeaponGenerator.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(); 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 { foreach (Type item2 in typeof(Def).AllSubclasses()) { if (item2 != typeof(ThingDef)) { GenGeneric.InvokeStaticMethodOnGenericType(typeof(DefDatabase <>), item2, "ResolveAllReferences", true); } } DefDatabase <ThingDef> .ResolveAllReferences(); } 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 { 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 { StaticConstructorOnStartupUtility.CallAll(); if (Prefs.DevMode) { StaticConstructorOnStartupUtility.ReportProbablyMissingAttributes(); } }); }
public void InitNewGame() { string str = (from mod in LoadedModManager.RunningMods select mod.ToString()).ToCommaList(false); Log.Message("Initializing new game with mods " + str, false); if (this.maps.Any <Map>()) { Log.Error("Called InitNewGame() but there already is a map. There should be 0 maps...", false); return; } if (this.initData == null) { Log.Error("Called InitNewGame() but init data is null. Create it first.", false); return; } MemoryUtility.UnloadUnusedUnityAssets(); DeepProfiler.Start("InitNewGame"); try { Current.ProgramState = ProgramState.MapInitializing; IntVec3 intVec = new IntVec3(this.initData.mapSize, 1, this.initData.mapSize); Settlement settlement = null; List <Settlement> settlements = Find.WorldObjects.Settlements; for (int i = 0; i < settlements.Count; i++) { if (settlements[i].Faction == Faction.OfPlayer) { settlement = settlements[i]; break; } } if (settlement == null) { Log.Error("Could not generate starting map because there is no any player faction base.", false); } this.tickManager.gameStartAbsTick = GenTicks.ConfiguredTicksAbsAtGameStart; Map currentMap = MapGenerator.GenerateMap(intVec, settlement, settlement.MapGeneratorDef, settlement.ExtraGenStepDefs, null); this.worldInt.info.initialMapSize = intVec; if (this.initData.permadeath) { this.info.permadeathMode = true; this.info.permadeathModeUniqueName = PermadeathModeUtility.GeneratePermadeathSaveName(); } PawnUtility.GiveAllStartingPlayerPawnsThought(ThoughtDefOf.NewColonyOptimism); this.FinalizeInit(); Current.Game.CurrentMap = currentMap; Find.CameraDriver.JumpToCurrentMapLoc(MapGenerator.PlayerStartSpot); Find.CameraDriver.ResetSize(); if (Prefs.PauseOnLoad && this.initData.startedFromEntry) { LongEventHandler.ExecuteWhenFinished(delegate { this.tickManager.DoSingleTick(); this.tickManager.CurTimeSpeed = TimeSpeed.Paused; }); } Find.Scenario.PostGameStart(); if (Faction.OfPlayer.def.startingResearchTags != null) { foreach (ResearchProjectTagDef current in Faction.OfPlayer.def.startingResearchTags) { foreach (ResearchProjectDef current2 in DefDatabase <ResearchProjectDef> .AllDefs) { if (current2.HasTag(current)) { this.researchManager.FinishProject(current2, false, null); } } } } GameComponentUtility.StartedNewGame(); this.initData = null; } finally { DeepProfiler.End(); } }
public void LoadData() { if (this.dataIsLoaded) { return; } this.dataIsLoaded = true; DeepProfiler.Start("Loading language data: " + this.folderName); foreach (string current in this.FolderPaths) { string localFolderPath = current; LongEventHandler.ExecuteWhenFinished(delegate { if (this.icon == BaseContent.BadTex) { FileInfo fileInfo = new FileInfo(Path.Combine(localFolderPath.ToString(), "LangIcon.png")); if (fileInfo.Exists) { this.icon = ModContentLoader <Texture2D> .LoadItem(fileInfo.FullName, null).contentItem; } } }); DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(current.ToString(), "CodeLinked")); if (directoryInfo.Exists) { this.loadErrors.Add("Translations aren't called CodeLinked any more. Please rename to Keyed: " + directoryInfo); } else { directoryInfo = new DirectoryInfo(Path.Combine(current.ToString(), "Keyed")); } if (directoryInfo.Exists) { FileInfo[] files = directoryInfo.GetFiles("*.xml", SearchOption.AllDirectories); for (int i = 0; i < files.Length; i++) { FileInfo file = files[i]; this.LoadFromFile_Keyed(file); } } DirectoryInfo directoryInfo2 = new DirectoryInfo(Path.Combine(current.ToString(), "DefLinked")); if (directoryInfo2.Exists) { this.loadErrors.Add("Translations aren't called DefLinked any more. Please rename to DefInjected: " + directoryInfo2); } else { directoryInfo2 = new DirectoryInfo(Path.Combine(current.ToString(), "DefInjected")); } if (directoryInfo2.Exists) { DirectoryInfo[] directories = directoryInfo2.GetDirectories("*", SearchOption.TopDirectoryOnly); for (int j = 0; j < directories.Length; j++) { DirectoryInfo directoryInfo3 = directories[j]; string name = directoryInfo3.Name; Type typeInAnyAssembly = GenTypes.GetTypeInAnyAssembly(name); if (typeInAnyAssembly == null && name.Length > 3) { typeInAnyAssembly = GenTypes.GetTypeInAnyAssembly(name.Substring(0, name.Length - 1)); } if (typeInAnyAssembly == null) { this.loadErrors.Add(string.Concat(new string[] { "Error loading language from ", current, ": dir ", directoryInfo3.Name, " doesn't correspond to any def type. Skipping..." })); } else { FileInfo[] files2 = directoryInfo3.GetFiles("*.xml", SearchOption.AllDirectories); for (int k = 0; k < files2.Length; k++) { FileInfo file2 = files2[k]; this.LoadFromFile_DefInject(file2, typeInAnyAssembly); } } } } this.EnsureAllDefTypesHaveDefInjectionPackage(); DirectoryInfo directoryInfo4 = new DirectoryInfo(Path.Combine(current.ToString(), "Strings")); if (directoryInfo4.Exists) { DirectoryInfo[] directories2 = directoryInfo4.GetDirectories("*", SearchOption.TopDirectoryOnly); for (int l = 0; l < directories2.Length; l++) { DirectoryInfo directoryInfo5 = directories2[l]; FileInfo[] files3 = directoryInfo5.GetFiles("*.txt", SearchOption.AllDirectories); for (int m = 0; m < files3.Length; m++) { FileInfo file3 = files3[m]; this.LoadFromFile_Strings(file3, directoryInfo4); } } } } DeepProfiler.End(); }
public void LoadData() { if (!dataIsLoaded) { dataIsLoaded = true; DeepProfiler.Start("Loading language data: " + folderName); try { foreach (string folderPath in FolderPaths) { string localFolderPath = folderPath; LongEventHandler.ExecuteWhenFinished(delegate { if (icon == BaseContent.BadTex) { FileInfo fileInfo = new FileInfo(Path.Combine(localFolderPath.ToString(), "LangIcon.png")); if (fileInfo.Exists) { icon = ModContentLoader <Texture2D> .LoadItem(fileInfo.FullName).contentItem; } } }); DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(folderPath.ToString(), "CodeLinked")); if (directoryInfo.Exists) { loadErrors.Add("Translations aren't called CodeLinked any more. Please rename to Keyed: " + directoryInfo); } else { directoryInfo = new DirectoryInfo(Path.Combine(folderPath.ToString(), "Keyed")); } if (directoryInfo.Exists) { FileInfo[] files = directoryInfo.GetFiles("*.xml", SearchOption.AllDirectories); foreach (FileInfo file in files) { LoadFromFile_Keyed(file); } } DirectoryInfo directoryInfo2 = new DirectoryInfo(Path.Combine(folderPath.ToString(), "DefLinked")); if (directoryInfo2.Exists) { loadErrors.Add("Translations aren't called DefLinked any more. Please rename to DefInjected: " + directoryInfo2); } else { directoryInfo2 = new DirectoryInfo(Path.Combine(folderPath.ToString(), "DefInjected")); } if (directoryInfo2.Exists) { DirectoryInfo[] directories = directoryInfo2.GetDirectories("*", SearchOption.TopDirectoryOnly); foreach (DirectoryInfo directoryInfo3 in directories) { string name = directoryInfo3.Name; Type typeInAnyAssembly = GenTypes.GetTypeInAnyAssembly(name); if (typeInAnyAssembly == null && name.Length > 3) { typeInAnyAssembly = GenTypes.GetTypeInAnyAssembly(name.Substring(0, name.Length - 1)); } if (typeInAnyAssembly == null) { loadErrors.Add("Error loading language from " + folderPath + ": dir " + directoryInfo3.Name + " doesn't correspond to any def type. Skipping..."); } else { FileInfo[] files2 = directoryInfo3.GetFiles("*.xml", SearchOption.AllDirectories); foreach (FileInfo file2 in files2) { LoadFromFile_DefInject(file2, typeInAnyAssembly); } } } } EnsureAllDefTypesHaveDefInjectionPackage(); DirectoryInfo directoryInfo4 = new DirectoryInfo(Path.Combine(folderPath.ToString(), "Strings")); if (directoryInfo4.Exists) { DirectoryInfo[] directories2 = directoryInfo4.GetDirectories("*", SearchOption.TopDirectoryOnly); foreach (DirectoryInfo directoryInfo5 in directories2) { FileInfo[] files3 = directoryInfo5.GetFiles("*.txt", SearchOption.AllDirectories); foreach (FileInfo file3 in files3) { LoadFromFile_Strings(file3, directoryInfo4); } } } wordInfo.LoadFrom(folderPath); } } catch (Exception arg) { Log.Error("Exception loading language data. Rethrowing. Exception: " + arg); throw; } finally { DeepProfiler.End(); } } }
public void ExposeData() { Scribe_Values.Look(ref uniqueID, "uniqueID", -1); Scribe_Values.Look(ref generationTick, "generationTick", 0); Scribe_Deep.Look(ref info, "mapInfo"); if (Scribe.mode == LoadSaveMode.Saving) { compressor = new MapFileCompressor(this); compressor.BuildCompressedString(); ExposeComponents(); compressor.ExposeData(); HashSet <string> hashSet = new HashSet <string>(); if (Scribe.EnterNode("things")) { try { foreach (Thing allThing in listerThings.AllThings) { try { if (allThing.def.isSaveable && !allThing.IsSaveCompressible()) { if (hashSet.Contains(allThing.ThingID)) { Log.Error("Saving Thing with already-used ID " + allThing.ThingID); } else { hashSet.Add(allThing.ThingID); } Thing target = allThing; Scribe_Deep.Look(ref target, "thing"); } } catch (OutOfMemoryException) { throw; } catch (Exception ex2) { Log.Error("Exception saving " + allThing + ": " + ex2); } } } finally { Scribe.ExitNode(); } } else { Log.Error("Could not enter the things node while saving."); } compressor = null; return; } if (Scribe.mode == LoadSaveMode.LoadingVars) { ConstructComponents(); regionAndRoomUpdater.Enabled = false; compressor = new MapFileCompressor(this); } ExposeComponents(); DeepProfiler.Start("Load compressed things"); compressor.ExposeData(); DeepProfiler.End(); DeepProfiler.Start("Load non-compressed things"); Scribe_Collections.Look(ref loadedFullThings, "things", LookMode.Deep); DeepProfiler.End(); }
public void LoadData() { if (!this.dataIsLoaded) { this.dataIsLoaded = true; DeepProfiler.Start("Loading language data: " + this.folderName); foreach (string text in this.FolderPaths) { string localFolderPath = text; LongEventHandler.ExecuteWhenFinished(delegate { if (this.icon == BaseContent.BadTex) { FileInfo fileInfo = new FileInfo(Path.Combine(localFolderPath.ToString(), "LangIcon.png")); if (fileInfo.Exists) { this.icon = ModContentLoader <Texture2D> .LoadItem(fileInfo.FullName, null).contentItem; } } }); DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(text.ToString(), "CodeLinked")); if (directoryInfo.Exists) { this.loadErrors.Add("Translations aren't called CodeLinked any more. Please rename to Keyed: " + directoryInfo); } else { directoryInfo = new DirectoryInfo(Path.Combine(text.ToString(), "Keyed")); } if (directoryInfo.Exists) { foreach (FileInfo file in directoryInfo.GetFiles("*.xml", SearchOption.AllDirectories)) { this.LoadFromFile_Keyed(file); } } DirectoryInfo directoryInfo2 = new DirectoryInfo(Path.Combine(text.ToString(), "DefLinked")); if (directoryInfo2.Exists) { this.loadErrors.Add("Translations aren't called DefLinked any more. Please rename to DefInjected: " + directoryInfo2); } else { directoryInfo2 = new DirectoryInfo(Path.Combine(text.ToString(), "DefInjected")); } if (directoryInfo2.Exists) { foreach (DirectoryInfo directoryInfo3 in directoryInfo2.GetDirectories("*", SearchOption.TopDirectoryOnly)) { string name = directoryInfo3.Name; Type typeInAnyAssembly = GenTypes.GetTypeInAnyAssembly(name); if (typeInAnyAssembly == null && name.Length > 3) { typeInAnyAssembly = GenTypes.GetTypeInAnyAssembly(name.Substring(0, name.Length - 1)); } if (typeInAnyAssembly == null) { this.loadErrors.Add(string.Concat(new string[] { "Error loading language from ", text, ": dir ", directoryInfo3.Name, " doesn't correspond to any def type. Skipping..." })); } else { foreach (FileInfo file2 in directoryInfo3.GetFiles("*.xml", SearchOption.AllDirectories)) { this.LoadFromFile_DefInject(file2, typeInAnyAssembly); } } } } DirectoryInfo directoryInfo4 = new DirectoryInfo(Path.Combine(text.ToString(), "Strings")); if (directoryInfo4.Exists) { foreach (DirectoryInfo directoryInfo5 in directoryInfo4.GetDirectories("*", SearchOption.TopDirectoryOnly)) { foreach (FileInfo file3 in directoryInfo5.GetFiles("*.txt", SearchOption.AllDirectories)) { this.LoadFromFile_Strings(file3, directoryInfo4); } } } } DeepProfiler.End(); } }
public void LoadGame() { if (maps.Any()) { Log.Error("Called LoadGame() but there already is a map. There should be 0 maps..."); } else { MemoryUtility.UnloadUnusedUnityAssets(); Current.ProgramState = ProgramState.MapInitializing; ExposeSmallComponents(); LongEventHandler.SetCurrentEventText("LoadingWorld".Translate()); if (!Scribe.EnterNode("world")) { Log.Error("Could not find world XML node."); } else { try { World = new World(); World.ExposeData(); } finally { Scribe.ExitNode(); } World.FinalizeInit(); LongEventHandler.SetCurrentEventText("LoadingMap".Translate()); Scribe_Collections.Look(ref maps, "maps", LookMode.Deep); if (maps.RemoveAll((Map x) => x == null) != 0) { Log.Warning("Some maps were null after loading."); } int value = -1; Scribe_Values.Look(ref value, "currentMapIndex", -1); if (value < 0 && maps.Any()) { Log.Error("Current map is null after loading but there are maps available. Setting current map to [0]."); value = 0; } if (value >= maps.Count) { Log.Error("Current map index out of bounds after loading."); value = ((!maps.Any()) ? (-1) : 0); } currentMapIndex = sbyte.MinValue; CurrentMap = ((value < 0) ? null : maps[value]); LongEventHandler.SetCurrentEventText("InitializingGame".Translate()); Find.CameraDriver.Expose(); DeepProfiler.Start("FinalizeLoading"); Scribe.loader.FinalizeLoading(); DeepProfiler.End(); LongEventHandler.SetCurrentEventText("SpawningAllThings".Translate()); for (int i = 0; i < maps.Count; i++) { try { maps[i].FinalizeLoading(); } catch (Exception arg) { Log.Error("Error in Map.FinalizeLoading(): " + arg); } try { maps[i].Parent.FinalizeLoading(); } catch (Exception arg2) { Log.Error("Error in MapParent.FinalizeLoading(): " + arg2); } } FinalizeInit(); if (Prefs.PauseOnLoad) { LongEventHandler.ExecuteWhenFinished(delegate { Find.TickManager.DoSingleTick(); Find.TickManager.CurTimeSpeed = TimeSpeed.Paused; }); } GameComponentUtility.LoadedGame(); } } }
public void InitNewGame() { string str = LoadedModManager.RunningMods.Select((ModContentPack mod) => mod.PackageIdPlayerFacing).ToLineList(" - "); Log.Message("Initializing new game with mods:\n" + str); if (maps.Any()) { Log.Error("Called InitNewGame() but there already is a map. There should be 0 maps..."); return; } if (initData == null) { Log.Error("Called InitNewGame() but init data is null. Create it first."); return; } MemoryUtility.UnloadUnusedUnityAssets(); DeepProfiler.Start("InitNewGame"); try { //InitMap Current.ProgramState = ProgramState.MapInitializing; IntVec3 intVec = new IntVec3(initData.mapSize, 1, initData.mapSize); Settlement settlement = null; List <Settlement> settlements = Find.WorldObjects.Settlements; for (int i = 0; i < settlements.Count; i++) { if (settlements[i].Faction == Faction.OfPlayer) { settlement = settlements[i]; break; } } if (settlement == null) { Log.Error("Could not generate starting map because there is no any player faction base."); } tickManager.gameStartAbsTick = GenTicks.ConfiguredTicksAbsAtGameStart; //-------------- //Map currentMap=Map //Map currentMap = MapGenerator.GenerateMap(intVec, settlement, settlement.MapGeneratorDef, settlement.ExtraGenStepDefs); //Map currentMap=MapGenerator.GenerateMap(intVec,settlement,settlement.MapGeneratorDef,settlement.ExtraGenStepDefs) Map currentMap = MapGenerator.GenerateMap(intVec, settlement, settlement.MapGeneratorDef, settlement.ExtraGenStepDefs); worldInt.info.initialMapSize = intVec; if (initData.permadeath) { info.permadeathMode = true; info.permadeathModeUniqueName = PermadeathModeUtility.GeneratePermadeathSaveName(); } PawnUtility.GiveAllStartingPlayerPawnsThought(ThoughtDefOf.NewColonyOptimism); FinalizeInit(); Current.Game.CurrentMap = currentMap; Find.CameraDriver.JumpToCurrentMapLoc(MapGenerator.PlayerStartSpot); Find.CameraDriver.ResetSize(); if (Prefs.PauseOnLoad && initData.startedFromEntry) { LongEventHandler.ExecuteWhenFinished(delegate { tickManager.DoSingleTick(); tickManager.CurTimeSpeed = TimeSpeed.Paused; }); } //--------------end Find.Scenario.PostGameStart(); if (Faction.OfPlayer.def.startingResearchTags != null) { foreach (ResearchProjectTagDef startingResearchTag in Faction.OfPlayer.def.startingResearchTags) { foreach (ResearchProjectDef allDef in DefDatabase <ResearchProjectDef> .AllDefs) { if (allDef.HasTag(startingResearchTag)) { researchManager.FinishProject(allDef); } } } } if (Faction.OfPlayer.def.startingTechprintsResearchTags != null) { foreach (ResearchProjectTagDef startingTechprintsResearchTag in Faction.OfPlayer.def.startingTechprintsResearchTags) { foreach (ResearchProjectDef allDef2 in DefDatabase <ResearchProjectDef> .AllDefs) { if (allDef2.HasTag(startingTechprintsResearchTag)) { int techprints = researchManager.GetTechprints(allDef2); if (techprints < allDef2.techprintCount) { researchManager.AddTechprints(allDef2, allDef2.techprintCount - techprints); } } } } } GameComponentUtility.StartedNewGame(); initData = null; } finally { DeepProfiler.End(); } }
public static void ParseAndProcessXML(XmlDocument xmlDoc, Dictionary <XmlNode, LoadableXmlAsset> assetlookup) { XmlNodeList childNodes = xmlDoc.DocumentElement.ChildNodes; List <XmlNode> list = new List <XmlNode>(); foreach (object item in childNodes) { list.Add(item as XmlNode); } DeepProfiler.Start("Loading asset nodes " + list.Count); try { for (int i = 0; i < list.Count; i++) { if (list[i].NodeType == XmlNodeType.Element) { LoadableXmlAsset value = null; DeepProfiler.Start("assetlookup.TryGetValue"); try { assetlookup.TryGetValue(list[i], out value); } finally { DeepProfiler.End(); } DeepProfiler.Start("XmlInheritance.TryRegister"); try { XmlInheritance.TryRegister(list[i], value?.mod); } finally { DeepProfiler.End(); } } } } finally { DeepProfiler.End(); } DeepProfiler.Start("XmlInheritance.Resolve()"); try { XmlInheritance.Resolve(); } finally { DeepProfiler.End(); } runningMods.FirstOrDefault(); DeepProfiler.Start("Loading defs for " + list.Count + " nodes"); try { foreach (XmlNode item2 in list) { LoadableXmlAsset loadableXmlAsset = assetlookup.TryGetValue(item2); Def def = DirectXmlLoader.DefFromNode(item2, loadableXmlAsset); if (def != null) { ModContentPack modContentPack = loadableXmlAsset?.mod; if (modContentPack != null) { modContentPack.AddDef(def, loadableXmlAsset.name); } else { patchedDefs.Add(def); } } } } finally { DeepProfiler.End(); } }
public void LoadGame() { if (this.maps.Any <Map>()) { Log.Error("Called LoadGame() but there already is a map. There should be 0 maps...", false); return; } MemoryUtility.UnloadUnusedUnityAssets(); Current.ProgramState = ProgramState.MapInitializing; this.ExposeSmallComponents(); LongEventHandler.SetCurrentEventText("LoadingWorld".Translate()); if (Scribe.EnterNode("world")) { try { this.World = new World(); this.World.ExposeData(); } finally { Scribe.ExitNode(); } this.World.FinalizeInit(); LongEventHandler.SetCurrentEventText("LoadingMap".Translate()); Scribe_Collections.Look <Map>(ref this.maps, "maps", LookMode.Deep, new object[0]); if (this.maps.RemoveAll((Map x) => x == null) != 0) { Log.Warning("Some maps were null after loading.", false); } int num = -1; Scribe_Values.Look <int>(ref num, "currentMapIndex", -1, false); if (num < 0 && this.maps.Any <Map>()) { Log.Error("Current map is null after loading but there are maps available. Setting current map to [0].", false); num = 0; } if (num >= this.maps.Count) { Log.Error("Current map index out of bounds after loading.", false); if (this.maps.Any <Map>()) { num = 0; } else { num = -1; } } this.currentMapIndex = -128; this.CurrentMap = ((num < 0) ? null : this.maps[num]); LongEventHandler.SetCurrentEventText("InitializingGame".Translate()); Find.CameraDriver.Expose(); DeepProfiler.Start("FinalizeLoading"); Scribe.loader.FinalizeLoading(); DeepProfiler.End(); LongEventHandler.SetCurrentEventText("SpawningAllThings".Translate()); for (int i = 0; i < this.maps.Count; i++) { try { this.maps[i].FinalizeLoading(); } catch (Exception arg) { Log.Error("Error in Map.FinalizeLoading(): " + arg, false); } try { this.maps[i].Parent.FinalizeLoading(); } catch (Exception arg2) { Log.Error("Error in MapParent.FinalizeLoading(): " + arg2, false); } } this.FinalizeInit(); if (Prefs.PauseOnLoad) { LongEventHandler.ExecuteWhenFinished(delegate { Find.TickManager.DoSingleTick(); Find.TickManager.CurTimeSpeed = TimeSpeed.Paused; }); } GameComponentUtility.LoadedGame(); return; } Log.Error("Could not find world XML node.", false); }
public static void LoadAllActiveMods() { XmlInheritance.Clear(); int num = 0; foreach (ModMetaData current in ModsConfig.ActiveModsInLoadOrder.ToList <ModMetaData>()) { DeepProfiler.Start("Initializing " + current); if (!current.RootDir.Exists) { ModsConfig.SetActive(current.Identifier, false); Log.Warning(string.Concat(new object[] { "Failed to find active mod ", current.Name, "(", current.Identifier, ") at ", current.RootDir })); DeepProfiler.End(); } else { ModContentPack item = new ModContentPack(current.RootDir, num, current.Name); num++; LoadedModManager.runningMods.Add(item); DeepProfiler.End(); } } for (int i = 0; i < LoadedModManager.runningMods.Count; i++) { ModContentPack modContentPack = LoadedModManager.runningMods[i]; DeepProfiler.Start("Loading " + modContentPack + " content"); modContentPack.ReloadContent(); DeepProfiler.End(); } foreach (Type type in typeof(Mod).InstantiableDescendantsAndSelf()) { if (!LoadedModManager.runningModClasses.ContainsKey(type)) { ModContentPack modContentPack2 = (from modpack in LoadedModManager.runningMods where modpack.assemblies.loadedAssemblies.Contains(type.Assembly) select modpack).FirstOrDefault <ModContentPack>(); LoadedModManager.runningModClasses[type] = (Mod)Activator.CreateInstance(type, new object[] { modContentPack2 }); } } for (int j = 0; j < LoadedModManager.runningMods.Count; j++) { ModContentPack modContentPack3 = LoadedModManager.runningMods[j]; DeepProfiler.Start("Loading " + modContentPack3); modContentPack3.LoadDefs(LoadedModManager.runningMods.SelectMany((ModContentPack rm) => rm.Patches)); DeepProfiler.End(); } foreach (ModContentPack current2 in LoadedModManager.runningMods) { foreach (PatchOperation current3 in current2.Patches) { current3.Complete(current2.Name); } current2.ClearPatchesCache(); } XmlInheritance.Clear(); }
private static void RecursiveNodeCopyOverwriteElements(XmlNode child, XmlNode current) { DeepProfiler.Start("RecursiveNodeCopyOverwriteElements"); try { XmlAttribute xmlAttribute = child.Attributes["Inherit"]; if (xmlAttribute != null && xmlAttribute.Value.ToLower() == "false") { while (current.HasChildNodes) { current.RemoveChild(current.FirstChild); } foreach (XmlNode item in child) { XmlNode newChild = current.OwnerDocument.ImportNode(item, deep: true); current.AppendChild(newChild); } return; } current.Attributes.RemoveAll(); XmlAttributeCollection attributes = child.Attributes; for (int i = 0; i < attributes.Count; i++) { XmlAttribute node2 = (XmlAttribute)current.OwnerDocument.ImportNode(attributes[i], deep: true); current.Attributes.Append(node2); } List <XmlElement> list = new List <XmlElement>(); XmlNode xmlNode = null; foreach (XmlNode item2 in child) { if (item2.NodeType == XmlNodeType.Text) { xmlNode = item2; } else if (item2.NodeType == XmlNodeType.Element) { list.Add((XmlElement)item2); } } if (xmlNode != null) { DeepProfiler.Start("RecursiveNodeCopyOverwriteElements - Remove all current nodes"); for (int num = current.ChildNodes.Count - 1; num >= 0; num--) { XmlNode xmlNode3 = current.ChildNodes[num]; if (xmlNode3.NodeType != XmlNodeType.Attribute) { current.RemoveChild(xmlNode3); } } DeepProfiler.End(); XmlNode newChild2 = current.OwnerDocument.ImportNode(xmlNode, deep: true); current.AppendChild(newChild2); return; } if (!list.Any()) { bool flag = false; foreach (XmlNode childNode in current.ChildNodes) { if (childNode.NodeType == XmlNodeType.Element) { flag = true; break; } } if (flag) { return; } foreach (XmlNode childNode2 in current.ChildNodes) { if (childNode2.NodeType != XmlNodeType.Attribute) { current.RemoveChild(childNode2); } } return; } for (int j = 0; j < list.Count; j++) { XmlElement xmlElement = list[j]; if (IsListElement(xmlElement)) { XmlNode newChild3 = current.OwnerDocument.ImportNode(xmlElement, deep: true); current.AppendChild(newChild3); continue; } XmlElement xmlElement2 = current[xmlElement.Name]; if (xmlElement2 != null) { RecursiveNodeCopyOverwriteElements(xmlElement, xmlElement2); continue; } XmlNode newChild4 = current.OwnerDocument.ImportNode(xmlElement, deep: true); current.AppendChild(newChild4); } } finally { DeepProfiler.End(); } }
public void LoadData() { if (dataIsLoaded) { return; } dataIsLoaded = true; DeepProfiler.Start("Loading language data: " + folderName); try { tmpAlreadyLoadedFiles.Clear(); foreach (Tuple <VirtualDirectory, ModContentPack, string> allDirectory in AllDirectories) { Tuple <VirtualDirectory, ModContentPack, string> localDirectory = allDirectory; if (!tmpAlreadyLoadedFiles.ContainsKey(localDirectory.Item2)) { tmpAlreadyLoadedFiles[localDirectory.Item2] = new HashSet <string>(); } LongEventHandler.ExecuteWhenFinished(delegate { if (icon == BaseContent.BadTex) { VirtualFile file = localDirectory.Item1.GetFile("LangIcon.png"); if (file.Exists) { icon = ModContentLoader <Texture2D> .LoadItem(file).contentItem; } } }); VirtualDirectory directory = localDirectory.Item1.GetDirectory("CodeLinked"); if (directory.Exists) { loadErrors.Add("Translations aren't called CodeLinked any more. Please rename to Keyed: " + directory); } else { directory = localDirectory.Item1.GetDirectory("Keyed"); } if (directory.Exists) { foreach (VirtualFile file2 in directory.GetFiles("*.xml", SearchOption.AllDirectories)) { if (TryRegisterFileIfNew(localDirectory, file2.FullPath)) { LoadFromFile_Keyed(file2); } } } VirtualDirectory directory2 = localDirectory.Item1.GetDirectory("DefLinked"); if (directory2.Exists) { loadErrors.Add("Translations aren't called DefLinked any more. Please rename to DefInjected: " + directory2); } else { directory2 = localDirectory.Item1.GetDirectory("DefInjected"); } if (directory2.Exists) { foreach (VirtualDirectory directory4 in directory2.GetDirectories("*", SearchOption.TopDirectoryOnly)) { string name = directory4.Name; Type typeInAnyAssembly = GenTypes.GetTypeInAnyAssembly(name); if (typeInAnyAssembly == null && name.Length > 3) { typeInAnyAssembly = GenTypes.GetTypeInAnyAssembly(name.Substring(0, name.Length - 1)); } if (typeInAnyAssembly == null) { loadErrors.Add(string.Concat("Error loading language from ", allDirectory, ": dir ", directory4.Name, " doesn't correspond to any def type. Skipping...")); continue; } foreach (VirtualFile file3 in directory4.GetFiles("*.xml", SearchOption.AllDirectories)) { if (TryRegisterFileIfNew(localDirectory, file3.FullPath)) { LoadFromFile_DefInject(file3, typeInAnyAssembly); } } } } EnsureAllDefTypesHaveDefInjectionPackage(); VirtualDirectory directory3 = localDirectory.Item1.GetDirectory("Strings"); if (directory3.Exists) { foreach (VirtualDirectory directory5 in directory3.GetDirectories("*", SearchOption.TopDirectoryOnly)) { foreach (VirtualFile file4 in directory5.GetFiles("*.txt", SearchOption.AllDirectories)) { if (TryRegisterFileIfNew(localDirectory, file4.FullPath)) { LoadFromFile_Strings(file4, directory3); } } } } wordInfo.LoadFrom(localDirectory, this); } } catch (Exception arg) { Log.Error("Exception loading language data. Rethrowing. Exception: " + arg); throw; } finally { DeepProfiler.End(); } }
public static Map GenerateMap(IntVec3 mapSize, MapParent parent, MapGeneratorDef mapGenerator, IEnumerable <GenStepDef> extraGenStepDefs = null, Action <Map> extraInitBeforeContentGen = null) { ProgramState programState = Current.ProgramState; Current.ProgramState = ProgramState.MapInitializing; MapGenerator.playerStartSpotInt = IntVec3.Invalid; MapGenerator.rootsToUnfog.Clear(); MapGenerator.data.Clear(); MapGenerator.mapBeingGenerated = null; Map result; try { DeepProfiler.Start("InitNewGeneratedMap"); if (parent != null && parent.HasMap) { Log.Error("Tried to generate a new map and set " + parent + " as its parent, but this world object already has a map. One world object can't have more than 1 map."); parent = null; } DeepProfiler.Start("Set up map"); Map map = new Map(); map.uniqueID = Find.UniqueIDsManager.GetNextMapID(); MapGenerator.mapBeingGenerated = map; map.info.Size = mapSize; map.info.parent = parent; map.ConstructComponents(); DeepProfiler.End(); Current.Game.AddMap(map); if (extraInitBeforeContentGen != null) { extraInitBeforeContentGen(map); } if (mapGenerator == null) { mapGenerator = DefDatabase <MapGeneratorDef> .AllDefsListForReading.RandomElementByWeight((MapGeneratorDef x) => x.selectionWeight); } IEnumerable <GenStepDef> enumerable = mapGenerator.GenSteps; if (extraGenStepDefs != null) { enumerable = enumerable.Concat(extraGenStepDefs); } map.areaManager.AddStartingAreas(); map.weatherDecider.StartInitialWeather(); DeepProfiler.Start("Generate contents into map"); MapGenerator.GenerateContentsIntoMap(enumerable, map); DeepProfiler.End(); Find.Scenario.PostMapGenerate(map); DeepProfiler.Start("Finalize map init"); map.FinalizeInit(); DeepProfiler.End(); DeepProfiler.Start("MapComponent.MapGenerated()"); MapComponentUtility.MapGenerated(map); DeepProfiler.End(); if (parent != null) { parent.PostMapGenerate(); } result = map; } finally { DeepProfiler.End(); MapGenerator.mapBeingGenerated = null; Current.ProgramState = programState; } return(result); }
public static T ObjectFromXml <T>(XmlNode xmlRoot, bool doPostLoad) { XmlAttribute xmlAttribute = xmlRoot.Attributes["IsNull"]; if (xmlAttribute != null && xmlAttribute.Value.ToUpperInvariant() == "TRUE") { return(default(T)); } MethodInfo methodInfo = CustomDataLoadMethodOf(typeof(T)); if (methodInfo != null) { xmlRoot = XmlInheritance.GetResolvedNodeFor(xmlRoot); Type type = ClassTypeOf <T>(xmlRoot); currentlyInstantiatingObjectOfType.Push(type); T val; try { val = (T)Activator.CreateInstance(type); } finally { currentlyInstantiatingObjectOfType.Pop(); } try { methodInfo.Invoke(val, new object[1] { xmlRoot }); } catch (Exception ex) { Log.Error(string.Concat("Exception in custom XML loader for ", typeof(T), ". Node is:\n ", xmlRoot.OuterXml, "\n\nException is:\n ", ex.ToString())); val = default(T); } if (doPostLoad) { TryDoPostLoad(val); } return(val); } if (typeof(ISlateRef).IsAssignableFrom(typeof(T))) { try { return(ParseHelper.FromString <T>(InnerTextWithReplacedNewlinesOrXML(xmlRoot))); } catch (Exception ex2) { Log.Error(string.Concat("Exception parsing ", xmlRoot.OuterXml, " to type ", typeof(T), ": ", ex2)); } return(default(T)); } if (xmlRoot.ChildNodes.Count == 1 && xmlRoot.FirstChild.NodeType == XmlNodeType.CDATA) { if (typeof(T) != typeof(string)) { Log.Error("CDATA can only be used for strings. Bad xml: " + xmlRoot.OuterXml); return(default(T)); } return((T)(object)xmlRoot.FirstChild.Value); } if (xmlRoot.ChildNodes.Count == 1 && xmlRoot.FirstChild.NodeType == XmlNodeType.Text) { try { return(ParseHelper.FromString <T>(xmlRoot.InnerText)); } catch (Exception ex3) { Log.Error(string.Concat("Exception parsing ", xmlRoot.OuterXml, " to type ", typeof(T), ": ", ex3)); } return(default(T)); } if (Attribute.IsDefined(typeof(T), typeof(FlagsAttribute))) { List <T> list = ListFromXml <T>(xmlRoot); int num = 0; foreach (T item in list) { int num2 = (int)(object)item; num |= num2; } return((T)(object)num); } if (typeof(T).HasGenericDefinition(typeof(List <>))) { Func <XmlNode, object> value = null; if (!listFromXmlMethods.TryGetValue(typeof(T), out value)) { MethodInfo method = typeof(DirectXmlToObject).GetMethod("ListFromXmlReflection", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); Type[] genericArguments = typeof(T).GetGenericArguments(); value = (Func <XmlNode, object>)Delegate.CreateDelegate(typeof(Func <XmlNode, object>), method.MakeGenericMethod(genericArguments)); listFromXmlMethods.Add(typeof(T), value); } return((T)value(xmlRoot)); } if (typeof(T).HasGenericDefinition(typeof(Dictionary <, >))) { Func <XmlNode, object> value2 = null; if (!dictionaryFromXmlMethods.TryGetValue(typeof(T), out value2)) { MethodInfo method2 = typeof(DirectXmlToObject).GetMethod("DictionaryFromXmlReflection", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); Type[] genericArguments2 = typeof(T).GetGenericArguments(); value2 = (Func <XmlNode, object>)Delegate.CreateDelegate(typeof(Func <XmlNode, object>), method2.MakeGenericMethod(genericArguments2)); dictionaryFromXmlMethods.Add(typeof(T), value2); } return((T)value2(xmlRoot)); } if (!xmlRoot.HasChildNodes) { if (typeof(T) == typeof(string)) { return((T)(object)""); } XmlAttribute xmlAttribute2 = xmlRoot.Attributes["IsNull"]; if (xmlAttribute2 != null && xmlAttribute2.Value.ToUpperInvariant() == "TRUE") { return(default(T)); } if (typeof(T).IsGenericType) { Type genericTypeDefinition = typeof(T).GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(List <>) || genericTypeDefinition == typeof(HashSet <>) || genericTypeDefinition == typeof(Dictionary <, >)) { return(Activator.CreateInstance <T>()); } } } xmlRoot = XmlInheritance.GetResolvedNodeFor(xmlRoot); Type type2 = ClassTypeOf <T>(xmlRoot); Type type3 = Nullable.GetUnderlyingType(type2) ?? type2; currentlyInstantiatingObjectOfType.Push(type3); T val2; try { val2 = (T)Activator.CreateInstance(type3); } finally { currentlyInstantiatingObjectOfType.Pop(); } HashSet <string> hashSet = null; if (xmlRoot.ChildNodes.Count > 1) { hashSet = new HashSet <string>(); } for (int i = 0; i < xmlRoot.ChildNodes.Count; i++) { XmlNode xmlNode = xmlRoot.ChildNodes[i]; if (xmlNode is XmlComment) { continue; } if (xmlRoot.ChildNodes.Count > 1) { if (hashSet.Contains(xmlNode.Name)) { Log.Error(string.Concat("XML ", typeof(T), " defines the same field twice: ", xmlNode.Name, ".\n\nField contents: ", xmlNode.InnerText, ".\n\nWhole XML:\n\n", xmlRoot.OuterXml)); } else { hashSet.Add(xmlNode.Name); } } FieldInfo value3 = null; DeepProfiler.Start("GetFieldInfoForType"); try { value3 = GetFieldInfoForType(val2.GetType(), xmlNode.Name, xmlRoot); } finally { DeepProfiler.End(); } if (value3 == null) { DeepProfiler.Start("Field search"); try { FieldAliasCache key = new FieldAliasCache(val2.GetType(), xmlNode.Name); if (!fieldAliases.TryGetValue(key, out value3)) { FieldInfo[] fields = val2.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fields) { object[] customAttributes = fieldInfo.GetCustomAttributes(typeof(LoadAliasAttribute), inherit: true); for (int k = 0; k < customAttributes.Length; k++) { if (((LoadAliasAttribute)customAttributes[k]).alias.EqualsIgnoreCase(xmlNode.Name)) { value3 = fieldInfo; break; } } if (value3 != null) { break; } } fieldAliases.Add(key, value3); } } finally { DeepProfiler.End(); } } if (value3 != null && value3.TryGetAttribute <UnsavedAttribute>() != null && !value3.TryGetAttribute <UnsavedAttribute>().allowLoading) { Log.Error("XML error: " + xmlNode.OuterXml + " corresponds to a field in type " + val2.GetType().Name + " which has an Unsaved attribute. Context: " + xmlRoot.OuterXml); } else if (value3 == null) { DeepProfiler.Start("Field search 2"); try { bool flag = false; XmlAttribute xmlAttribute3 = xmlNode.Attributes?["IgnoreIfNoMatchingField"]; if (xmlAttribute3 != null && xmlAttribute3.Value.ToUpperInvariant() == "TRUE") { flag = true; } else { object[] customAttributes = val2.GetType().GetCustomAttributes(typeof(IgnoreSavedElementAttribute), inherit: true); for (int j = 0; j < customAttributes.Length; j++) { if (string.Equals(((IgnoreSavedElementAttribute)customAttributes[j]).elementToIgnore, xmlNode.Name, StringComparison.OrdinalIgnoreCase)) { flag = true; break; } } } if (!flag) { Log.Error("XML error: " + xmlNode.OuterXml + " doesn't correspond to any field in type " + val2.GetType().Name + ". Context: " + xmlRoot.OuterXml); } } finally { DeepProfiler.End(); } } else if (typeof(Def).IsAssignableFrom(value3.FieldType)) { if (xmlNode.InnerText.NullOrEmpty()) { value3.SetValue(val2, null); continue; } XmlAttribute xmlAttribute4 = xmlNode.Attributes["MayRequire"]; DirectXmlCrossRefLoader.RegisterObjectWantsCrossRef(val2, value3, xmlNode.InnerText, xmlAttribute4?.Value.ToLower()); } else { object obj = null; try { obj = GetObjectFromXmlMethod(value3.FieldType)(xmlNode, doPostLoad); } catch (Exception ex4) { Log.Error("Exception loading from " + xmlNode.ToString() + ": " + ex4.ToString()); continue; } if (!typeof(T).IsValueType) { value3.SetValue(val2, obj); continue; } object obj2 = val2; value3.SetValue(obj2, obj); val2 = (T)obj2; } } if (doPostLoad) { TryDoPostLoad(val2); } return(val2); }
public override void ResolveReferences() { base.ResolveReferences(); DeepProfiler.Start("Stat refs"); try { if (workTableSpeedStat == null) { workTableSpeedStat = StatDefOf.WorkTableWorkSpeedFactor; } if (workTableEfficiencyStat == null) { workTableEfficiencyStat = StatDefOf.WorkTableEfficiencyFactor; } } finally { DeepProfiler.End(); } DeepProfiler.Start("ingredients reference resolve"); try { for (int i = 0; i < ingredients.Count; i++) { ingredients[i].ResolveReferences(); } } finally { DeepProfiler.End(); } DeepProfiler.Start("fixedIngredientFilter.ResolveReferences()"); try { if (fixedIngredientFilter != null) { fixedIngredientFilter.ResolveReferences(); } } finally { DeepProfiler.End(); } DeepProfiler.Start("defaultIngredientFilter setup"); try { if (defaultIngredientFilter == null) { defaultIngredientFilter = new ThingFilter(); if (fixedIngredientFilter != null) { defaultIngredientFilter.CopyAllowancesFrom(fixedIngredientFilter); } } } finally { DeepProfiler.End(); } DeepProfiler.Start("defaultIngredientFilter.ResolveReferences()"); try { defaultIngredientFilter.ResolveReferences(); } finally { DeepProfiler.End(); } }
public void ExposeData() { Scribe_Values.Look <int>(ref this.uniqueID, "uniqueID", -1, false); Scribe_Deep.Look <MapInfo>(ref this.info, "mapInfo", new object[0]); if (Scribe.mode == LoadSaveMode.Saving) { this.compressor = new MapFileCompressor(this); this.compressor.BuildCompressedString(); this.ExposeComponents(); this.compressor.ExposeData(); HashSet <string> hashSet = new HashSet <string>(); if (Scribe.EnterNode("things")) { try { foreach (Thing thing in this.listerThings.AllThings) { try { if (thing.def.isSaveable && !thing.IsSaveCompressible()) { if (hashSet.Contains(thing.ThingID)) { Log.Error("Saving Thing with already-used ID " + thing.ThingID, false); } else { hashSet.Add(thing.ThingID); } Thing thing2 = thing; Scribe_Deep.Look <Thing>(ref thing2, "thing", new object[0]); } } catch (Exception ex) { Log.Error(string.Concat(new object[] { "Exception saving ", thing, ": ", ex }), false); } } } finally { Scribe.ExitNode(); } } else { Log.Error("Could not enter the things node while saving.", false); } this.compressor = null; } else { if (Scribe.mode == LoadSaveMode.LoadingVars) { this.ConstructComponents(); this.regionAndRoomUpdater.Enabled = false; this.compressor = new MapFileCompressor(this); } this.ExposeComponents(); DeepProfiler.Start("Load compressed things"); this.compressor.ExposeData(); DeepProfiler.End(); DeepProfiler.Start("Load non-compressed things"); Scribe_Collections.Look <Thing>(ref this.loadedFullThings, "things", LookMode.Deep, new object[0]); DeepProfiler.End(); } }
public void InitNewGame() { string str = GenText.ToCommaList(from mod in LoadedModManager.RunningMods select mod.ToString(), true); Log.Message("Initializing new game with mods " + str); if (this.maps.Any()) { Log.Error("Called InitNewGame() but there already is a map. There should be 0 maps..."); } else if (this.initData == null) { Log.Error("Called InitNewGame() but init data is null. Create it first."); } else { MemoryUtility.UnloadUnusedUnityAssets(); DeepProfiler.Start("InitNewGame"); try { Current.ProgramState = ProgramState.MapInitializing; IntVec3 intVec = new IntVec3(this.initData.mapSize, 1, this.initData.mapSize); FactionBase factionBase = null; List <FactionBase> factionBases = Find.WorldObjects.FactionBases; int num = 0; while (num < factionBases.Count) { if (factionBases[num].Faction != Faction.OfPlayer) { num++; continue; } factionBase = factionBases[num]; break; } if (factionBase == null) { Log.Error("Could not generate starting map because there is no any player faction base."); } this.tickManager.gameStartAbsTick = GenTicks.ConfiguredTicksAbsAtGameStart; Map visibleMap = MapGenerator.GenerateMap(intVec, factionBase, factionBase.MapGeneratorDef, factionBase.ExtraGenStepDefs, null); this.worldInt.info.initialMapSize = intVec; if (this.initData.permadeath) { this.info.permadeathMode = true; this.info.permadeathModeUniqueName = PermadeathModeUtility.GeneratePermadeathSaveName(); } PawnUtility.GiveAllStartingPlayerPawnsThought(ThoughtDefOf.NewColonyOptimism); this.FinalizeInit(); Current.Game.VisibleMap = visibleMap; Find.CameraDriver.JumpToVisibleMapLoc(MapGenerator.PlayerStartSpot); Find.CameraDriver.ResetSize(); if (Prefs.PauseOnLoad && this.initData.startedFromEntry) { LongEventHandler.ExecuteWhenFinished(delegate { this.tickManager.DoSingleTick(); this.tickManager.CurTimeSpeed = TimeSpeed.Paused; }); } Find.Scenario.PostGameStart(); if (Faction.OfPlayer.def.startingResearchTags != null) { foreach (string startingResearchTag in Faction.OfPlayer.def.startingResearchTags) { foreach (ResearchProjectDef allDef in DefDatabase <ResearchProjectDef> .AllDefs) { if (allDef.HasTag(startingResearchTag)) { this.researchManager.InstantFinish(allDef, false); } } } } GameComponentUtility.StartedNewGame(); this.initData = null; } finally { DeepProfiler.End(); } } }