/// <summary> /// Checks if a collection of mods satisfies this dependency. /// </summary> public bool IsMet(ModCollection mods, Version factorioVersion) { bool result; if (IsBase || IsInverted) { result = true; } else { if (HasVersionRestriction) { if (ExactRestriction) { result = mods.Contains(ModName, ModVersion); } else { var candidates = mods.Find(ModName, factorioVersion); result = candidates.Any(item => item.Version >= ModVersion); } } else { result = mods.ContainsbyFactorioVersion(ModName, factorioVersion); } } Unsatisfied = !result; OnPropertyChanged(new PropertyChangedEventArgs(nameof(Unsatisfied))); return(result); }
/// <summary> /// Activates this dependency if possible. /// </summary> public void Activate(ModCollection mods, Version factorioVersion) { if (IsBase) { return; } else if (IsInverted) { var candidates = GetTargetMods(mods, factorioVersion); foreach (var item in candidates) { item.Active = false; } } else { var candidates = GetTargetMods(mods, factorioVersion); if (!candidates.Any(item => item.Active)) { Mod max = candidates.MaxBy(item => item.Version, new VersionComparer()); if (max != null) { max.Active = true; } } } }
/// <summary> /// Loads all mods from the selected mod directory into the specified parent collection. /// </summary> /// <param name="parentCollection">The collection to contain the mods.</param> /// <param name="modpackCollection">The collection containing all modpacks.</param> public static void LoadMods(ModCollection parentCollection, ModpackCollection modpackCollection) { parentCollection.BeginUpdate(); var modDirectory = App.Instance.Settings.GetModDirectory(); if (!modDirectory.Exists) { modDirectory.Create(); } var selectedDirectories = new List <DirectoryInfo>(); foreach (var subDirectory in modDirectory.EnumerateDirectories()) { if (System.Version.TryParse(subDirectory.Name, out var factorioVersion)) { selectedDirectories.Add(subDirectory); } } var fileDictionary = CreateFileDictionary(selectedDirectories); LoadModsFromFileDictionary(fileDictionary, parentCollection, modpackCollection); parentCollection.EndUpdate(); }
private IEnumerable <Mod> GetTargetMods(ModCollection mods, Version factorioVersion) { if (HasVersionRestriction) { if (ExactRestriction) { if (mods.TryGetMod(ModName, ModVersion, out Mod mod)) { return(mod.EnumerateSingle()); } else { return(Enumerable.Empty <Mod>()); } } else { return(mods.Find(ModName, factorioVersion).Where(item => item.Version >= ModVersion)); } } else { return(mods.Find(ModName, factorioVersion)); } }
private static bool MigrateV0ToV1(ModCollection collection) { if (collection.Version > 0) { return(false); } collection.Version = 1; // Remove all completely defaulted settings from active and inactive mods. for (var i = 0; i < collection._settings.Count; ++i) { if (SettingIsDefaultV0(collection._settings[i])) { collection._settings[i] = null; } } foreach (var(key, _) in collection._unusedSettings.Where(kvp => SettingIsDefaultV0(kvp.Value)).ToList()) { collection._unusedSettings.Remove(key); } return(true); }
/// <summary> /// Checks if a collection of mods contains a mod that satisfies this dependency. /// </summary> public bool IsPresent(ModCollection mods, Version factorioVersion) { bool result = false; if (IsBase || IsInverted) { result = true; } else if (HasRestriction) { var comparison = comparisonFunctions[RestrictionComparison]; var candidates = mods.Find(ModName, factorioVersion); foreach (var candidate in candidates) { if (comparison(candidate.Version, RestrictionVersion)) { result = true; break; } } } else { result = mods.ContainsbyFactorioVersion(ModName, factorioVersion); } Unsatisfied = !result; return(result); }
public void PublishLoadResults(ModCollection modCollection) { var disabledMods = modCollection.DisabledMods.ToList(); var validMods = modCollection.ValidMods.ToList(); var invalidMods = modCollection.InvalidMods.ToList(); System.Console.WriteLine($"Summary for mods loaded:\r\n" + $"Total Mods Found - {modCollection.Mods.Count}\r\n" + $"Disabled Mods - {disabledMods.Count}\r\n" + $"Valid Mods Loaded - {validMods.Count}\r\n" + $"Invalid Mods - {invalidMods.Count}\r\n"); System.Console.WriteLine("Disabled Mods:"); disabledMods.ForEach(mod => { System.Console.WriteLine($"{mod.Name}"); }); System.Console.WriteLine(); System.Console.WriteLine("Invalid Mods:"); invalidMods.ForEach(mod => { System.Console.WriteLine($"{mod.Name}\r\n" + $"\t{string.Join("\r\n", mod.InvalidReasonList)}"); }); System.Console.WriteLine(); System.Console.WriteLine("Valid Mods Load Order : "); validMods.GroupBy(mod => mod.LoadCycle).OrderBy(mods => mods.Key).ToList().ForEach(mods => { System.Console.WriteLine($"Load Cycle [{mods.Key}]:\r\n" + $"{new string('-', 10)}\r\n" + $"{string.Join("\r\n", mods.OrderBy(mod => mod.LoadOrder).Select(mod => $"[{mod.LoadOrder,-3}] - {mod.Name}"))}\r\n"); }); }
/// <summary> /// Checks if a collection of mods contains a mod that satisfies this dependency. /// </summary> public bool IsPresent(ModCollection mods, Version factorioVersion, out Mod mod) { bool result = false; mod = null; if (IsBase || IsInverted) { result = true; } else if (HasRestriction) { var comparison = comparisonFunctions[RestrictionComparison]; var candidates = mods.Find(ModName, factorioVersion).Where(item => comparison(item.Version, RestrictionVersion)); mod = candidates.MaxBy(candidate => candidate.Version, new VersionComparer()); result = mod != null; } else { var candidates = mods.Find(ModName, factorioVersion); mod = candidates.MaxBy(candidate => candidate.Version, new VersionComparer()); result = mod != null; } return(result); }
public ArchiveSettingsScriptLoader(Func <ZipArchive, string, string> callback, ZipArchive archive, ModCollection parentCollection, InfoFile infoFile) { this.callback = callback; this.archive = archive; this.parentCollection = parentCollection; this.infoFile = infoFile; }
/// <summary> /// Activates this dependency if possible. /// </summary> public void Activate(ModCollection mods, Version factorioVersion) { if (IsBase) { return; } var candidates = mods.Find(ModName, factorioVersion); if (HasRestriction) { var comparison = comparisonFunctions[RestrictionComparison]; candidates = candidates.Where(candidate => comparison(candidate.Version, RestrictionVersion)); } if (IsInverted) { foreach (var candidate in candidates) { candidate.Active = false; } } else { if (!candidates.Any(candidate => candidate.Active, true)) { var max = candidates.MaxBy(candidate => candidate.Version, new VersionComparer()); max.Active = true; } } }
/// <summary> /// Gets all mods that are available online. /// </summary> /// <returns>Returns a list of online available mods.</returns> public static async Task <List <ModInfo> > GetModsAsync(ModCollection installedMods) { var page = await Task.Run(() => DownloadPage()); List <ModInfo> mods = new List <ModInfo>(page.Mods); foreach (var installedMod in installedMods) { if (!mods.Any(mod => mod.Name == installedMod.Name)) { try { var info = await GetExtendedInfoAsync(installedMod); mods.Add(info); } catch (WebException ex) { if (ex.Status != WebExceptionStatus.ProtocolError) { throw; } } } } if (mods == null) { mods = new List <ModInfo>(); } return(mods); }
public static void Migrate(ModCollection collection) { var changes = MigrateV0ToV1(collection); if (changes) { collection.Save(); } }
public static void SaveBinarySettings(ModCollection mods) { if (updateCount > 0) { return; } binaryFiles.Clear(); deserializedBinary.Clear(); foreach (var mod in mods) { if (mod.Active) { var binary = GetTemplate(mod.FactorioVersion); binary.AddMod(mod); } } var modDir = App.Instance.Settings.GetModDirectory(); foreach (var subDir in modDir.EnumerateDirectories()) { if (Version.TryParse(subDir.Name, out var version)) { GetTemplate(version); } } foreach (var kvp in deserializedBinary) { var version = kvp.Key; var template = kvp.Value; if (version >= BehaviourSwitch) { string json = JsonHelper.Serialize(template); var file = new BinaryFile(version, json); var dir = App.Instance.Settings.GetModDirectory(version); if (!dir.Exists) { dir.Create(); } file.Save(new FileInfo(Path.Combine(dir.FullName, "mod-settings.dat"))); } else { var dir = App.Instance.Settings.GetModDirectory(version); if (!dir.Exists) { dir.Create(); } JsonHelper.Serialize(template, new FileInfo(Path.Combine(dir.FullName, "mod-settings.json"))); } } }
public void SetCurrentCollection(ModCollection collection, bool force = false) { var idx = Array.IndexOf(_collections, collection) - 1; if (idx >= 0) { SetCurrentCollection(idx, force); } }
public static MetaChanger ChangeEqdp(ModCollection collection) { #if USE_EQDP collection.SetEqdpFiles(); return(new MetaChanger(MetaManipulation.Type.Eqdp)); #else return(new MetaChanger(MetaManipulation.Type.Unknown)); #endif }
private static void ResettleCollectionJson(Configuration config) { var collectionJson = new FileInfo(Path.Combine(config.ModDirectory, "collection.json")); if (!collectionJson.Exists) { return; } var defaultCollection = new ModCollection(); var defaultCollectionFile = defaultCollection.FileName(); if (defaultCollectionFile.Exists) { return; } try { var text = File.ReadAllText(collectionJson.FullName); var data = JArray.Parse(text); var maxPriority = 0; foreach (var setting in data.Cast <JObject>()) { var modName = ( string )setting["FolderName"] !; var enabled = ( bool )setting["Enabled"] !; var priority = ( int )setting["Priority"] !; var settings = setting["Settings"] !.ToObject <Dictionary <string, int> >() ?? setting["Conf"] !.ToObject <Dictionary <string, int> >(); var save = new ModSettings() { Enabled = enabled, Priority = priority, Settings = settings !, }; defaultCollection.Settings.Add(modName, save); maxPriority = Math.Max(maxPriority, priority); } if (!config.InvertModListOrder) { foreach (var setting in defaultCollection.Settings.Values) { setting.Priority = maxPriority - setting.Priority; } } defaultCollection.Save(); } catch (Exception e) { PluginLog.Error($"Could not migrate the old collection file to new collection files:\n{e}"); throw; } }
public GameData(ContentManager Content, GraphicsDevice device, AudioManager audio, World world) { player = new Player(world, Content, audio, device); mods = new ModCollection(); npcs = new NPCCollection(world, Content, player, device, audio); bullets = new BulletCollection(Content, device); missions = new MissionCollection(world, npcs); this.world = world; this.audio = audio; }
// Draw all rows respecting filters and using clipping. private void DrawEffectiveRows(ModCollection active, int skips, float height, bool hasFilters) { // We can use the known counts if no filters are active. var stop = hasFilters ? ImGuiClip.FilteredClippedDraw(active.ResolvedFiles, skips, CheckFilters, DrawLine) : ImGuiClip.ClippedDraw(active.ResolvedFiles, skips, DrawLine, active.ResolvedFiles.Count); var m = active.MetaCache; // If no meta manipulations are active, we can just draw the end dummy. if (m is { Count : > 0 })
private static string ResolvePath(string path, Mod.Manager _, ModCollection collection) { if (!Penumbra.Config.EnableMods) { return(path); } var gamePath = Utf8GamePath.FromString(path, out var p, true) ? p : Utf8GamePath.Empty; var ret = collection.ResolvePath(gamePath); return(ret?.ToString() ?? path); }
private int GetIndex(ModCollection collection) { var ret = _collections.IndexOf(c => c.Name == collection.Name); if (ret < 0) { PluginLog.Error($"Collection {collection.Name} is not found in collections."); return(0); } return(ret); }
private static string ResolvePath(string path, ModManager manager, ModCollection collection) { if (!Penumbra.Config.IsEnabled) { return(path); } var gamePath = new GamePath(path); var ret = collection.Cache?.ResolveSwappedOrReplacementPath(gamePath); ret ??= manager.Collections.ForcedCollection.Cache?.ResolveSwappedOrReplacementPath(gamePath); ret ??= path; return(ret); }
public ModCollection LoadModCollectionFromDirectory(string sourceDirectory) { var modCollection = new ModCollection(); Directory.EnumerateDirectories(sourceDirectory) .Where(directory => File.Exists(Path.Combine(directory, ModObjectConstants.ModFileName))) .ToList().ForEach( directory => { modCollection.AddMod(LoadModBaseFromDirectory(directory)); } ); modCollection.ProcessModDependencies(); modCollection.ProcessModLoadOrder(); return(modCollection); }
public void loadData(int loadedPlayerLevel, int loadedPlayerXP, List<Mod> loadedWeaponMods, List<Mod> loadedMods, byte[] loadedMissionLevels, byte[] loadedMissionTKinds, byte[] loadedMissionTCounts, byte[] loadedMissionZones, byte[] loadedMissionAreas, bool[] loadedMissionStates, byte[][] loadedMissionKinds, int firstModValue) { this.player.level = loadedPlayerLevel; this.player.XP = loadedPlayerXP; this.player.myWeapon.mods = loadedWeaponMods; this.mods._content = loadedMods; this.mods.firstMod = new Mod(Constants.MOD_ELM, firstModValue); this.mods.setupESpecials(); this.player.myWeapon.setup(); for (int i = 0; i < 4; i++) { this.missions[i] = new Type1Mission(loadedMissionLevels[i], loadedMissionTKinds[i], loadedMissionTCounts[i], loadedMissionZones[i], loadedMissionAreas[i], npcs.Labels, world.Labels, loadedMissionStates[i], loadedMissionKinds[i]); } }
/// <summary> /// Checks if a collection of mods satisfies this dependency and the dependency is active. /// </summary> public bool IsActive(ModCollection mods, Version factorioVersion) { if (IsBase) { return(true); } else if (IsInverted) { var candidates = GetTargetMods(mods, factorioVersion); return(candidates.All(item => !item.Active)); } else { var candidates = GetTargetMods(mods, factorioVersion); return(candidates.Any(item => item.Active)); } }
public IList <IModSetting> GetSettings(ModCollection parentCollection, IHasModSettings owner) { const string mainFileName = "settings.lua"; if (settings == null) { var script = new Script(); var data = new SettingsData(); var luaData = UserData.Create(data); script.Globals.Set("data", luaData); var modsTable = new Table(script); foreach (var mod in parentCollection.Where(m => m.FactorioVersion == InfoFile.FactorioVersion)) { modsTable.Set(DynValue.NewString(mod.Name), DynValue.True); } script.Globals.Set("mods", DynValue.NewTable(modsTable)); if (isFile) { using (var archive = ZipFile.OpenRead(file.FullName)) { script.Options.ScriptLoader = new ArchiveSettingsScriptLoader(LoadSettingsFileFromArchive, archive, parentCollection, InfoFile) { ModulePaths = new[] { "?.lua" } }; string mainFile = LoadSettingsFileFromArchive(archive, mainFileName); script.DoString(mainFile); } } else { script.Options.ScriptLoader = new DirectorySettingsScriptLoader(LoadSettingsFileFromDirectory, parentCollection, InfoFile) { ModulePaths = new[] { "?.lua" } }; string mainFile = LoadSettingsFileFromDirectory(mainFileName); script.DoString(mainFile); } settings = data.ToSettings(owner); } return(settings); }
/// <summary> /// Checks if a collection of mods satisfies this dependency and the dependency is active. /// </summary> public bool IsActive(ModCollection mods, Version factorioVersion) { if (IsBase || IsInverted) { return(true); } else if (HasRestriction) { var comparison = comparisonFunctions[RestrictionComparison]; var candidates = mods.Find(ModName, factorioVersion); return(candidates.Any(candidate => candidate.Active && comparison(candidate.Version, RestrictionVersion))); } else { var candidates = mods.Find(ModName, factorioVersion); return(candidates.Any(candidate => candidate.Active)); } }
public override void reward(Player player, ModCollection mods) { int exp = (int)(40 * (float)level / (float)player.level); exp = Math.Min(exp, 75); exp = Math.Max(exp, 1); if (player.lv != 50) { player.getEXP(exp); countXPGained += exp; } if (startLv < player.level) { mods.generate(Math.Min(player.level, level)); rewardLabel = mods.lastMod; } else rewardLabel = "-"; }
/// <summary> /// Gets all mods that are available online. /// </summary> /// <returns>Returns a list of online available mods.</returns> public static async Task <List <ModInfo> > GetModsAsync(ModCollection installedMods, int pageSize = 500) { List <ModInfo> mods = null; var pages = await Task.Run(() => DownloadAllPages(pageSize)); foreach (var page in pages) { if (mods == null) { mods = new List <ModInfo>(page.Info.ModCount + 50); } mods.AddRange(page.Mods); } foreach (var installedMod in installedMods) { if (!mods.Any(mod => mod.Name == installedMod.Name)) { try { var info = await GetExtendedInfoAsync(installedMod); mods.Add(info); } catch (WebException ex) { if (ex.Status != WebExceptionStatus.ProtocolError) { throw; } } } } if (mods == null) { mods = new List <ModInfo>(); } return(mods); }
/// <summary> /// Downloads a mod. /// </summary> /// <param name="release">The mods release to be downloaded.</param> /// <param name="username">The username.</param> /// <param name="token">The login token.</param> /// <param name="progress">A progress object used to report the progress of the operation.</param> /// <param name="cancellationToken">A cancelation token that can be used to cancel the operation.</param> /// <param name="parentCollection">The collection to contain the mods.</param> /// <param name="modpackCollection">The collection containing all modpacks.</param> public static async Task <Mod> DownloadReleaseAsync(ModRelease release, string username, string token, IProgress <double> progress, CancellationToken cancellationToken, ModCollection parentCollection, ModpackCollection modpackCollection) { DirectoryInfo modDirectory = App.Instance.Settings.GetModDirectory(release.InfoFile.FactorioVersion); if (!modDirectory.Exists) { modDirectory.Create(); } var downloadUrl = BuildUrl(release, username, token); var file = new FileInfo(Path.Combine(modDirectory.FullName, release.FileName)); try { await WebHelper.DownloadFileAsync(downloadUrl, null, file, progress, cancellationToken); if (!cancellationToken.IsCancellationRequested) { if (ModFile.TryLoadFromFile(file, out ModFile modFile)) { if (modFile.InfoFile.FactorioVersion == release.InfoFile.FactorioVersion) { return(await Mod.Add(modFile, parentCollection, modpackCollection, false)); } } throw new InvalidOperationException("The server sent an invalid mod file."); } } catch (Exception) { if (file.Exists) { file.Delete(); } throw; } return(null); }
public static async Task <List <ModInfo> > FetchMods(Window progressOwner, ModCollection installedMods) { var progressWindow = new ProgressWindow() { Owner = progressOwner }; var progressViewModel = (ProgressViewModel)progressWindow.ViewModel; progressViewModel.ActionName = App.Instance.GetLocalizedResourceString("FetchingModsAction"); progressViewModel.CanCancel = false; progressViewModel.IsIndeterminate = true; Task <List <ModInfo> > fetchModsTask = ModWebsite.GetModsAsync(installedMods); Task closeWindowTask = fetchModsTask.ContinueWith(t => progressWindow.Dispatcher.Invoke(progressWindow.Close)); progressWindow.ShowDialog(); List <ModInfo> modInfos = await fetchModsTask; await closeWindowTask; return(modInfos); }
/// <summary> /// Adds a mod to the managed mod directory. /// </summary> /// <param name="file">The mod file to be added.</param> /// <param name="parentCollection">The mod collection.</param> /// <param name="modpackCollection">The modpack collection.</param> /// <param name="copy">Specifies if the mod file should be copied or moved.</param> /// <param name="silent">Specifies if messages should be displayed.</param> /// <returns>Returns the added mod, or an existing mod if the mod that was tried to be added already existed in the managed mod directory.</returns> public static async Task <Mod> Add(ModFile file, ModCollection parentCollection, ModpackCollection modpackCollection, bool copy, bool silent = false) { var infoFile = file.InfoFile; if (parentCollection.TryGetMod(infoFile.Name, infoFile.Version, out Mod existingMod)) { if (!silent) { ShowModExistsMessage(infoFile); } return(existingMod); } if (!file.ResidesInModDirectory) { var modDirectory = App.Instance.Settings.GetModDirectory(infoFile.FactorioVersion); if (!modDirectory.Exists) { modDirectory.Create(); } if (copy) { file = await file.CopyToAsync(modDirectory.FullName); } else { await file.MoveToAsync(modDirectory.FullName); } } var newMod = new Mod(file, parentCollection, modpackCollection); parentCollection.Add(newMod); return(newMod); }
private static void LoadModsFromFileDictionary(Dictionary <string, ModFileCollection> fileDictionary, ModCollection parentCollection, ModpackCollection modpackCollection) { foreach (var modFileList in fileDictionary.Select(kvp => kvp.Value)) { var mod = new Mod(modFileList, parentCollection, modpackCollection); parentCollection.Add(mod); } }
/// <summary> /// Adds a mod to the managed mod directory. /// </summary> /// <param name="archiveFile">The mod file to be added.</param> /// <param name="parentCollection">The mod collection.</param> /// <param name="modpackCollection">The modpack collection.</param> /// <param name="copy">Specifies if the mod file should be copied or moved.</param> /// <param name="hasUid">Specifies if the mod file to be added contains a UID in its name.</param> /// <param name="silent">Specifies if messages should be displayed.</param> /// <returns>Returns the added mod, or an existing mod if the mod that was tried to be added already existed in the managed mod directory.</returns> public static async Task <Mod> Add(FileInfo archiveFile, ModCollection parentCollection, ModpackCollection modpackCollection, bool copy, bool hasUid = false, bool silent = false) { if (ModFile.TryLoadFromFile(archiveFile, out var modFile, hasUid)) { return(await Add(modFile, parentCollection, modpackCollection, copy, silent)); }
public override void reward(Player player, ModCollection modCollection) { throw new NotImplementedException(); }
public abstract void reward(Player player, ModCollection modCollection);