Ejemplo n.º 1
0
        private static void GeneratePreviewForSeed(string seed, int mapTile, int mapSize, bool revealCaves, ThreadableTexture texture)
        {
            var prevSeed = Find.World.info.seedString;

            try {
                MapRerollController.HasCavesOverride.HasCaves        = Find.World.HasCaves(mapTile);
                MapRerollController.HasCavesOverride.OverrideEnabled = true;
                Find.World.info.seedString = seed;

                MapRerollController.RandStateStackCheckingPaused = true;
                var grids = GenerateMapGrids(mapTile, mapSize, revealCaves);
                DeepProfiler.Start("generateMapPreviewTexture");
                const string terrainGenStepName = "Terrain";
                var          terrainGenStepDef  = DefDatabase <GenStepDef> .GetNamedSilentFail(terrainGenStepName);

                if (terrainGenStepDef == null)
                {
                    throw new Exception("Named GenStepDef not found: " + terrainGenStepName);
                }
                var terrainGenstep         = terrainGenStepDef.genStep;
                var riverMaker             = ReflectionCache.GenStepTerrain_GenerateRiver.Invoke(terrainGenstep, new object[] { grids.Map });
                var beachTerrainAtDelegate = (BeachMakerBeachTerrainAt)Delegate.CreateDelegate(typeof(BeachMakerBeachTerrainAt), null, ReflectionCache.BeachMaker_BeachTerrainAt);
                var riverTerrainAtDelegate = riverMaker == null ? null
                                        : (RiverMakerTerrainAt)Delegate.CreateDelegate(typeof(RiverMakerTerrainAt), riverMaker, ReflectionCache.RiverMaker_TerrainAt);
                ReflectionCache.BeachMaker_Init.Invoke(null, new object[] { grids.Map });

                var mapBounds = CellRect.WholeMap(grids.Map);
                foreach (var cell in mapBounds)
                {
                    const float rockCutoff = .7f;
                    var         terrainDef = TerrainFrom(cell, grids.Map, grids.ElevationGrid[cell], grids.FertilityGrid[cell], riverTerrainAtDelegate, beachTerrainAtDelegate, false);
                    if (!terrainColors.TryGetValue(terrainDef.defName, out Color pixelColor))
                    {
                        pixelColor = missingTerrainColor;
                    }
                    if (grids.ElevationGrid[cell] > rockCutoff && !terrainDef.IsRiver)
                    {
                        pixelColor = solidStoneColor;
                        if (grids.CavesGrid[cell] > 0)
                        {
                            pixelColor = caveColor;
                        }
                    }
                    texture.SetPixel(cell.x, cell.z, pixelColor);
                }

                AddBevelToSolidStone(texture);

                foreach (var terrainPatchMaker in grids.Map.Biome.terrainPatchMakers)
                {
                    terrainPatchMaker.Cleanup();
                }
            } catch (Exception e) {
                MapRerollController.Instance.Logger.ReportException(e, null, false, "preview generation");
            } finally {
                RockNoises.Reset();
                DeepProfiler.End();
                Find.World.info.seedString = prevSeed;
                MapRerollController.RandStateStackCheckingPaused     = false;
                MapRerollController.HasCavesOverride.OverrideEnabled = false;
                try {
                    ReflectionCache.BeachMaker_Cleanup.Invoke(null, null);
                } catch (Exception e) {
                    MapRerollController.Instance.Logger.ReportException(e, null, false, "BeachMaker preview cleanup");
                }
            }
        }
Ejemplo n.º 2
0
 public void Dispose()
 {
     DeepProfiler.End();
 }
Ejemplo n.º 3
0
 public static void End()
 {
     DeepProfiler.End();
 }
Ejemplo n.º 4
0
        public override void Generate()
        {
            Log.Message("GenStep_CaveRoof.Generate");
            if (Find.Map.Biome != Util_CaveBiome.CaveBiomeDef)
            {
                // Nothing to do in other biomes.
                return;
            }
            // Compute number of cave wells (5 for standard map 250x250, around 13 for bigest map 400x400).
            caveWellsNumber = Mathf.CeilToInt((Find.Map.Size.x * Find.Map.Size.z) / 12500);
            Log.Message("caveWellsNumber = " + caveWellsNumber);

            MapGenFloatGrid elevationGrid = MapGenerator.Elevation;

            foreach (IntVec3 cell in Find.Map.AllCells)
            {
                Thing thing = Find.EdificeGrid.InnerArray[CellIndices.CellToIndex(cell)];
                if (thing != null && thing.def.holdsRoof)
                {
                    Find.RoofGrid.SetRoof(cell, RoofDefOf.RoofRockThick);
                }
                else
                {
                    // Spawn cave roof holder.
                    GenSpawn.Spawn(Util_CaveBiome.CaveRoofDef, cell);
                }
            }

            // Update region and room to be able to use the CanReachMapEdge function.
            DeepProfiler.Start("RebuildAllRegionsBeforeCaveWells");
            RegionAndRoomUpdater.Enabled = true;
            RegionAndRoomUpdater.RebuildAllRegionsAndRooms();
            RegionAndRoomUpdater.Enabled = false;
            DeepProfiler.End();

            // Get cave wells position.
            caveWellsPosition = GetCaveWellsPosition();

            // Spawn cave wells.
            // First cave well is always dry (to avoid starting thing scattering errors).
            SpawnDryCaveWellAt(caveWellsPosition[0]);
            SpawnAnimalCorpsesMaker(caveWellsPosition[0]);
            for (int caveWellIndex = 1; caveWellIndex < caveWellsNumber; caveWellIndex++)
            {
                if (Rand.Value < 0.8f)
                {
                    // Spawn aqueous cave well.
                    SpawnAqueousCaveWellAt(caveWellsPosition[caveWellIndex]);
                }
                else if (Rand.Value < 0.9f)
                {
                    // Spawn dry cave well + fallen animal corpses.
                    SpawnDryCaveWellAt(caveWellsPosition[caveWellIndex]);
                    SpawnAnimalCorpsesMaker(caveWellsPosition[caveWellIndex]);
                }
                else
                {
                    // Spawn dry cave well + sacrificial stone.
                    SpawnDryCaveWellAt(caveWellsPosition[caveWellIndex]);
                    SpawnRitualStone(caveWellsPosition[caveWellIndex]);
                }
            }
        }
Ejemplo n.º 5
0
        internal static void LoadAllPlayData(bool recovering = false)
        {
            if (PlayDataLoader.Loaded)
            {
                Log.Error("Loading play data when already loaded. Call ClearAllPlayData first.");
            }
            else
            {
                queueRecovering      = false;
                queueLoadAllPlayData = false;

                DeepProfiler.Start("LoadAllPlayData");
                try
                {
                    DoPlayLoad();
                }
                catch (Exception ex)
                {
                    if (!Prefs.ResetModsConfigOnCrash)
                    {
                        throw;
                    }
                    else if (recovering)
                    {
                        Log.Warning("Could not recover from errors loading play data. Giving up.");
                        throw;
                    }
                    else
                    {
                        IEnumerable <ModMetaData> activeMods = ModsConfig.ActiveModsInLoadOrder;
                        if (Enumerable.Count <ModMetaData>(activeMods) == 1 && Enumerable.First <ModMetaData>(activeMods).IsCoreMod)
                        {
                            throw;
                        }
                        else
                        {
                            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: " + (object)ex);
                            try
                            {
                                PlayDataLoader.ClearAllPlayData();
                            }
                            catch
                            {
                                Log.Warning("Caught exception while recovering from errors and trying to clear all play data. Ignoring it.\nThe exception was: " + (object)ex);
                            }
                            ModsConfig.Reset();
                            CrossRefLoader.Clear();
                            PostLoadInitter.Clear();
                            PlayDataLoader.LoadAllPlayData(true);
                            return;
                        }
                    }
                }
                finally
                {
                    DeepProfiler.End();
                }
                // A14 - PlayDataLoader.loaded is now private, Loaded property is getter only
                PlayDataLoader_loaded.SetValue(null, false);
                if (!recovering)
                {
                    return;
                }
                Log.Message("Successfully recovered from errors and loaded play data.");
                DelayedErrorWindowRequest.Add(Translator.Translate("RecoveredFromErrorsText"), Translator.Translate("RecoveredFromErrorsDialogTitle"));
            }
        }
Ejemplo n.º 6
0
 static void Postfix()
 {
     DeepProfiler.End();
 }
Ejemplo n.º 7
0
        public override void Generate(Map map)
        {
            if (map.Biome != Util_CaveBiome.CaveBiomeDef)
            {
                // Nothing to do in other biomes.
                return;
            }
            // Compute number of cave wells (5 for standard map 250x250, around 13 for bigest map 400x400).
            caveWellsNumber = Mathf.CeilToInt((map.Size.x * map.Size.z) / 12500);

            MapGenFloatGrid elevationGrid = MapGenerator.Elevation;

            foreach (IntVec3 cell in map.AllCells)
            {
                Thing thing = map.edificeGrid.InnerArray[map.cellIndices.CellToIndex(cell)];
                if (thing != null && thing.def.holdsRoof)
                {
                    map.roofGrid.SetRoof(cell, RoofDefOf.RoofRockThick);
                }
                else
                {
                    // Spawn cave roof holder.
                    GenSpawn.Spawn(Util_CaveBiome.CaveRoofDef, cell, map);
                }
            }

            // Update regions and rooms to be able to use the CanReachMapEdge function to find goo cave well spots.
            DeepProfiler.Start("RebuildAllRegionsBeforeCaveWells");
            map.regionAndRoomUpdater.Enabled = true;
            map.regionAndRoomUpdater.RebuildAllRegionsAndRooms();
            map.regionAndRoomUpdater.Enabled = false;
            DeepProfiler.End();

            // Get cave wells position.
            caveWellsPosition = GetCaveWellsPosition(map);

            // Spawn cave wells.
            // First cave well is always dry (to avoid starting thing scattering errors).
            SpawnDryCaveWellWithAnimalCorpsesAt(map, caveWellsPosition[0]);
            for (int caveWellIndex = 1; caveWellIndex < caveWellsNumber; caveWellIndex++)
            {
                if (Rand.Value < 0.5f)
                {
                    // Spawn aqueous cave well.
                    SpawnAqueousCaveWellAt(map, caveWellsPosition[caveWellIndex]);
                }
                else if (Rand.Value < 0.9f)
                {
                    // Spawn dry cave well + fallen animal corpses.
                    SpawnDryCaveWellWithAnimalCorpsesAt(map, caveWellsPosition[caveWellIndex]);
                }
                else
                {
                    // Spawn dry cave well + sacrificial stone.
                    SpawnDryCaveWellWithRitualStoneAt(map, caveWellsPosition[caveWellIndex]);
                }
            }

            // TODO: should correct null region error? May be due to artificial buildings. River should avoid this.
            // Update regions and rooms now that cave wells are spawned.
            DeepProfiler.Start("RebuildAllRegionsAfterCaveWells");
            map.regionAndRoomUpdater.Enabled = true;
            map.regionAndRoomUpdater.RebuildAllRegionsAndRooms();
            map.regionAndRoomUpdater.Enabled = false;
            DeepProfiler.End();
        }
Ejemplo n.º 8
0
        public static IEnumerator ExecuteToExecuteWhenFinishedTheGoodVersion(List <Action> toExecuteWhenFinished, bool skipLast, Action <Action> actionStartCallback, Action taskFinishedCallback, Action completeCallback)
        {
            lastEnd = DateTime.Now.Ticks;
            if (LongEventHandlerMirror.CurrentlyExecutingToExecuteWhenFinished)
            {
                Log.Warning("BL: Already executing.");
            }
            else
            {
                LongEventHandlerMirror.CurrentlyExecutingToExecuteWhenFinished = true;

                if (toExecuteWhenFinished.Count > 0)
                {
                    DeepProfiler.Start("ExecuteToExecuteWhenFinished()");
                }

                for (var index = 0; index < toExecuteWhenFinished.Count + (skipLast ? -1 : 0);)
                {
                    do
                    {
                        var action = toExecuteWhenFinished[index];
                        DeepProfiler.Start($"{action.Method.DeclaringType} -> {action.Method}");
                        try
                        {
                            // _currentAction = action;
                            actionStartCallback(action);

                            action();

                            // _numTasksRun++;
                            taskFinishedCallback();
                        }
                        catch (Exception ex)
                        {
                            Log.Error("Could not execute post-long-event action. Exception: " + ex);
                        }
                        finally
                        {
                            DeepProfiler.End();
                        }

                        index++;
                        if (index >= toExecuteWhenFinished.Count)
                        {
                            break;
                        }
                    } while (DateTime.Now.Ticks - lastEnd < MAX_FRAME_DURATION); //Target 60fps

                    yield return(null);

                    lastEnd = DateTime.Now.Ticks;
                }

                try
                {
                    if (toExecuteWhenFinished.Count > 0)
                    {
                        DeepProfiler.End();
                    }

                    LongEventHandlerMirror.ToExecuteWhenFinished = new List <Action>();
                    LongEventHandlerMirror.CurrentlyExecutingToExecuteWhenFinished = false;
                }
                catch (Exception e)
                {
                    Log.Error("BL: Exception finishing up toExecuteWhenFinished! " + e);
                }
                finally
                {
                    Log.Message("[BetterLoading] TEWFH: Firing complete callback.");
                    completeCallback();
                }
            }
        }
Ejemplo n.º 9
0
        public static Quest Generate(QuestScriptDef root, Slate initialVars)
        {
            if (DeepProfiler.enabled)
            {
                DeepProfiler.Start("Generate quest");
            }
            Quest result = null;

            try
            {
                if (working)
                {
                    throw new Exception("Called Generate() while already working.");
                }
                working       = true;
                QuestGen.root = root;
                slate.Reset();
                slate.SetAll(initialVars);
                quest = Quest.MakeRaw();
                quest.ticksUntilAcceptanceExpiry = (int)(root.expireDaysRange.RandomInRange * 60000f);
                if (root.defaultChallengeRating > 0)
                {
                    quest.challengeRating = root.defaultChallengeRating;
                }
                quest.root = root;
                slate.SetIfNone("inSignal", quest.InitiateSignal);
                root.Run();
                try
                {
                    QuestNode_ResolveQuestName.Resolve();
                }
                catch (Exception arg)
                {
                    Log.Error("Error while generating quest name: " + arg);
                }
                try
                {
                    QuestNode_ResolveQuestDescription.Resolve();
                }
                catch (Exception arg2)
                {
                    Log.Error("Error while generating quest description: " + arg2);
                }
                try
                {
                    QuestNode_ResolveTextRequests.Resolve();
                }
                catch (Exception arg3)
                {
                    Log.Error("Error while resolving text requests: " + arg3);
                }
                AddSlateQuestTags();
                bool flag = root.autoAccept;
                if (flag)
                {
                    List <QuestPart> partsListForReading = quest.PartsListForReading;
                    for (int i = 0; i < partsListForReading.Count; i++)
                    {
                        if (partsListForReading[i].PreventsAutoAccept)
                        {
                            flag = false;
                            break;
                        }
                    }
                }
                if (flag)
                {
                    quest.SetInitiallyAccepted();
                }
                result = quest;
                return(result);
            }
            catch (Exception arg4)
            {
                Log.Error("Error in QuestGen: " + arg4);
                return(result);
            }
            finally
            {
                if (DeepProfiler.enabled)
                {
                    DeepProfiler.End();
                }
                quest         = null;
                QuestGen.root = null;
                working       = false;
                generatedPawns.Clear();
                textRequests.Clear();
                slate.Reset();
                questDescriptionRules.Clear();
                questDescriptionConstants.Clear();
                questNameRules.Clear();
                questNameConstants.Clear();
                slateQuestTagsToAddWhenFinished.Clear();
                ResetIdCounters();
            }
        }
Ejemplo n.º 10
0
        public static TempGameData SaveAndReload()
        {
            //SimpleProfiler.Start();
            Multiplayer.reloading = true;

            var worldGridSaved     = Find.WorldGrid;
            var worldRendererSaved = Find.World.renderer;
            var tweenedPos         = new Dictionary <int, Vector3>();
            var drawers            = new Dictionary <int, MapDrawer>();
            var localFactionId     = Multiplayer.RealPlayerFaction.loadID;
            var mapCmds            = new Dictionary <int, Queue <ScheduledCommand> >();
            var planetRenderMode   = Find.World.renderer.wantedMode;
            var chatWindow         = ChatWindow.Opened;

            var selectedData = new ByteWriter();

            SyncSerialization.WriteSync(selectedData, Find.Selector.selected.OfType <ISelectable>().ToList());

            //Multiplayer.RealPlayerFaction = Multiplayer.DummyFaction;

            foreach (Map map in Find.Maps)
            {
                drawers[map.uniqueID] = map.mapDrawer;
                //RebuildRegionsAndRoomsPatch.copyFrom[map.uniqueID] = map.regionGrid;

                foreach (Pawn p in map.mapPawns.AllPawnsSpawned)
                {
                    tweenedPos[p.thingIDNumber] = p.drawer.tweener.tweenedPos;
                }

                mapCmds[map.uniqueID] = map.AsyncTime().cmds;
            }

            mapCmds[ScheduledCommand.Global] = Multiplayer.WorldComp.cmds;

            DeepProfiler.Start("Multiplayer SaveAndReload: Save");
            //WriteElementPatch.cachedVals = new Dictionary<string, object>();
            //WriteElementPatch.id = 0;
            var gameData = SaveGameData();

            DeepProfiler.End();
            //Log.Message($"Saving took {WriteElementPatch.cachedVals.Count} {WriteElementPatch.cachedVals.FirstOrDefault()}");

            MapDrawerRegenPatch.copyFrom      = drawers;
            WorldGridCachePatch.copyFrom      = worldGridSaved;
            WorldGridExposeDataPatch.copyFrom = worldGridSaved;
            WorldRendererCachePatch.copyFrom  = worldRendererSaved;

            MusicManagerPlay musicManager = null;

            if (Find.MusicManagerPlay.gameObjectCreated)
            {
                var musicTransform = Find.MusicManagerPlay.audioSource.transform;
                if (musicTransform.parent == Find.Root.soundRoot.sourcePool.sourcePoolCamera.cameraSourcesContainer.transform)
                {
                    musicTransform.parent = musicTransform.parent.parent;
                }

                musicManager = Find.MusicManagerPlay;
            }

            //SpawnSetupPatch.total = 0;
            //SpawnSetupPatch.total2 = new long[SpawnSetupPatch.total2.Length];

            LoadInMainThread(gameData);

            if (musicManager != null)
            {
                Current.Root_Play.musicManagerPlay = musicManager;
            }

            Multiplayer.RealPlayerFaction = Find.FactionManager.GetById(localFactionId);

            foreach (Map m in Find.Maps)
            {
                foreach (Pawn p in m.mapPawns.AllPawnsSpawned)
                {
                    if (tweenedPos.TryGetValue(p.thingIDNumber, out Vector3 v))
                    {
                        p.drawer.tweener.tweenedPos    = v;
                        p.drawer.tweener.lastDrawFrame = Time.frameCount;
                    }
                }

                m.AsyncTime().cmds = mapCmds[m.uniqueID];
            }

            if (chatWindow != null)
            {
                Find.WindowStack.Add_KeepRect(chatWindow);
            }

            var selectedReader = new ByteReader(selectedData.ToArray())
            {
                context = new MpContext()
                {
                    map = Find.CurrentMap
                }
            };

            Find.Selector.selected = SyncSerialization.ReadSync <List <ISelectable> >(selectedReader).AllNotNull().Cast <object>().ToList();

            Find.World.renderer.wantedMode = planetRenderMode;
            Multiplayer.WorldComp.cmds     = mapCmds[ScheduledCommand.Global];

            Multiplayer.reloading = false;
            //SimpleProfiler.Pause();

            //Log.Message($"allocs {(double)SpawnSetupPatch.total2.Sum() / Stopwatch.Frequency * 1000} ({SpawnSetupPatch.total2.Select((l,i) => $"{SpawnSetupPatch.methods[i]}: {(double)l / Stopwatch.Frequency * 1000}").Join(delimiter: "\n")}) {SpawnSetupPatch.total} {AllocsPrefixClass.allocs} {CustomXmlElement.n} {CustomXmlElement.m} {CustomXmlElement.n - CustomXmlElement.m} {(double)CustomXmlElement.n/CustomXmlElement.m}");

            return(gameData);
        }
Ejemplo n.º 11
0
        public RIMMSAssemble(ModContentPack content) : base(content)
        {
            //Log.Message("starting rimmsassemble");

            //moving the new handler to the front since rimworlds handler is bugged and breaks the processing
            EventInfo           ei  = typeof(AppDomain).GetEvent("AssemblyResolve");
            FieldInfo           fi  = typeof(AppDomain).GetField("AssemblyResolve", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            ResolveEventHandler eh  = fi.GetValue(AppDomain.CurrentDomain) as ResolveEventHandler;
            List <Delegate>     lst = new List <Delegate>(eh.GetInvocationList());

            foreach (Delegate del in lst)
            {
                ei.GetRemoveMethod().Invoke(AppDomain.CurrentDomain, new object[] { del });
            }

            ResolveEventHandler reh = (object sender, ResolveEventArgs args) => {
                if (args.Name.IndexOf(" Version=") < 0)
                {
                    return(null);
                }

                //Log.Message("Custom assembly resolver: "+sender+" "+args+" "+args.Name);

                try {
                    AssemblyName an = new AssemblyName(args.Name);
                    an.Version = null;
                    return(Assembly.Load(an));
                } catch (Exception exception) {
                    Log.Error(exception.Message);
                }
                return(null);
            };

            AppDomain.CurrentDomain.AssemblyResolve += reh;

            foreach (Delegate del in lst)
            {
                ei.GetAddMethod().Invoke(AppDomain.CurrentDomain, new object[] { del });
            }

            //At this point assemblies that do not have types whose definition is not dependant on other assemblies will work.
            //However if a class is defined with a type dependancy the assembly loading crashed during earlier AssemblyIsUsable.
            //Therefore those assemblies must be renamed and only loaded after the assembly resolver is in place.
            //This also means we must take over the mod loading loop to ensure mods are loaded in proper order since assemblies are no longer loaded in order.
            List <Type> allExistingModClasses = new List <Type>(typeof(Mod).InstantiableDescendantsAndSelf());
            Dictionary <Assembly, ModContentPack> loadedAssemblies = new Dictionary <Assembly, ModContentPack>();
            MethodInfo miAssemblyIsUsable = typeof(ModAssemblyHandler).GetMethod("AssemblyIsUsable", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

            foreach (ModContentPack modContentPack in LoadedModManager.RunningMods)
            {
                ModAssemblyHandler            ass = modContentPack.assemblies;
                Dictionary <string, FileInfo> assFilesInAssemblyFolder = ModContentPack.GetAllFilesForMod(modContentPack, "Assemblies/", s => s.ToLower() == ".ass");
                if (assFilesInAssemblyFolder == null || assFilesInAssemblyFolder.Count == 0)
                {
                    continue;
                }
                foreach (FileInfo fileInfo in assFilesInAssemblyFolder.Values)
                {
                    Assembly assembly = null;
                    try {
                        byte[]   rawAssembly = File.ReadAllBytes(fileInfo.FullName);
                        string   fileName    = Path.Combine(fileInfo.DirectoryName, Path.GetFileNameWithoutExtension(fileInfo.FullName)) + ".pdb";
                        FileInfo fileInfo2   = new FileInfo(fileName);
                        if (fileInfo2.Exists)
                        {
                            byte[] rawSymbolStore = File.ReadAllBytes(fileInfo2.FullName);
                            assembly = AppDomain.CurrentDomain.Load(rawAssembly, rawSymbolStore);
                        }
                        else
                        {
                            assembly = AppDomain.CurrentDomain.Load(rawAssembly);
                        }
                    } catch (Exception ex) {
                        Log.Error("Exception loading " + fileInfo.Name + ": " + ex.ToString(), false);
                        break;
                    }
                    Log.Message("testing assembly: " + assembly + " " + ass.loadedAssemblies.Contains(assembly));
                    if (assembly != null && !ass.loadedAssemblies.Contains(assembly))
                    {
                        if ((bool)miAssemblyIsUsable.Invoke(ass, new Object[] { assembly }))
                        {
                            ass.loadedAssemblies.Add(assembly);
                            loadedAssemblies.Add(assembly, modContentPack);
                            //Log.Message("Loading ass assembly: "+assembly.FullName);
                        }
                        else
                        {
                            Log.Message("Unusable ass assemble: " + assembly.FullName);
                        }
                    }
                }
            }

            if (loadedAssemblies.Count > 0)
            {
                //Reordering the mod classes and initializing them in order while filling runningModClasses will end the initial loop in createmodclasses() and load mods in the right order.
                Log.Message("Found ass assemblies. Creating new mod classes via custom loop.");
                List <Type>            modTypesSorted    = new List <Type>();
                List <ModContentPack>  modsOrdered       = LoadedModManager.RunningModsListForReading;
                Dictionary <Type, Mod> runningModClasses = (Dictionary <Type, Mod>) typeof(LoadedModManager).GetField("runningModClasses", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static)
                                                           .GetValue(null);
                foreach (Type type in typeof(Mod).InstantiableDescendantsAndSelf())
                {
                    if (!runningModClasses.ContainsKey(type) && !modTypesSorted.Contains(type) && type != typeof(RIMMSAssemble))
                    {
                        modTypesSorted.Add(type);
                    }
                }
                modTypesSorted.SortBy <Type, int>(t => modsOrdered.FirstIndexOf(m => m.assemblies.loadedAssemblies.Contains(t.Assembly)));

                List <ModContentPack> .Enumerator enumerator = modsOrdered.GetEnumerator();
                foreach (Type type in modTypesSorted)
                {
                    DeepProfiler.Start("Loading " + type + " mod class");
                    try
                    {
                        while (enumerator.MoveNext() && !enumerator.Current.assemblies.loadedAssemblies.Contains(type.Assembly))
                        {
                        }
                        if (enumerator.Current != null)
                        {
                            runningModClasses[type] = (Mod)Activator.CreateInstance(type, new object[] { enumerator.Current });
                        }
                        else
                        {
                            Log.Error("Failed to match ModContentPack to assembly!");
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error(string.Concat(new object[]
                        {
                            "Error while instantiating a mod of type ",
                            type,
                            ": ",
                            ex
                        }), false);
                    }
                    finally
                    {
                        DeepProfiler.End();
                    }
                }
            }            /* else {
                          *     Log.Message("No new assemblies found, continuing with normal loading.");
                          * }*/
        }