Пример #1
0
        public static void LoadTextPacks(IEnumerable <ContentPackage> selectedContentPackages)
        {
            HashSet <string> newLanguages = new HashSet <string>();
            Dictionary <string, List <TextPack> > newTextPacks = new Dictionary <string, List <TextPack> >();

            var textFiles = ContentPackage.GetFilesOfType(selectedContentPackages, ContentType.Text).ToList();

            foreach (ContentFile file in textFiles)
            {
#if !DEBUG
                try
                {
#endif
                var textPack = new TextPack(file.Path);
                newLanguages.Add(textPack.Language);
                if (!newTextPacks.ContainsKey(textPack.Language))
                {
                    newTextPacks.Add(textPack.Language, new List <TextPack>());
                }
                newTextPacks[textPack.Language].Add(textPack);
#if !DEBUG
            }
            catch (Exception e)
            {
                DebugConsole.ThrowError("Failed to load text file \"" + file.Path + "\"!", e);
            }
#endif
            }

            if (newTextPacks.Count == 0)
            {
                DebugConsole.ThrowError("No text files available in any of the selected content packages. Attempting to find a vanilla English text file...");
                if (!File.Exists(VanillaTextFilePath))
                {
                    throw new Exception("No text files found in any of the selected content packages or in the default text path!");
                }
                var textPack = new TextPack(VanillaTextFilePath);
                newLanguages.Add(textPack.Language);
                newTextPacks.Add(textPack.Language, new List <TextPack>()
                {
                    textPack
                });
            }

            if (newTextPacks.Count == 0)
            {
                throw new Exception("Failed to load text packs!");
            }

            lock (mutex)
            {
                textPacks          = newTextPacks;
                availableLanguages = newLanguages;
                DebugConsole.NewMessage("Loaded languages: " + string.Join(", ", newLanguages));
            }

            Initialized = true;
        }
Пример #2
0
        public static bool LoadFromFile(string filePath, ContentPackage contentPackage, bool forceOverride = false)
        {
            XDocument doc = XMLExtensions.TryLoadXml(filePath);

            if (doc == null)
            {
                DebugConsole.ThrowError($"Loading character file failed: {filePath}");
                return(false);
            }
            if (Prefabs.AllPrefabs.Any(kvp => kvp.Value.Any(cf => cf?.FilePath == filePath)))
            {
                DebugConsole.ThrowError($"Duplicate path: {filePath}");
                return(false);
            }
            XElement mainElement = doc.Root;

            if (doc.Root.IsCharacterVariant())
            {
                if (!CheckSpeciesName(mainElement, filePath, out string n))
                {
                    return(false);
                }
                string inherit = mainElement.GetAttributeString("inherit", null);
                string id      = n.ToLowerInvariant();
                Prefabs.Add(new CharacterPrefab
                {
                    Name           = n,
                    OriginalName   = n,
                    Identifier     = id,
                    FilePath       = filePath,
                    ContentPackage = contentPackage,
                    XDocument      = doc,
                    VariantOf      = inherit
                }, isOverride: false);
                return(true);
            }
            else if (doc.Root.IsOverride())
            {
                mainElement = doc.Root.FirstElement();
            }
            if (!CheckSpeciesName(mainElement, filePath, out string name))
            {
                return(false);
            }
            string identifier = name.ToLowerInvariant();

            Prefabs.Add(new CharacterPrefab
            {
                Name           = name,
                OriginalName   = name,
                Identifier     = identifier,
                FilePath       = filePath,
                ContentPackage = contentPackage,
                XDocument      = doc
            }, forceOverride || doc.Root.IsOverride());

            return(true);
        }
Пример #3
0
        public static ContentPackage CreatePackage(string name)
        {
            ContentPackage newPackage = new ContentPackage("Content/Data/" + name);

            newPackage.name = name;
            newPackage.Path = Folder + name;
            list.Add(newPackage);

            return(newPackage);
        }
Пример #4
0
        public static string GetFolder(string speciesName, ContentPackage contentPackage = null)
        {
            string configFilePath = Character.GetConfigFile(speciesName, contentPackage);
            var    folder         = XMLExtensions.TryLoadXml(configFilePath)?.Root?.Element("ragdolls")?.GetAttributeString("folder", string.Empty);

            if (string.IsNullOrEmpty(folder) || folder.ToLowerInvariant() == "default")
            {
                folder = Path.Combine(Path.GetDirectoryName(configFilePath), "Ragdolls") + Path.DirectorySeparatorChar;
            }
            return(folder);
        }
Пример #5
0
 /// <summary>
 /// Returns the file paths of all files of the given type in the content packages.
 /// </summary>
 /// <param name="type"></param>
 /// <param name="searchAllContentPackages">If true, also returns files in content packages that are installed but not currently selected.</param>
 public IEnumerable <string> GetFilesOfType(ContentType type, bool searchAllContentPackages = false)
 {
     if (searchAllContentPackages)
     {
         return(ContentPackage.GetFilesOfType(ContentPackage.List, type));
     }
     else
     {
         return(ContentPackage.GetFilesOfType(SelectedPackages, type));
     }
 }
Пример #6
0
 /// <summary>
 /// Returns the file paths of all files of the given type in the content packages.
 /// </summary>
 /// <param name="type"></param>
 /// <param name="searchAllContentPackages">If true, also returns files in content packages that are installed but not currently selected.</param>
 public IEnumerable <ContentFile> GetFilesOfType(ContentType type, bool searchAllContentPackages = false)
 {
     if (searchAllContentPackages)
     {
         return(ContentPackage.GetFilesOfType(ContentPackage.AllPackages, type));
     }
     else
     {
         return(ContentPackage.GetFilesOfType(Config.AllEnabledPackages, type));
     }
 }
Пример #7
0
 public static void RemovePackage(ContentPackage package)
 {
     if (package.IsCorePackage)
     {
         corePackages.RemoveOnMainThread(package);
     }
     else
     {
         regularPackages.RemoveOnMainThread(package);
     }
 }
Пример #8
0
        public static string GetFolder(string speciesName, ContentPackage contentPackage = null)
        {
            var folder = XMLExtensions.TryLoadXml(Character.GetConfigFile(speciesName, contentPackage))?.Root?.Element("ragdolls")?.GetAttributeString("folder", string.Empty);

            if (string.IsNullOrEmpty(folder) || folder.ToLowerInvariant() == "default")
            {
                //DebugConsole.NewMessage("[RagollParams] Using the default folder.");
                folder = GetDefaultFolder(speciesName);
            }
            return(folder);
        }
Пример #9
0
        public static ContentPackage CreatePackage(string name, string path, bool corePackage)
        {
            ContentPackage newPackage = new ContentPackage()
            {
                Name          = name,
                Path          = path,
                isCorePackage = corePackage,
                GameVersion   = GameMain.Version
            };

            return(newPackage);
        }
Пример #10
0
 public static void AddPackage(ContentPackage newPackage)
 {
     if (corePackages.Concat(regularPackages).Any(p => p.Name.Equals(newPackage.Name, StringComparison.OrdinalIgnoreCase)))
     {
         DebugConsole.ThrowError($"Attempted to add \"{newPackage.Name}\" more than once!\n{Environment.StackTrace}");
     }
     if (newPackage.IsCorePackage)
     {
         corePackages.AddOnMainThread(newPackage);
     }
     else
     {
         regularPackages.AddOnMainThread(newPackage);
     }
 }
Пример #11
0
        public GameSettings()
        {
            ContentPackage.LoadAll(ContentPackage.Folder);
            CompletedTutorialNames = new List <string>();

            LoadDefaultConfig();

            if (WasGameUpdated)
            {
                UpdaterUtil.CleanOldFiles();
                WasGameUpdated = false;
                SaveNewDefaultConfig();
            }

            LoadPlayerConfig();
        }
Пример #12
0
        public static void Init()
        {
            var files = ContentPackage.GetFilesOfType(GameMain.Config.SelectedContentPackages, ContentType.MapGenerationParameters);

            if (!files.Any())
            {
                DebugConsole.ThrowError("No map generation parameters found in the selected content packages!");
                return;
            }
            // Let's not actually load the parameters until we have solved which file is the last, because loading the parameters takes some resources that would also need to be released.
            XElement selectedElement = null;

            foreach (string file in files)
            {
                XDocument doc = XMLExtensions.TryLoadXml(file);
                if (doc == null)
                {
                    continue;
                }
                var mainElement = doc.Root;
                if (doc.Root.IsOverride())
                {
                    mainElement = doc.Root.FirstElement();
                    if (selectedElement != null)
                    {
                        DebugConsole.NewMessage($"Overriding the map generation parameters with '{file}'", Color.Yellow);
                    }
                }
                else if (selectedElement != null)
                {
                    DebugConsole.ThrowError($"Error in {file}: Another map generation parameter file already loaded! Use <override></override> tags to override it.");
                    break;
                }
                selectedElement = mainElement;
            }
            if (selectedElement == null)
            {
                DebugConsole.ThrowError("Could not find a valid element in the map generation parameter files!");
            }
            else
            {
                instance = new MapGenerationParams(selectedElement);
            }
        }
Пример #13
0
        public static bool LoadFromFile(string filePath, ContentPackage contentPackage, bool forceOverride = false)
        {
            XDocument doc = XMLExtensions.TryLoadXml(filePath);

            if (doc == null)
            {
                DebugConsole.ThrowError($"Loading character file failed: {filePath}");
                return(false);
            }
            if (Prefabs.AllPrefabs.Any(kvp => kvp.Value.Any(cf => cf?.FilePath == filePath)))
            {
                DebugConsole.ThrowError($"Duplicate path: {filePath}");
                return(false);
            }
            XElement mainElement = doc.Root.IsOverride() ? doc.Root.FirstElement() : doc.Root;
            var      name        = mainElement.GetAttributeString("name", null);

            if (name != null)
            {
                DebugConsole.NewMessage($"Error in {filePath}: 'name' is deprecated! Use 'speciesname' instead.", Color.Orange);
            }
            else
            {
                name = mainElement.GetAttributeString("speciesname", string.Empty);
            }
            if (string.IsNullOrWhiteSpace(name))
            {
                DebugConsole.ThrowError($"No species name defined for: {filePath}");
                return(false);
            }
            var identifier = name.ToLowerInvariant();

            Prefabs.Add(new CharacterPrefab
            {
                Name           = name,
                OriginalName   = name,
                Identifier     = identifier,
                FilePath       = filePath,
                ContentPackage = contentPackage,
                XDocument      = doc
            }, forceOverride || doc.Root.IsOverride());

            return(true);
        }
Пример #14
0
        private bool SelectContentPackage(GUITickBox tickBox)
        {
            var contentPackage = tickBox.UserData as ContentPackage;

            if (contentPackage.CorePackage)
            {
                if (tickBox.Selected)
                {
                    //make sure no other core packages are selected
                    SelectedContentPackages.RemoveWhere(cp => cp.CorePackage && cp != contentPackage);
                    SelectedContentPackages.Add(contentPackage);
                    foreach (GUITickBox otherTickBox in tickBox.Parent.Children)
                    {
                        ContentPackage otherContentPackage = otherTickBox.UserData as ContentPackage;
                        if (otherContentPackage == contentPackage)
                        {
                            continue;
                        }
                        otherTickBox.Selected = SelectedContentPackages.Contains(otherContentPackage);
                    }
                }
                else if (SelectedContentPackages.Contains(contentPackage))
                {
                    //core packages cannot be deselected, only switched by selecting another core package
                    new GUIMessageBox(TextManager.Get("Warning"), TextManager.Get("CorePackageRequiredWarning"));
                    tickBox.Selected = true;
                    return(true);
                }
            }
            else
            {
                if (tickBox.Selected)
                {
                    SelectedContentPackages.Add(contentPackage);
                }
                else
                {
                    SelectedContentPackages.Remove(contentPackage);
                }
            }
            UnsavedSettings = true;
            return(true);
        }
Пример #15
0
        public void Load(string filePath)
        {
            XDocument doc = XMLExtensions.TryLoadXml(filePath);

            if (doc == null)
            {
                DebugConsole.ThrowError("No config file found");

                MasterServerUrl = "";

                SelectedContentPackage = ContentPackage.list.Any() ? ContentPackage.list[0] : new ContentPackage("");

                return;
            }

            MasterServerUrl = doc.Root.GetAttributeString("masterserverurl", "");

            AutoCheckUpdates = doc.Root.GetAttributeBool("autocheckupdates", true);
            WasGameUpdated   = doc.Root.GetAttributeBool("wasgameupdated", false);

            VerboseLogging = doc.Root.GetAttributeBool("verboselogging", false);

            InitProjSpecific(doc);

            foreach (XElement subElement in doc.Root.Elements())
            {
                switch (subElement.Name.ToString().ToLowerInvariant())
                {
                case "contentpackage":
                    string path = subElement.GetAttributeString("path", "");


                    SelectedContentPackage = ContentPackage.list.Find(cp => cp.Path == path);

                    if (SelectedContentPackage == null)
                    {
                        SelectedContentPackage = new ContentPackage(path);
                    }
                    break;
                }
            }
        }
Пример #16
0
        public static void LoadTextPacks(IEnumerable <ContentPackage> selectedContentPackages)
        {
            availableLanguages.Clear();
            textPacks.Clear();
            var textFiles = ContentPackage.GetFilesOfType(selectedContentPackages, ContentType.Text);

            foreach (string file in textFiles)
            {
                try
                {
                    var textPack = new TextPack(file);
                    availableLanguages.Add(textPack.Language);
                    if (!textPacks.ContainsKey(textPack.Language))
                    {
                        textPacks.Add(textPack.Language, new List <TextPack>());
                    }
                    textPacks[textPack.Language].Add(textPack);
                }
                catch (Exception e)
                {
                    DebugConsole.ThrowError("Failed to load text file \"" + file + "\"!", e);
                }
            }

            if (textPacks.Count == 0)
            {
                DebugConsole.ThrowError("No text files available in any of the selected content packages. Attempting to find a vanilla English text file...");
                if (!File.Exists(VanillaTextFilePath))
                {
                    throw new Exception("No text files found in any of the selected content packages or in the default text path!");
                }
                var textPack = new TextPack(VanillaTextFilePath);
                availableLanguages.Add(textPack.Language);
                textPacks.Add(textPack.Language, new List <TextPack>()
                {
                    textPack
                });
            }
            Initialized = true;
        }
Пример #17
0
        public static void Init()
        {
            var files = ContentPackage.GetFilesOfType(GameMain.Config.SelectedContentPackages, ContentType.MapGenerationParameters);

            if (!files.Any())
            {
                DebugConsole.ThrowError("No map generation parameters found in the selected content packages!");
                return;
            }

            foreach (string file in files)
            {
                XDocument doc = XMLExtensions.TryLoadXml(file);
                if (doc?.Root == null)
                {
                    return;
                }

                instance = new MapGenerationParams(doc.Root);
                break;
            }
        }
Пример #18
0
        public static void LoadAll(string folder)
        {
            if (!Directory.Exists(folder))
            {
                try
                {
                    Directory.CreateDirectory(folder);
                }
                catch
                {
                    return;
                }
            }

            string[] files = Directory.GetFiles(folder, "*.xml");

            list.Clear();

            foreach (string filePath in files)
            {
                ContentPackage package = new ContentPackage(filePath);
                list.Add(package);
            }
        }
Пример #19
0
        private void ShowCreateItemFrame()
        {
            createItemFrame.ClearChildren();

            if (itemEditor == null)
            {
                return;
            }

            var createItemContent = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.9f), createItemFrame.RectTransform, Anchor.Center))
            {
                RelativeSpacing = 0.02f
            };

            new GUITextBlock(new RectTransform(new Vector2(0.2f, 0.05f), createItemContent.RectTransform), "Title");
            var titleBox = new GUITextBox(new RectTransform(new Vector2(0.8f, 0.05f), createItemContent.RectTransform), itemEditor.Title);

            new GUITextBlock(new RectTransform(new Vector2(0.2f, 0.05f), createItemContent.RectTransform), "Description");
            var descriptionBox = new GUITextBox(new RectTransform(new Vector2(0.8f, 0.1f), createItemContent.RectTransform), itemEditor.Description);

            descriptionBox.OnTextChanged += (textBox, text) => { itemEditor.Description = text; return(true); };

            new GUIButton(new RectTransform(new Vector2(0.25f, 0.05f), createItemContent.RectTransform, Anchor.TopRight), "Show folder")
            {
                IgnoreLayoutGroups = true,
                OnClicked          = (btn, userdata) => { System.Diagnostics.Process.Start(Path.GetFullPath(SteamManager.WorkshopItemStagingFolder)); return(true); }
            };

            new GUITextBlock(new RectTransform(new Vector2(0.2f, 0.05f), createItemContent.RectTransform), "Files included in the item");
            createItemFileList = new GUIListBox(new RectTransform(new Vector2(0.8f, 0.4f), createItemContent.RectTransform));
            RefreshCreateItemFileList();

            new GUIButton(new RectTransform(new Vector2(0.25f, 0.05f), createItemContent.RectTransform, Anchor.TopRight), "Refresh")
            {
                OnClicked = (btn, userdata) =>
                {
                    itemContentPackage = new ContentPackage(itemContentPackage.Path);
                    RefreshCreateItemFileList();
                    return(true);
                }
            };

            new GUIButton(new RectTransform(new Vector2(0.25f, 0.05f), createItemContent.RectTransform, Anchor.BottomRight),
                          "Publish item")
            {
                IgnoreLayoutGroups = true,
                OnClicked          = (btn, userData) =>
                {
                    itemEditor.Title       = titleBox.Text;
                    itemEditor.Description = descriptionBox.Text;
                    if (string.IsNullOrWhiteSpace(itemEditor.Title))
                    {
                        titleBox.Flash(Color.Red);
                        return(false);
                    }
                    if (string.IsNullOrWhiteSpace(itemEditor.Description))
                    {
                        descriptionBox.Flash(Color.Red);
                        return(false);
                    }
                    PublishWorkshopItem();
                    return(true);
                }
            };
        }
Пример #20
0
        public static void Init()
        {
            List.Clear();
            var locationTypeFiles = GameMain.Instance.GetFilesOfType(ContentType.LocationTypes);

            if (!locationTypeFiles.Any())
            {
                DebugConsole.ThrowError("No location types configured in any of the selected content packages. Attempting to load from the vanilla content package...");
                locationTypeFiles = ContentPackage.GetFilesOfType(GameMain.VanillaContent.ToEnumerable(), ContentType.LocationTypes);
                if (!locationTypeFiles.Any())
                {
                    throw new Exception("No location types configured in any of the selected content packages. Please try uninstalling mods or reinstalling the game.");
                }
            }

            foreach (ContentFile file in locationTypeFiles)
            {
                XDocument doc = XMLExtensions.TryLoadXml(file.Path);
                if (doc == null)
                {
                    continue;
                }
                var mainElement = doc.Root;
                if (doc.Root.IsOverride())
                {
                    mainElement = doc.Root.FirstElement();
                    DebugConsole.NewMessage($"Overriding all location types with '{file.Path}'", Color.Yellow);
                    List.Clear();
                }
                else if (List.Any())
                {
                    DebugConsole.NewMessage($"Loading additional location types from file '{file.Path}'");
                }
                foreach (XElement sourceElement in mainElement.Elements())
                {
                    var  element         = sourceElement;
                    bool allowOverriding = false;
                    if (sourceElement.IsOverride())
                    {
                        element         = sourceElement.FirstElement();
                        allowOverriding = true;
                    }
                    string identifier = element.GetAttributeString("identifier", null);
                    if (string.IsNullOrWhiteSpace(identifier))
                    {
                        DebugConsole.ThrowError($"Error in '{file.Path}': No identifier defined for {element.Name.ToString()}");
                        continue;
                    }
                    var duplicate = List.FirstOrDefault(l => l.Identifier == identifier);
                    if (duplicate != null)
                    {
                        if (allowOverriding)
                        {
                            List.Remove(duplicate);
                            DebugConsole.NewMessage($"Overriding the location type with the identifier '{identifier}' with '{file.Path}'", Color.Yellow);
                        }
                        else
                        {
                            DebugConsole.ThrowError($"Error in '{file.Path}': Duplicate identifier defined with the identifier '{identifier}'");
                            continue;
                        }
                    }
                    LocationType locationType = new LocationType(element);
                    List.Add(locationType);
                }
            }

            foreach (EventSet eventSet in EventSet.List)
            {
                eventSet.CheckLocationTypeErrors();
            }
        }
Пример #21
0
        public LevelEditorScreen()
        {
            cam = new Camera()
            {
                MinZoom = 0.01f,
                MaxZoom = 1.0f
            };

            leftPanel = new GUIFrame(new RectTransform(new Vector2(0.125f, 0.8f), Frame.RectTransform)
            {
                MinSize = new Point(150, 0)
            });
            var paddedLeftPanel = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.95f), leftPanel.RectTransform, Anchor.CenterLeft)
            {
                RelativeOffset = new Vector2(0.02f, 0.0f)
            })
            {
                Stretch         = true,
                RelativeSpacing = 0.01f
            };

            paramsList             = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.3f), paddedLeftPanel.RectTransform));
            paramsList.OnSelected += (GUIComponent component, object obj) =>
            {
                selectedParams = obj as LevelGenerationParams;
                editorContainer.ClearChildren();
                SortLevelObjectsList(selectedParams);
                new SerializableEntityEditor(editorContainer.Content.RectTransform, selectedParams, false, true, elementHeight: 20);
                return(true);
            };

            var ruinTitle = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedLeftPanel.RectTransform), TextManager.Get("leveleditor.ruinparams"), font: GUI.SubHeadingFont);

            ruinParamsList             = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.1f), paddedLeftPanel.RectTransform));
            ruinParamsList.OnSelected += (GUIComponent component, object obj) =>
            {
                var ruinGenerationParams = obj as RuinGenerationParams;
                editorContainer.ClearChildren();
                new SerializableEntityEditor(editorContainer.Content.RectTransform, ruinGenerationParams, false, true, elementHeight: 20);
                return(true);
            };

            var outpostTitle = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedLeftPanel.RectTransform), TextManager.Get("leveleditor.outpostparams"), font: GUI.SubHeadingFont);

            GUITextBlock.AutoScaleAndNormalize(ruinTitle, outpostTitle);

            outpostParamsList             = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.2f), paddedLeftPanel.RectTransform));
            outpostParamsList.OnSelected += (GUIComponent component, object obj) =>
            {
                var outpostGenerationParams = obj as OutpostGenerationParams;
                editorContainer.ClearChildren();
                var outpostParamsEditor = new SerializableEntityEditor(editorContainer.Content.RectTransform, outpostGenerationParams, false, true, elementHeight: 20);

                // location type -------------------------

                var locationTypeGroup = new GUILayoutGroup(new RectTransform(new Point(editorContainer.Content.Rect.Width, 20)), isHorizontal: true, childAnchor: Anchor.CenterLeft)
                {
                    Stretch = true
                };

                new GUITextBlock(new RectTransform(new Vector2(0.5f, 1f), locationTypeGroup.RectTransform), TextManager.Get("outpostmoduleallowedlocationtypes"), textAlignment: Alignment.CenterLeft);
                HashSet <string> availableLocationTypes = new HashSet <string> {
                    "any"
                };
                foreach (LocationType locationType in LocationType.List)
                {
                    availableLocationTypes.Add(locationType.Identifier);
                }

                var locationTypeDropDown = new GUIDropDown(new RectTransform(new Vector2(0.5f, 1f), locationTypeGroup.RectTransform),
                                                           text: string.Join(", ", outpostGenerationParams.AllowedLocationTypes.Select(lt => TextManager.Capitalize(lt)) ?? "any".ToEnumerable()), selectMultiple: true);
                foreach (string locationType in availableLocationTypes)
                {
                    locationTypeDropDown.AddItem(TextManager.Capitalize(locationType), locationType);
                    if (outpostGenerationParams.AllowedLocationTypes.Contains(locationType))
                    {
                        locationTypeDropDown.SelectItem(locationType);
                    }
                }
                if (!outpostGenerationParams.AllowedLocationTypes.Any())
                {
                    locationTypeDropDown.SelectItem("any");
                }

                locationTypeDropDown.OnSelected += (_, __) =>
                {
                    outpostGenerationParams.SetAllowedLocationTypes(locationTypeDropDown.SelectedDataMultiple.Cast <string>());
                    locationTypeDropDown.Text = ToolBox.LimitString(locationTypeDropDown.Text, locationTypeDropDown.Font, locationTypeDropDown.Rect.Width);
                    return(true);
                };
                locationTypeGroup.RectTransform.MinSize = new Point(locationTypeGroup.Rect.Width, locationTypeGroup.RectTransform.Children.Max(c => c.MinSize.Y));

                outpostParamsEditor.AddCustomContent(locationTypeGroup, 100);

                // module count -------------------------

                var moduleLabel = new GUITextBlock(new RectTransform(new Point(editorContainer.Content.Rect.Width, (int)(70 * GUI.Scale))), TextManager.Get("submarinetype.outpostmodules"), font: GUI.SubHeadingFont);
                outpostParamsEditor.AddCustomContent(moduleLabel, 100);

                foreach (KeyValuePair <string, int> moduleCount in outpostGenerationParams.ModuleCounts)
                {
                    var moduleCountGroup = new GUILayoutGroup(new RectTransform(new Point(editorContainer.Content.Rect.Width, (int)(25 * GUI.Scale))), isHorizontal: true, childAnchor: Anchor.CenterLeft);
                    new GUITextBlock(new RectTransform(new Vector2(0.5f, 1f), moduleCountGroup.RectTransform), TextManager.Capitalize(moduleCount.Key), textAlignment: Alignment.CenterLeft);
                    new GUINumberInput(new RectTransform(new Vector2(0.5f, 1f), moduleCountGroup.RectTransform), GUINumberInput.NumberType.Int)
                    {
                        MinValueInt    = 0,
                        MaxValueInt    = 100,
                        IntValue       = moduleCount.Value,
                        OnValueChanged = (numInput) =>
                        {
                            outpostGenerationParams.SetModuleCount(moduleCount.Key, numInput.IntValue);
                            if (numInput.IntValue == 0)
                            {
                                outpostParamsList.Select(outpostParamsList.SelectedData);
                            }
                        }
                    };
                    moduleCountGroup.RectTransform.MinSize = new Point(moduleCountGroup.Rect.Width, moduleCountGroup.RectTransform.Children.Max(c => c.MinSize.Y));
                    outpostParamsEditor.AddCustomContent(moduleCountGroup, 100);
                }

                // add module count -------------------------

                var addModuleCountGroup = new GUILayoutGroup(new RectTransform(new Point(editorContainer.Content.Rect.Width, (int)(40 * GUI.Scale))), isHorizontal: true, childAnchor: Anchor.Center);

                HashSet <string> availableFlags = new HashSet <string>();
                foreach (string flag in OutpostGenerationParams.Params.SelectMany(p => p.ModuleCounts.Select(m => m.Key)))
                {
                    availableFlags.Add(flag);
                }
                foreach (var sub in SubmarineInfo.SavedSubmarines)
                {
                    if (sub.OutpostModuleInfo == null)
                    {
                        continue;
                    }
                    foreach (string flag in sub.OutpostModuleInfo.ModuleFlags)
                    {
                        availableFlags.Add(flag);
                    }
                }

                var moduleTypeDropDown = new GUIDropDown(new RectTransform(new Vector2(0.8f, 0.8f), addModuleCountGroup.RectTransform),
                                                         text: TextManager.Get("leveleditor.addmoduletype"));
                foreach (string flag in availableFlags)
                {
                    if (outpostGenerationParams.ModuleCounts.Any(mc => mc.Key.Equals(flag, StringComparison.OrdinalIgnoreCase)))
                    {
                        continue;
                    }
                    moduleTypeDropDown.AddItem(TextManager.Capitalize(flag), flag);
                }
                moduleTypeDropDown.OnSelected += (_, userdata) =>
                {
                    outpostGenerationParams.SetModuleCount(userdata as string, 1);
                    outpostParamsList.Select(outpostParamsList.SelectedData);
                    return(true);
                };
                addModuleCountGroup.RectTransform.MinSize = new Point(addModuleCountGroup.Rect.Width, addModuleCountGroup.RectTransform.Children.Max(c => c.MinSize.Y));
                outpostParamsEditor.AddCustomContent(addModuleCountGroup, 100);

                return(true);
            };

            var createLevelObjButton = new GUIButton(new RectTransform(new Vector2(1.0f, 0.05f), paddedLeftPanel.RectTransform),
                                                     TextManager.Get("leveleditor.createlevelobj"))
            {
                OnClicked = (btn, obj) =>
                {
                    Wizard.Instance.Create();
                    return(true);
                }
            };

            GUITextBlock.AutoScaleAndNormalize(createLevelObjButton.TextBlock);

            lightingEnabled = new GUITickBox(new RectTransform(new Vector2(1.0f, 0.025f), paddedLeftPanel.RectTransform),
                                             TextManager.Get("leveleditor.lightingenabled"));

            cursorLightEnabled = new GUITickBox(new RectTransform(new Vector2(1.0f, 0.025f), paddedLeftPanel.RectTransform),
                                                TextManager.Get("leveleditor.cursorlightenabled"));

            new GUIButton(new RectTransform(new Vector2(1.0f, 0.05f), paddedLeftPanel.RectTransform),
                          TextManager.Get("leveleditor.reloadtextures"))
            {
                OnClicked = (btn, obj) =>
                {
                    Level.Loaded?.ReloadTextures();
                    return(true);
                }
            };

            new GUIButton(new RectTransform(new Vector2(1.0f, 0.05f), paddedLeftPanel.RectTransform),
                          TextManager.Get("editor.saveall"))
            {
                OnClicked = (btn, obj) =>
                {
                    SerializeAll();
                    return(true);
                }
            };

            rightPanel = new GUIFrame(new RectTransform(new Vector2(0.25f, 1.0f), Frame.RectTransform, Anchor.TopRight)
            {
                MinSize = new Point(450, 0)
            });
            var paddedRightPanel = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.95f), rightPanel.RectTransform, Anchor.Center)
            {
                RelativeOffset = new Vector2(0.02f, 0.0f)
            })
            {
                Stretch         = true,
                RelativeSpacing = 0.01f
            };

            editorContainer = new GUIListBox(new RectTransform(new Vector2(1.0f, 1.0f), paddedRightPanel.RectTransform));

            var seedContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.05f), paddedRightPanel.RectTransform), isHorizontal: true);

            new GUITextBlock(new RectTransform(new Vector2(0.5f, 1.0f), seedContainer.RectTransform), TextManager.Get("leveleditor.levelseed"));
            seedBox = new GUITextBox(new RectTransform(new Vector2(0.5f, 1.0f), seedContainer.RectTransform), ToolBox.RandomSeed(8));

            new GUIButton(new RectTransform(new Vector2(1.0f, 0.05f), paddedRightPanel.RectTransform),
                          TextManager.Get("leveleditor.generate"))
            {
                OnClicked = (btn, obj) =>
                {
                    Submarine.Unload();
                    GameMain.LightManager.ClearLights();
                    LevelData levelData = LevelData.CreateRandom(seedBox.Text, generationParams: selectedParams);
                    levelData.ForceOutpostGenerationParams = outpostParamsList.SelectedData as OutpostGenerationParams;
                    Level.Generate(levelData, mirror: false);
                    GameMain.LightManager.AddLight(pointerLightSource);
                    cam.Position = new Vector2(Level.Loaded.Size.X / 2, Level.Loaded.Size.Y / 2);
                    foreach (GUITextBlock param in paramsList.Content.Children)
                    {
                        param.TextColor = param.UserData == selectedParams ? GUI.Style.Green : param.Style.TextColor;
                    }
                    seedBox.Deselect();
                    return(true);
                }
            };

            new GUIButton(new RectTransform(new Vector2(1.0f, 0.05f), paddedRightPanel.RectTransform),
                          TextManager.Get("leveleditor.test"))
            {
                OnClicked = (btn, obj) =>
                {
                    if (Level.Loaded?.LevelData == null)
                    {
                        return(false);
                    }

                    GameMain.GameScreen.Select();

                    var currEntities = Entity.GetEntities().ToList();
                    if (Submarine.MainSub != null)
                    {
                        var toRemove = Entity.GetEntities().Where(e => e.Submarine == Submarine.MainSub).ToList();
                        foreach (Entity ent in toRemove)
                        {
                            ent.Remove();
                        }
                        Submarine.MainSub.Remove();
                    }

                    //TODO: hacky workaround to check for wrecks and outposts, refactor SubmarineInfo and ContentType at some point
                    var nonPlayerFiles = ContentPackage.GetFilesOfType(GameMain.Config.AllEnabledPackages, ContentType.Wreck).ToList();
                    nonPlayerFiles.AddRange(ContentPackage.GetFilesOfType(GameMain.Config.AllEnabledPackages, ContentType.Outpost));
                    nonPlayerFiles.AddRange(ContentPackage.GetFilesOfType(GameMain.Config.AllEnabledPackages, ContentType.OutpostModule));
                    SubmarineInfo subInfo = SubmarineInfo.SavedSubmarines.FirstOrDefault(s => s.Name.Equals(GameMain.Config.QuickStartSubmarineName, StringComparison.InvariantCultureIgnoreCase));
                    subInfo ??= SubmarineInfo.SavedSubmarines.GetRandom(s =>
                                                                        s.IsPlayer && !s.HasTag(SubmarineTag.Shuttle) &&
                                                                        !nonPlayerFiles.Any(f => f.Path.CleanUpPath().Equals(s.FilePath.CleanUpPath(), StringComparison.InvariantCultureIgnoreCase)));
                    GameSession gameSession = new GameSession(subInfo, "", GameModePreset.TestMode, null);
                    gameSession.StartRound(Level.Loaded.LevelData);
                    (gameSession.GameMode as TestGameMode).OnRoundEnd = () =>
                    {
                        GameMain.LevelEditorScreen.Select();
                        Submarine.MainSub.Remove();

                        var toRemove = Entity.GetEntities().Where(e => !currEntities.Contains(e)).ToList();
                        foreach (Entity ent in toRemove)
                        {
                            ent.Remove();
                        }

                        Submarine.MainSub = null;
                    };

                    GameMain.GameSession = gameSession;

                    return(true);
                }
            };

            bottomPanel = new GUIFrame(new RectTransform(new Vector2(0.75f, 0.22f), Frame.RectTransform, Anchor.BottomLeft)
            {
                MaxSize = new Point(GameMain.GraphicsWidth - rightPanel.Rect.Width, 1000)
            }, style: "GUIFrameBottom");

            levelObjectList = new GUIListBox(new RectTransform(new Vector2(0.99f, 0.85f), bottomPanel.RectTransform, Anchor.Center))
            {
                UseGridLayout = true
            };
            levelObjectList.OnSelected += (GUIComponent component, object obj) =>
            {
                selectedLevelObject = obj as LevelObjectPrefab;
                CreateLevelObjectEditor(selectedLevelObject);
                return(true);
            };

            spriteEditDoneButton = new GUIButton(new RectTransform(new Point(200, 30), anchor: Anchor.BottomRight)
            {
                AbsoluteOffset = new Point(20, 20)
            },
                                                 TextManager.Get("leveleditor.spriteeditdone"))
            {
                OnClicked = (btn, userdata) =>
                {
                    editingSprite = null;
                    return(true);
                }
            };

            topPanel = new GUIFrame(new RectTransform(new Point(400, 100), GUI.Canvas)
            {
                RelativeOffset = new Vector2(leftPanel.RectTransform.RelativeSize.X * 2, 0.0f)
            }, style: "GUIFrameTop");
        }
Пример #22
0
        private IEnumerable <object> Load(bool isSeparateThread)
        {
            if (GameSettings.VerboseLogging)
            {
                DebugConsole.NewMessage("LOADING COROUTINE", Color.Lime);
            }

            while (TitleScreen.WaitForLanguageSelection)
            {
                yield return(CoroutineStatus.Running);
            }

            SoundManager = new Sounds.SoundManager();
            SoundManager.SetCategoryGainMultiplier("default", Config.SoundVolume, 0);
            SoundManager.SetCategoryGainMultiplier("ui", Config.SoundVolume, 0);
            SoundManager.SetCategoryGainMultiplier("waterambience", Config.SoundVolume, 0);
            SoundManager.SetCategoryGainMultiplier("music", Config.MusicVolume, 0);
            SoundManager.SetCategoryGainMultiplier("voip", Config.VoiceChatVolume * 20.0f, 0);

            if (ConsoleArguments.Contains("-skipintro"))
            {
                Config.EnableSplashScreen = false;
            }

            if (Config.EnableSplashScreen)
            {
                var pendingSplashScreens = TitleScreen.PendingSplashScreens;
                pendingSplashScreens?.Enqueue(new Pair <string, Point>("Content/Splash_UTG.mp4", new Point(1280, 720)));
                pendingSplashScreens?.Enqueue(new Pair <string, Point>("Content/Splash_FF.mp4", new Point(1280, 720)));
                pendingSplashScreens?.Enqueue(new Pair <string, Point>("Content/Splash_Daedalic.mp4", new Point(1920, 1080)));
            }

            //if not loading in a separate thread, wait for the splash screens to finish before continuing the loading
            //otherwise the videos will look extremely choppy
            if (!isSeparateThread)
            {
                while (TitleScreen.PlayingSplashScreen || TitleScreen.PendingSplashScreens.Count > 0)
                {
                    yield return(CoroutineStatus.Running);
                }
            }

            GUI.Init(Window, Config.SelectedContentPackages, GraphicsDevice);
            DebugConsole.Init();

            if (Config.AutoUpdateWorkshopItems)
            {
                if (SteamManager.AutoUpdateWorkshopItems())
                {
                    ContentPackage.LoadAll();
                    Config.ReloadContentPackages();
                }
            }

            if (SelectedPackages.Count == 0)
            {
                DebugConsole.Log("No content packages selected");
            }
            else
            {
                DebugConsole.Log("Selected content packages: " + string.Join(", ", SelectedPackages.Select(cp => cp.Name)));
            }

#if DEBUG
            GameSettings.ShowUserStatisticsPrompt = false;
            GameSettings.SendUserStatistics       = false;
#endif

            InitUserStats();

            yield return(CoroutineStatus.Running);

            Debug.WriteLine("sounds");

            int i = 0;
            foreach (object crObj in SoundPlayer.Init())
            {
                CoroutineStatus status = (CoroutineStatus)crObj;
                if (status == CoroutineStatus.Success)
                {
                    break;
                }

                i++;
                TitleScreen.LoadState = SoundPlayer.SoundCount == 0 ?
                                        1.0f :
                                        Math.Min(40.0f * i / Math.Max(SoundPlayer.SoundCount, 1), 40.0f);

                yield return(CoroutineStatus.Running);
            }

            TitleScreen.LoadState = 40.0f;
            yield return(CoroutineStatus.Running);

            LightManager = new Lights.LightManager(base.GraphicsDevice, Content);

            TitleScreen.LoadState = 41.0f;
            yield return(CoroutineStatus.Running);

            GUI.LoadContent();
            TitleScreen.LoadState = 42.0f;

            yield return(CoroutineStatus.Running);

            MissionPrefab.Init();
            MapEntityPrefab.Init();
            Tutorials.Tutorial.Init();
            MapGenerationParams.Init();
            LevelGenerationParams.LoadPresets();
            ScriptedEventSet.LoadPrefabs();
            AfflictionPrefab.LoadAll(GetFilesOfType(ContentType.Afflictions));
            TitleScreen.LoadState = 50.0f;
            yield return(CoroutineStatus.Running);

            StructurePrefab.LoadAll(GetFilesOfType(ContentType.Structure));
            TitleScreen.LoadState = 53.0f;
            yield return(CoroutineStatus.Running);

            ItemPrefab.LoadAll(GetFilesOfType(ContentType.Item));
            TitleScreen.LoadState = 55.0f;
            yield return(CoroutineStatus.Running);

            JobPrefab.LoadAll(GetFilesOfType(ContentType.Jobs));
            // Add any missing jobs from the prefab into Config.JobNamePreferences.
            foreach (JobPrefab job in JobPrefab.List)
            {
                if (!Config.JobPreferences.Contains(job.Identifier))
                {
                    Config.JobPreferences.Add(job.Identifier);
                }
            }

            NPCConversation.LoadAll(GetFilesOfType(ContentType.NPCConversations));

            ItemAssemblyPrefab.LoadAll();
            TitleScreen.LoadState = 60.0f;
            yield return(CoroutineStatus.Running);

            GameModePreset.Init();

            Submarine.RefreshSavedSubs();

            TitleScreen.LoadState = 65.0f;
            yield return(CoroutineStatus.Running);

            GameScreen = new GameScreen(GraphicsDeviceManager.GraphicsDevice, Content);

            TitleScreen.LoadState = 68.0f;
            yield return(CoroutineStatus.Running);

            MainMenuScreen   = new MainMenuScreen(this);
            LobbyScreen      = new LobbyScreen();
            ServerListScreen = new ServerListScreen();

            TitleScreen.LoadState = 70.0f;
            yield return(CoroutineStatus.Running);

            if (SteamManager.USE_STEAM)
            {
                SteamWorkshopScreen = new SteamWorkshopScreen();
                if (SteamManager.IsInitialized)
                {
                    SteamManager.Instance.Friends.OnInvitedToGame    += OnInvitedToGame;
                    SteamManager.Instance.Lobby.OnLobbyJoinRequested += OnLobbyJoinRequested;
                }
            }
            SubEditorScreen = new SubEditorScreen();

            TitleScreen.LoadState = 75.0f;
            yield return(CoroutineStatus.Running);

            ParticleEditorScreen = new ParticleEditorScreen();

            TitleScreen.LoadState = 80.0f;
            yield return(CoroutineStatus.Running);

            LevelEditorScreen     = new LevelEditorScreen();
            SpriteEditorScreen    = new SpriteEditorScreen();
            CharacterEditorScreen = new CharacterEditorScreen();

            yield return(CoroutineStatus.Running);

            TitleScreen.LoadState = 85.0f;
            ParticleManager       = new ParticleManager(GameScreen.Cam);
            ParticleManager.LoadPrefabs();
            TitleScreen.LoadState = 88.0f;
            LevelObjectPrefab.LoadAll();

            TitleScreen.LoadState = 90.0f;
            yield return(CoroutineStatus.Running);

            DecalManager = new DecalManager();
            LocationType.Init();
            MainMenuScreen.Select();

            CheckContentPackage();

            foreach (string steamError in SteamManager.InitializationErrors)
            {
                new GUIMessageBox(TextManager.Get("Error"), TextManager.Get(steamError));
            }

            TitleScreen.LoadState = 100.0f;
            hasLoaded             = true;
            if (GameSettings.VerboseLogging)
            {
                DebugConsole.NewMessage("LOADING COROUTINE FINISHED", Color.Lime);
            }
            yield return(CoroutineStatus.Success);
        }
Пример #23
0
        public GameSettings(string filePath)
        {
            ContentPackage.LoadAll(ContentPackage.Folder);

            Load(filePath);
        }
Пример #24
0
 public static string GetDefaultFile(string speciesName, ContentPackage contentPackage = null) => $"{GetFolder(speciesName, contentPackage)}{GetDefaultFileName(speciesName)}.xml";
Пример #25
0
        public void Load(string filePath)
        {
            XDocument doc = XMLExtensions.TryLoadXml(filePath);

            MasterServerUrl = doc.Root.GetAttributeString("masterserverurl", "");

            AutoCheckUpdates = doc.Root.GetAttributeBool("autocheckupdates", true);
            WasGameUpdated   = doc.Root.GetAttributeBool("wasgameupdated", false);

            VerboseLogging       = doc.Root.GetAttributeBool("verboselogging", false);
            SaveDebugConsoleLogs = doc.Root.GetAttributeBool("savedebugconsolelogs", false);
            if (doc.Root.Attribute("senduserstatistics") == null)
            {
                ShowUserStatisticsPrompt = true;
            }
            else
            {
                sendUserStatistics = doc.Root.GetAttributeBool("senduserstatistics", true);
            }

            if (doc == null)
            {
                GraphicsWidth  = 1024;
                GraphicsHeight = 678;

                MasterServerUrl = "";

                SelectedContentPackage = ContentPackage.list.Any() ? ContentPackage.list[0] : new ContentPackage("");

                JobNamePreferences = new List <string>();
                foreach (JobPrefab job in JobPrefab.List)
                {
                    JobNamePreferences.Add(job.Name);
                }
                return;
            }

            XElement graphicsMode = doc.Root.Element("graphicsmode");

            GraphicsWidth  = graphicsMode.GetAttributeInt("width", 0);
            GraphicsHeight = graphicsMode.GetAttributeInt("height", 0);
            VSyncEnabled   = graphicsMode.GetAttributeBool("vsync", true);

#if CLIENT
            if (GraphicsWidth == 0 || GraphicsHeight == 0)
            {
                GraphicsWidth  = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
                GraphicsHeight = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;
            }
#endif

            //FullScreenEnabled = ToolBox.GetAttributeBool(graphicsMode, "fullscreen", true);

            var windowModeStr = graphicsMode.GetAttributeString("displaymode", "Fullscreen");
            if (!Enum.TryParse <WindowMode>(windowModeStr, out windowMode))
            {
                windowMode = WindowMode.Fullscreen;
            }

            SoundVolume = doc.Root.GetAttributeFloat("soundvolume", 1.0f);
            MusicVolume = doc.Root.GetAttributeFloat("musicvolume", 0.3f);

            EnableSplashScreen = doc.Root.GetAttributeBool("enablesplashscreen", true);

            keyMapping = new KeyOrMouse[Enum.GetNames(typeof(InputType)).Length];
            keyMapping[(int)InputType.Up]    = new KeyOrMouse(Keys.W);
            keyMapping[(int)InputType.Down]  = new KeyOrMouse(Keys.S);
            keyMapping[(int)InputType.Left]  = new KeyOrMouse(Keys.A);
            keyMapping[(int)InputType.Right] = new KeyOrMouse(Keys.D);
            keyMapping[(int)InputType.Run]   = new KeyOrMouse(Keys.LeftShift);

            keyMapping[(int)InputType.Chat]       = new KeyOrMouse(Keys.Tab);
            keyMapping[(int)InputType.RadioChat]  = new KeyOrMouse(Keys.OemPipe);
            keyMapping[(int)InputType.CrewOrders] = new KeyOrMouse(Keys.C);

            keyMapping[(int)InputType.Select] = new KeyOrMouse(Keys.E);

            keyMapping[(int)InputType.Use] = new KeyOrMouse(0);
            keyMapping[(int)InputType.Aim] = new KeyOrMouse(1);

            foreach (XElement subElement in doc.Root.Elements())
            {
                switch (subElement.Name.ToString().ToLowerInvariant())
                {
                case "keymapping":
                    foreach (XAttribute attribute in subElement.Attributes())
                    {
                        if (Enum.TryParse(attribute.Name.ToString(), true, out InputType inputType))
                        {
                            if (int.TryParse(attribute.Value.ToString(), out int mouseButton))
                            {
                                keyMapping[(int)inputType] = new KeyOrMouse(mouseButton);
                            }
                            else
                            {
                                if (Enum.TryParse(attribute.Value.ToString(), true, out Keys key))
                                {
                                    keyMapping[(int)inputType] = new KeyOrMouse(key);
                                }
                            }
                        }
                    }
                    break;

                case "gameplay":
                    JobNamePreferences = new List <string>();
                    foreach (XElement ele in subElement.Element("jobpreferences").Elements("job"))
                    {
                        JobNamePreferences.Add(ele.GetAttributeString("name", ""));
                    }
                    break;

                case "player":
                    defaultPlayerName  = subElement.GetAttributeString("name", "");
                    characterHeadIndex = subElement.GetAttributeInt("headindex", Rand.Int(10));
                    characterGender    = subElement.GetAttributeString("gender", Rand.Range(0.0f, 1.0f) < 0.5f ? "male" : "female")
                                         .ToLowerInvariant() == "male" ? Gender.Male : Gender.Female;
                    break;
                }
            }

            foreach (InputType inputType in Enum.GetValues(typeof(InputType)))
            {
                if (keyMapping[(int)inputType] == null)
                {
                    DebugConsole.ThrowError("Key binding for the input type \"" + inputType + " not set!");
                    keyMapping[(int)inputType] = new KeyOrMouse(Keys.D1);
                }
            }

            UnsavedSettings = false;

            foreach (XElement subElement in doc.Root.Elements())
            {
                switch (subElement.Name.ToString().ToLowerInvariant())
                {
                case "contentpackage":
                    string path = subElement.GetAttributeString("path", "");

                    SelectedContentPackage = ContentPackage.list.Find(cp => cp.Path == path);
                    if (SelectedContentPackage == null)
                    {
                        SelectedContentPackage = new ContentPackage(path);
                    }
                    break;
                }
            }
        }
Пример #26
0
        private IEnumerable <object> Load()
        {
            if (GameSettings.VerboseLogging)
            {
                DebugConsole.NewMessage("LOADING COROUTINE", Color.Lime);
            }

            SoundManager = new Sounds.SoundManager();
            SoundManager.SetCategoryGainMultiplier("default", Config.SoundVolume);
            SoundManager.SetCategoryGainMultiplier("ui", Config.SoundVolume);
            SoundManager.SetCategoryGainMultiplier("waterambience", Config.SoundVolume);
            SoundManager.SetCategoryGainMultiplier("music", Config.MusicVolume);
            SoundManager.SetCategoryGainMultiplier("voip", Config.VoiceChatVolume);
            if (Config.EnableSplashScreen)
            {
                try
                {
                    (TitleScreen as LoadingScreen).SplashScreen = new Video(base.GraphicsDevice, SoundManager, "Content/splashscreen.mp4", 1280, 720);
                }
                catch (Exception e)
                {
                    Config.EnableSplashScreen = false;
                    DebugConsole.ThrowError("Playing the splash screen failed.", e);
                }
            }

            GUI.Init(Window, Config.SelectedContentPackages, GraphicsDevice);
            DebugConsole.Init();

            SteamManager.Initialize();
            if (Config.AutoUpdateWorkshopItems)
            {
                if (SteamManager.AutoUpdateWorkshopItems())
                {
                    ContentPackage.LoadAll(ContentPackage.Folder);
                    Config.ReloadContentPackages();
                }
            }

            if (SelectedPackages.Count == 0)
            {
                DebugConsole.Log("No content packages selected");
            }
            else
            {
                DebugConsole.Log("Selected content packages: " + string.Join(", ", SelectedPackages.Select(cp => cp.Name)));
            }

#if DEBUG
            GameSettings.ShowUserStatisticsPrompt = false;
            GameSettings.SendUserStatistics       = false;
#endif

            InitUserStats();

            yield return(CoroutineStatus.Running);


            LightManager = new Lights.LightManager(base.GraphicsDevice, Content);

            WaterRenderer.Instance = new WaterRenderer(base.GraphicsDevice, Content);
            TitleScreen.LoadState  = 1.0f;
            yield return(CoroutineStatus.Running);

            GUI.LoadContent();
            TitleScreen.LoadState = 2.0f;

            yield return(CoroutineStatus.Running);

            MissionPrefab.Init();
            MapEntityPrefab.Init();
            Tutorials.Tutorial.Init();
            MapGenerationParams.Init();
            LevelGenerationParams.LoadPresets();
            ScriptedEventSet.LoadPrefabs();
            AfflictionPrefab.LoadAll(GetFilesOfType(ContentType.Afflictions));
            TitleScreen.LoadState = 10.0f;
            yield return(CoroutineStatus.Running);

            StructurePrefab.LoadAll(GetFilesOfType(ContentType.Structure));
            TitleScreen.LoadState = 15.0f;
            yield return(CoroutineStatus.Running);

            ItemPrefab.LoadAll(GetFilesOfType(ContentType.Item));
            TitleScreen.LoadState = 25.0f;
            yield return(CoroutineStatus.Running);

            JobPrefab.LoadAll(GetFilesOfType(ContentType.Jobs));
            // Add any missing jobs from the prefab into Config.JobNamePreferences.
            foreach (JobPrefab job in JobPrefab.List)
            {
                if (!Config.JobPreferences.Contains(job.Identifier))
                {
                    Config.JobPreferences.Add(job.Identifier);
                }
            }

            NPCConversation.LoadAll(GetFilesOfType(ContentType.NPCConversations));

            ItemAssemblyPrefab.LoadAll();
            TitleScreen.LoadState = 30.0f;
            yield return(CoroutineStatus.Running);

            Debug.WriteLine("sounds");

            int i = 0;
            foreach (object crObj in SoundPlayer.Init())
            {
                CoroutineStatus status = (CoroutineStatus)crObj;
                if (status == CoroutineStatus.Success)
                {
                    break;
                }

                i++;
                TitleScreen.LoadState = SoundPlayer.SoundCount == 0 ?
                                        30.0f :
                                        Math.Min(30.0f + 40.0f * i / Math.Max(SoundPlayer.SoundCount, 1), 70.0f);

                yield return(CoroutineStatus.Running);
            }

            TitleScreen.LoadState = 70.0f;
            yield return(CoroutineStatus.Running);

            GameModePreset.Init();

            Submarine.RefreshSavedSubs();

            TitleScreen.LoadState = 80.0f;

            yield return(CoroutineStatus.Running);

            GameScreen = new GameScreen(GraphicsDeviceManager.GraphicsDevice, Content);

            TitleScreen.LoadState = 90.0f;

            yield return(CoroutineStatus.Running);

            MainMenuScreen   = new MainMenuScreen(this);
            LobbyScreen      = new LobbyScreen();
            ServerListScreen = new ServerListScreen();

            if (SteamManager.USE_STEAM)
            {
                SteamWorkshopScreen = new SteamWorkshopScreen();
            }

            SubEditorScreen       = new SubEditorScreen();
            ParticleEditorScreen  = new ParticleEditorScreen();
            LevelEditorScreen     = new LevelEditorScreen();
            SpriteEditorScreen    = new SpriteEditorScreen();
            CharacterEditorScreen = new CharacterEditorScreen();

            yield return(CoroutineStatus.Running);

            TitleScreen.LoadState = 95.0f;
            ParticleManager       = new ParticleManager(GameScreen.Cam);
            ParticleManager.LoadPrefabs();
            TitleScreen.LoadState = 97.0f;
            LevelObjectPrefab.LoadAll();
            DecalManager          = new DecalManager();
            TitleScreen.LoadState = 99.0f;
            yield return(CoroutineStatus.Running);

            LocationType.Init();
            MainMenuScreen.Select();

            CheckContentPackage();

            TitleScreen.LoadState = 100.0f;
            hasLoaded             = true;
            if (GameSettings.VerboseLogging)
            {
                DebugConsole.NewMessage("LOADING COROUTINE FINISHED", Color.Lime);
            }
            yield return(CoroutineStatus.Success);
        }
Пример #27
0
        public static void RefreshSavedSubs()
        {
            var contentPackageSubs = ContentPackage.GetFilesOfType(
                GameMain.Config.AllEnabledPackages,
                ContentType.Submarine, ContentType.Outpost, ContentType.OutpostModule,
                ContentType.Wreck, ContentType.BeaconStation);

            for (int i = savedSubmarines.Count - 1; i >= 0; i--)
            {
                if (File.Exists(savedSubmarines[i].FilePath))
                {
                    bool isDownloadedSub      = Path.GetFullPath(Path.GetDirectoryName(savedSubmarines[i].FilePath)) == Path.GetFullPath(SaveUtil.SubmarineDownloadFolder);
                    bool isInSubmarinesFolder = Path.GetFullPath(Path.GetDirectoryName(savedSubmarines[i].FilePath)) == Path.GetFullPath(SavePath);
                    bool isInContentPackage   = contentPackageSubs.Any(fp => Path.GetFullPath(fp.Path).CleanUpPath() == Path.GetFullPath(savedSubmarines[i].FilePath).CleanUpPath());
                    if (isDownloadedSub)
                    {
                        continue;
                    }
                    if (savedSubmarines[i].LastModifiedTime == File.GetLastWriteTime(savedSubmarines[i].FilePath) && (isInSubmarinesFolder || isInContentPackage))
                    {
                        continue;
                    }
                }
                savedSubmarines[i].Dispose();
            }

            if (!Directory.Exists(SavePath))
            {
                try
                {
                    Directory.CreateDirectory(SavePath);
                }
                catch (Exception e)
                {
                    DebugConsole.ThrowError("Directory \"" + SavePath + "\" not found and creating the directory failed.", e);
                    return;
                }
            }

            List <string> filePaths;

            string[] subDirectories;

            try
            {
                filePaths      = Directory.GetFiles(SavePath).ToList();
                subDirectories = Directory.GetDirectories(SavePath).Where(s =>
                {
                    DirectoryInfo dir = new DirectoryInfo(s);
                    return(!dir.Attributes.HasFlag(System.IO.FileAttributes.Hidden) && !dir.Name.StartsWith("."));
                }).ToArray();
            }
            catch (Exception e)
            {
                DebugConsole.ThrowError("Couldn't open directory \"" + SavePath + "\"!", e);
                return;
            }

            foreach (string subDirectory in subDirectories)
            {
                try
                {
                    filePaths.AddRange(Directory.GetFiles(subDirectory).ToList());
                }
                catch (Exception e)
                {
                    DebugConsole.ThrowError("Couldn't open subdirectory \"" + subDirectory + "\"!", e);
                    return;
                }
            }

            foreach (ContentFile subFile in contentPackageSubs)
            {
                if (!filePaths.Any(fp => Path.GetFullPath(fp) == Path.GetFullPath(subFile.Path)))
                {
                    filePaths.Add(subFile.Path);
                }
            }

            filePaths.RemoveAll(p => savedSubmarines.Any(sub => sub.FilePath == p));

            foreach (string path in filePaths)
            {
                var subInfo = new SubmarineInfo(path);
                if (subInfo.IsFileCorrupted)
                {
#if CLIENT
                    if (DebugConsole.IsOpen)
                    {
                        DebugConsole.Toggle();
                    }
                    var deleteSubPrompt = new GUIMessageBox(
                        TextManager.Get("Error"),
                        TextManager.GetWithVariable("SubLoadError", "[subname]", subInfo.Name) + "\n" +
                        TextManager.GetWithVariable("DeleteFileVerification", "[filename]", subInfo.Name),
                        new string[] { TextManager.Get("Yes"), TextManager.Get("No") });

                    string filePath = path;
                    deleteSubPrompt.Buttons[0].OnClicked += (btn, userdata) =>
                    {
                        try
                        {
                            File.Delete(filePath);
                        }
                        catch (Exception e)
                        {
                            DebugConsole.ThrowError($"Failed to delete file \"{filePath}\".", e);
                        }
                        deleteSubPrompt.Close();
                        return(true);
                    };
                    deleteSubPrompt.Buttons[1].OnClicked += deleteSubPrompt.Close;
#endif
                }
                else
                {
                    savedSubmarines.Add(subInfo);
                }
            }
        }
Пример #28
0
        public static void Init()
        {
            var files = ContentPackage.GetFilesOfType(GameMain.Config.AllEnabledPackages, ContentType.MapGenerationParameters);

            if (!files.Any())
            {
                DebugConsole.ThrowError("No map generation parameters found in the selected content packages!");
                return;
            }
            // Let's not actually load the parameters until we have solved which file is the last, because loading the parameters takes some resources that would also need to be released.
            XElement selectedElement = null;
            string   selectedFile    = null;

            foreach (ContentFile file in files)
            {
                XDocument doc = XMLExtensions.TryLoadXml(file.Path);
                if (doc == null)
                {
                    continue;
                }
                var mainElement = doc.Root;
                if (doc.Root.IsOverride())
                {
                    mainElement = doc.Root.FirstElement();
                    if (selectedElement != null)
                    {
                        DebugConsole.NewMessage($"Overriding the map generation parameters with '{file.Path}'", Color.Yellow);
                    }
                }
                else if (selectedElement != null)
                {
                    DebugConsole.ThrowError($"Error in {file.Path}: Another map generation parameter file already loaded! Use <override></override> tags to override it.");
                    break;
                }
                selectedElement = mainElement;
                selectedFile    = file.Path;
            }

            if (selectedFile == loadedFile)
            {
                return;
            }

#if CLIENT
            if (instance != null)
            {
                instance?.ConnectionSprite?.Remove();
                instance?.PassedConnectionSprite?.Remove();
                instance?.SelectedLocationIndicator?.Remove();
                instance?.CurrentLocationIndicator?.Remove();
                instance?.DecorativeGraphSprite?.Remove();
                instance?.MissionIcon?.Remove();
                instance?.TypeChangeIcon?.Remove();
                instance?.FogOfWarSprite?.Remove();
                foreach (List <Sprite> spriteList in instance.mapTiles.Values)
                {
                    foreach (Sprite sprite in spriteList)
                    {
                        sprite.Remove();
                    }
                }
                instance.mapTiles.Clear();
            }
#endif
            instance = null;

            if (selectedElement == null)
            {
                DebugConsole.ThrowError("Could not find a valid element in the map generation parameter files!");
            }
            else
            {
                instance   = new MapGenerationParams(selectedElement);
                loadedFile = selectedFile;
            }
        }
Пример #29
0
        private IEnumerable <object> Load(bool isSeparateThread)
        {
            if (GameSettings.VerboseLogging)
            {
                DebugConsole.NewMessage("LOADING COROUTINE", Color.Lime);
            }

            while (TitleScreen.WaitForLanguageSelection)
            {
                yield return(CoroutineStatus.Running);
            }

            SoundManager = new Sounds.SoundManager();
            SoundManager.SetCategoryGainMultiplier("default", Config.SoundVolume, 0);
            SoundManager.SetCategoryGainMultiplier("ui", Config.SoundVolume, 0);
            SoundManager.SetCategoryGainMultiplier("waterambience", Config.SoundVolume, 0);
            SoundManager.SetCategoryGainMultiplier("music", Config.MusicVolume, 0);
            SoundManager.SetCategoryGainMultiplier("voip", Math.Min(Config.VoiceChatVolume, 1.0f), 0);

            if (Config.EnableSplashScreen && !ConsoleArguments.Contains("-skipintro"))
            {
                var   pendingSplashScreens = TitleScreen.PendingSplashScreens;
                float baseVolume           = MathHelper.Clamp(Config.SoundVolume * 2.0f, 0.0f, 1.0f);
                pendingSplashScreens?.Enqueue(new LoadingScreen.PendingSplashScreen("Content/SplashScreens/Splash_UTG.webm", baseVolume * 0.5f));
                pendingSplashScreens?.Enqueue(new LoadingScreen.PendingSplashScreen("Content/SplashScreens/Splash_FF.webm", baseVolume));
                pendingSplashScreens?.Enqueue(new LoadingScreen.PendingSplashScreen("Content/SplashScreens/Splash_Daedalic.webm", baseVolume * 0.1f));
            }

            //if not loading in a separate thread, wait for the splash screens to finish before continuing the loading
            //otherwise the videos will look extremely choppy
            if (!isSeparateThread)
            {
                while (TitleScreen.PlayingSplashScreen || TitleScreen.PendingSplashScreens.Count > 0)
                {
                    yield return(CoroutineStatus.Running);
                }
            }

            GUI.Init(Window, Config.AllEnabledPackages, GraphicsDevice);
            DebugConsole.Init();

            if (Config.AutoUpdateWorkshopItems)
            {
                Config.WaitingForAutoUpdate = true;
                TaskPool.Add("AutoUpdateWorkshopItemsAsync",
                             SteamManager.AutoUpdateWorkshopItemsAsync(), (task) =>
                {
                    bool result = ((Task <bool>)task).Result;

                    Config.WaitingForAutoUpdate = false;
                });

                while (Config.WaitingForAutoUpdate)
                {
                    yield return(CoroutineStatus.Running);
                }
            }

#if DEBUG
            if (Config.ModBreakerMode)
            {
                Config.SelectCorePackage(ContentPackage.CorePackages.GetRandom());
                foreach (var regularPackage in ContentPackage.RegularPackages)
                {
                    if (Rand.Range(0.0, 1.0) <= 0.5)
                    {
                        Config.EnableRegularPackage(regularPackage);
                    }
                    else
                    {
                        Config.DisableRegularPackage(regularPackage);
                    }
                }
                ContentPackage.SortContentPackages(p =>
                {
                    return(Rand.Int(int.MaxValue));
                });
            }
#endif

            if (Config.AllEnabledPackages.None())
            {
                DebugConsole.Log("No content packages selected");
            }
            else
            {
                DebugConsole.Log("Selected content packages: " + string.Join(", ", Config.AllEnabledPackages.Select(cp => cp.Name)));
            }

#if DEBUG
            GameSettings.ShowUserStatisticsPrompt = false;
            GameSettings.SendUserStatistics       = false;
#endif

            InitUserStats();

            yield return(CoroutineStatus.Running);

            Debug.WriteLine("sounds");

            int i = 0;
            foreach (object crObj in SoundPlayer.Init())
            {
                CoroutineStatus status = (CoroutineStatus)crObj;
                if (status == CoroutineStatus.Success)
                {
                    break;
                }

                i++;
                TitleScreen.LoadState = SoundPlayer.SoundCount == 0 ?
                                        1.0f :
                                        Math.Min(40.0f * i / Math.Max(SoundPlayer.SoundCount, 1), 40.0f);

                yield return(CoroutineStatus.Running);
            }

            TitleScreen.LoadState = 40.0f;
            yield return(CoroutineStatus.Running);

            LightManager = new Lights.LightManager(base.GraphicsDevice, Content);

            TitleScreen.LoadState = 41.0f;
            yield return(CoroutineStatus.Running);

            GUI.LoadContent();
            TitleScreen.LoadState = 42.0f;

            yield return(CoroutineStatus.Running);

            TaskPool.Add("InitRelayNetworkAccess", SteamManager.InitRelayNetworkAccess(), (t) => { });

            FactionPrefab.LoadFactions();
            NPCSet.LoadSets();
            CharacterPrefab.LoadAll();
            MissionPrefab.Init();
            TraitorMissionPrefab.Init();
            MapEntityPrefab.Init();
            Tutorials.Tutorial.Init();
            MapGenerationParams.Init();
            LevelGenerationParams.LoadPresets();
            CaveGenerationParams.LoadPresets();
            OutpostGenerationParams.LoadPresets();
            WreckAIConfig.LoadAll();
            EventSet.LoadPrefabs();
            ItemPrefab.LoadAll(GetFilesOfType(ContentType.Item));
            AfflictionPrefab.LoadAll(GetFilesOfType(ContentType.Afflictions));
            SkillSettings.Load(GetFilesOfType(ContentType.SkillSettings));
            Order.Init();
            EventManagerSettings.Init();
            BallastFloraPrefab.LoadAll(GetFilesOfType(ContentType.MapCreature));
            HintManager.Init();
            TitleScreen.LoadState = 50.0f;
            yield return(CoroutineStatus.Running);

            StructurePrefab.LoadAll(GetFilesOfType(ContentType.Structure));
            TitleScreen.LoadState = 55.0f;
            yield return(CoroutineStatus.Running);

            UpgradePrefab.LoadAll(GetFilesOfType(ContentType.UpgradeModules));
            TitleScreen.LoadState = 56.0f;
            yield return(CoroutineStatus.Running);

            JobPrefab.LoadAll(GetFilesOfType(ContentType.Jobs));
            CorpsePrefab.LoadAll(GetFilesOfType(ContentType.Corpses));

            NPCConversation.LoadAll(GetFilesOfType(ContentType.NPCConversations));

            ItemAssemblyPrefab.LoadAll();
            TitleScreen.LoadState = 60.0f;
            yield return(CoroutineStatus.Running);

            GameModePreset.Init();

            SaveUtil.DeleteDownloadedSubs();
            SubmarineInfo.RefreshSavedSubs();

            TitleScreen.LoadState = 65.0f;
            yield return(CoroutineStatus.Running);

            GameScreen = new GameScreen(GraphicsDeviceManager.GraphicsDevice, Content);

            TitleScreen.LoadState = 68.0f;
            yield return(CoroutineStatus.Running);

            MainMenuScreen   = new MainMenuScreen(this);
            ServerListScreen = new ServerListScreen();

            TitleScreen.LoadState = 70.0f;
            yield return(CoroutineStatus.Running);

#if USE_STEAM
            SteamWorkshopScreen = new SteamWorkshopScreen();
            if (SteamManager.IsInitialized)
            {
                Steamworks.SteamFriends.OnGameRichPresenceJoinRequested += OnInvitedToGame;
                Steamworks.SteamFriends.OnGameLobbyJoinRequested        += OnLobbyJoinRequested;
            }
#endif

            SubEditorScreen = new SubEditorScreen();

            TitleScreen.LoadState = 75.0f;
            yield return(CoroutineStatus.Running);

            ParticleEditorScreen = new ParticleEditorScreen();

            TitleScreen.LoadState = 80.0f;
            yield return(CoroutineStatus.Running);

            LevelEditorScreen     = new LevelEditorScreen();
            SpriteEditorScreen    = new SpriteEditorScreen();
            EventEditorScreen     = new EventEditorScreen();
            CharacterEditorScreen = new CharacterEditor.CharacterEditorScreen();
            CampaignEndScreen     = new CampaignEndScreen();

            yield return(CoroutineStatus.Running);

            TitleScreen.LoadState = 85.0f;
            ParticleManager       = new ParticleManager(GameScreen.Cam);
            ParticleManager.LoadPrefabs();
            TitleScreen.LoadState = 88.0f;
            LevelObjectPrefab.LoadAll();

            TitleScreen.LoadState = 90.0f;
            yield return(CoroutineStatus.Running);

            DecalManager = new DecalManager();
            LocationType.Init();
            MainMenuScreen.Select();

            foreach (string steamError in SteamManager.InitializationErrors)
            {
                new GUIMessageBox(TextManager.Get("Error"), TextManager.Get(steamError));
            }

            TitleScreen.LoadState = 100.0f;
            hasLoaded             = true;
            if (GameSettings.VerboseLogging)
            {
                DebugConsole.NewMessage("LOADING COROUTINE FINISHED", Color.Lime);
            }
            yield return(CoroutineStatus.Success);
        }
Пример #30
0
 /// <summary>
 /// Returns the file paths of all files of the given type in the currently selected content packages.
 /// </summary>
 public IEnumerable <string> GetFilesOfType(ContentType type)
 {
     return(ContentPackage.GetFilesOfType(SelectedPackages, type));
 }