public bool TrySetValue(object parentObject, string value) { if (value == null) { return(false); } if (!supportedTypes.TryGetValue(PropertyType, out string typeName)) { if (PropertyType.IsEnum) { object enumVal; try { enumVal = Enum.Parse(propertyInfo.PropertyType, value, true); } catch (Exception e) { DebugConsole.ThrowError("Failed to set the value of the property \"" + Name + "\" of \"" + parentObject + "\" to " + value + " (not a valid " + propertyInfo.PropertyType + ")", e); return(false); } try { propertyInfo.SetValue(parentObject, enumVal); } catch (Exception e) { DebugConsole.ThrowError("Failed to set the value of the property \"" + Name + "\" of \"" + parentObject.ToString() + "\" to " + value.ToString(), e); return(false); } } else { DebugConsole.ThrowError("Failed to set the value of the property \"" + Name + "\" of \"" + parentObject + "\" to " + value); DebugConsole.ThrowError("(Type not supported)"); return(false); } } try { switch (typeName) { case "bool": bool boolValue = value == "true" || value == "True"; if (TrySetValueWithoutReflection(parentObject, boolValue)) { return(true); } propertyInfo.SetValue(parentObject, boolValue, null); break; case "int": if (int.TryParse(value, out int intVal)) { if (TrySetValueWithoutReflection(parentObject, intVal)) { return(true); } propertyInfo.SetValue(parentObject, intVal, null); } else { return(false); } break; case "float": if (float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out float floatVal)) { if (TrySetValueWithoutReflection(parentObject, floatVal)) { return(true); } propertyInfo.SetValue(parentObject, floatVal, null); } else { return(false); } break; case "string": propertyInfo.SetValue(parentObject, value, null); break; case "point": propertyInfo.SetValue(parentObject, XMLExtensions.ParsePoint(value)); break; case "vector2": propertyInfo.SetValue(parentObject, XMLExtensions.ParseVector2(value)); break; case "vector3": propertyInfo.SetValue(parentObject, XMLExtensions.ParseVector3(value)); break; case "vector4": propertyInfo.SetValue(parentObject, XMLExtensions.ParseVector4(value)); break; case "color": propertyInfo.SetValue(parentObject, XMLExtensions.ParseColor(value)); break; case "rectangle": propertyInfo.SetValue(parentObject, XMLExtensions.ParseRect(value, true)); break; } } catch (Exception e) { DebugConsole.ThrowError("Failed to set the value of the property \"" + Name + "\" of \"" + parentObject.ToString() + "\" to " + value.ToString(), e); return(false); } return(true); }
static void CrashDump(GameMain game, string filePath, Exception exception) { int existingFiles = 0; string originalFilePath = filePath; while (File.Exists(filePath)) { existingFiles++; filePath = Path.GetFileNameWithoutExtension(originalFilePath) + " (" + (existingFiles + 1) + ")" + Path.GetExtension(originalFilePath); } DebugConsole.DequeueMessages(); Md5Hash exeHash = null; try { string exePath = System.Reflection.Assembly.GetEntryAssembly().Location; var md5 = System.Security.Cryptography.MD5.Create(); byte[] exeBytes = File.ReadAllBytes(exePath); exeHash = new Md5Hash(exeBytes); } catch { //do nothing, generate the rest of the crash report } StringBuilder sb = new StringBuilder(); sb.AppendLine("Barotrauma Client crash report (generated on " + DateTime.Now + ")"); sb.AppendLine("\n"); sb.AppendLine("Barotrauma seems to have crashed. Sorry for the inconvenience! "); sb.AppendLine("\n"); try { if (exception is GameMain.LoadingException) { //exception occurred in loading screen: //assume content packages are the culprit and reset them XDocument doc = XMLExtensions.TryLoadXml(GameSettings.PlayerSavePath); XDocument baseDoc = XMLExtensions.TryLoadXml(GameSettings.SavePath); if (doc != null && baseDoc != null) { XElement newElement = new XElement(doc.Root.Name); newElement.Add(doc.Root.Attributes()); newElement.Add(doc.Root.Elements().Where(e => !e.Name.LocalName.Equals("contentpackage", StringComparison.InvariantCultureIgnoreCase))); newElement.Add(baseDoc.Root.Elements().Where(e => e.Name.LocalName.Equals("contentpackage", StringComparison.InvariantCultureIgnoreCase))); XDocument newDoc = new XDocument(newElement); newDoc.Save(GameSettings.PlayerSavePath); sb.AppendLine("To prevent further startup errors, installed mods will be disabled the next time you launch the game."); sb.AppendLine("\n"); } } } catch { //welp i guess we couldn't reset the config! } if (exeHash?.Hash != null) { sb.AppendLine(exeHash.Hash); } sb.AppendLine("\n"); sb.AppendLine("Game version " + GameMain.Version + " (" + AssemblyInfo.BuildString + ", branch " + AssemblyInfo.GitBranch + ", revision " + AssemblyInfo.GitRevision + ")"); if (GameMain.Config != null) { sb.AppendLine("Graphics mode: " + GameMain.Config.GraphicsWidth + "x" + GameMain.Config.GraphicsHeight + " (" + GameMain.Config.WindowMode.ToString() + ")"); sb.AppendLine("VSync " + (GameMain.Config.VSyncEnabled ? "ON" : "OFF")); sb.AppendLine("Language: " + (GameMain.Config.Language ?? "none")); } if (GameMain.Config.AllEnabledPackages != null) { sb.AppendLine("Selected content packages: " + (!GameMain.Config.AllEnabledPackages.Any() ? "None" : string.Join(", ", GameMain.Config.AllEnabledPackages.Select(c => c.Name)))); } sb.AppendLine("Level seed: " + ((Level.Loaded == null) ? "no level loaded" : Level.Loaded.Seed)); sb.AppendLine("Loaded submarine: " + ((Submarine.MainSub == null) ? "None" : Submarine.MainSub.Info.Name + " (" + Submarine.MainSub.Info.MD5Hash + ")")); sb.AppendLine("Selected screen: " + (Screen.Selected == null ? "None" : Screen.Selected.ToString())); if (SteamManager.IsInitialized) { sb.AppendLine("SteamManager initialized"); } if (GameMain.Client != null) { sb.AppendLine("Client (" + (GameMain.Client.GameStarted ? "Round had started)" : "Round hadn't been started)")); } sb.AppendLine("\n"); sb.AppendLine("System info:"); sb.AppendLine(" Operating system: " + System.Environment.OSVersion + (System.Environment.Is64BitOperatingSystem ? " 64 bit" : " x86")); if (game == null) { sb.AppendLine(" Game not initialized"); } else { if (game.GraphicsDevice == null) { sb.AppendLine(" Graphics device not set"); } else { if (game.GraphicsDevice.Adapter == null) { sb.AppendLine(" Graphics adapter not set"); } else { sb.AppendLine(" GPU name: " + game.GraphicsDevice.Adapter.Description); sb.AppendLine(" Display mode: " + game.GraphicsDevice.Adapter.CurrentDisplayMode); } sb.AppendLine(" GPU status: " + game.GraphicsDevice.GraphicsDeviceStatus); } } sb.AppendLine("\n"); sb.AppendLine("Exception: " + exception.Message + " (" + exception.GetType().ToString() + ")"); #if WINDOWS if (exception is SharpDXException sharpDxException && ((uint)sharpDxException.HResult) == 0x887A0005) { var dxDevice = (SharpDX.Direct3D11.Device)game.GraphicsDevice.Handle; sb.AppendLine("Device removed reason: " + dxDevice.DeviceRemovedReason.ToString()); } #endif if (exception.TargetSite != null) { sb.AppendLine("Target site: " + exception.TargetSite.ToString()); } sb.AppendLine("Stack trace: "); sb.AppendLine(exception.StackTrace.CleanupStackTrace()); sb.AppendLine("\n"); if (exception.InnerException != null) { sb.AppendLine("InnerException: " + exception.InnerException.Message); if (exception.InnerException.TargetSite != null) { sb.AppendLine("Target site: " + exception.InnerException.TargetSite.ToString()); } sb.AppendLine("Stack trace: "); sb.AppendLine(exception.InnerException.StackTrace.CleanupStackTrace()); } sb.AppendLine("Last debug messages:"); for (int i = DebugConsole.Messages.Count - 1; i >= 0; i--) { sb.AppendLine("[" + DebugConsole.Messages[i].Time + "] " + DebugConsole.Messages[i].Text); } string crashReport = sb.ToString(); File.WriteAllText(filePath, crashReport); if (GameSettings.SaveDebugConsoleLogs) { DebugConsole.SaveLogs(); } if (GameSettings.SendUserStatistics) { CrashMessageBox("A crash report (\"" + filePath + "\") was saved in the root folder of the game and sent to the developers.", filePath); GameAnalytics.AddErrorEvent(EGAErrorSeverity.Critical, crashReport); GameAnalytics.OnQuit(); } else { CrashMessageBox("A crash report (\"" + filePath + "\") was saved in the root folder of the game. The error was not sent to the developers because user statistics have been disabled, but" + " if you'd like to help fix this bug, you may post it on Barotrauma's GitHub issue tracker: https://github.com/Regalis11/Barotrauma/issues/", filePath); } }
public GUIMessageBox Create() { var box = new GUIMessageBox(TextManager.Get("LevelEditorCreateLevelObj"), string.Empty, new string[] { TextManager.Get("Cancel"), TextManager.Get("Done") }, GameMain.GraphicsWidth / 2, (int)(GameMain.GraphicsHeight * 0.8f)); box.Content.ChildAnchor = Anchor.TopCenter; box.Content.AbsoluteSpacing = 20; int elementSize = 30; var listBox = new GUIListBox(new RectTransform(new Vector2(1, 0.9f), box.Content.RectTransform)); new GUITextBlock(new RectTransform(new Point(listBox.Content.Rect.Width, elementSize), listBox.Content.RectTransform), TextManager.Get("LevelEditorLevelObjName")) { CanBeFocused = false }; var nameBox = new GUITextBox(new RectTransform(new Point(listBox.Content.Rect.Width, elementSize), listBox.Content.RectTransform)); new GUITextBlock(new RectTransform(new Point(listBox.Content.Rect.Width, elementSize), listBox.Content.RectTransform), TextManager.Get("LevelEditorLevelObjTexturePath")) { CanBeFocused = false }; var texturePathBox = new GUITextBox(new RectTransform(new Point(listBox.Content.Rect.Width, elementSize), listBox.Content.RectTransform)); foreach (LevelObjectPrefab prefab in LevelObjectPrefab.List) { if (prefab.Sprite == null) { continue; } texturePathBox.Text = Path.GetDirectoryName(prefab.Sprite.FilePath); break; } newPrefab = new LevelObjectPrefab(null); new SerializableEntityEditor(listBox.Content.RectTransform, newPrefab, false, false); box.Buttons[0].OnClicked += (b, d) => { box.Close(); return(true); }; // Next box.Buttons[1].OnClicked += (b, d) => { if (string.IsNullOrEmpty(nameBox.Text)) { nameBox.Flash(Color.Red); GUI.AddMessage(TextManager.Get("LevelEditorLevelObjNameEmpty"), Color.Red); return(false); } if (LevelObjectPrefab.List.Any(obj => obj.Name.ToLower() == nameBox.Text.ToLower())) { nameBox.Flash(Color.Red); GUI.AddMessage(TextManager.Get("LevelEditorLevelObjNameTaken"), Color.Red); return(false); } if (!File.Exists(texturePathBox.Text)) { texturePathBox.Flash(Color.Red); GUI.AddMessage(TextManager.Get("LevelEditorLevelObjTextureNotFound"), Color.Red); return(false); } newPrefab.Name = nameBox.Text; XmlWriterSettings settings = new XmlWriterSettings { Indent = true }; foreach (string configFile in GameMain.Instance.GetFilesOfType(ContentType.LevelObjectPrefabs)) { XDocument doc = XMLExtensions.TryLoadXml(configFile); if (doc?.Root == null) { continue; } var newElement = new XElement(newPrefab.Name); newPrefab.Save(newElement); newElement.Add(new XElement("Sprite", new XAttribute("texture", texturePathBox.Text), new XAttribute("sourcerect", "0,0,100,100"), new XAttribute("origin", "0.5,0.5"))); doc.Root.Add(newElement); using (var writer = XmlWriter.Create(configFile, settings)) { doc.WriteTo(writer); writer.Flush(); } break; } LevelObjectPrefab.List.Add(newPrefab); GameMain.LevelEditorScreen.UpdateLevelObjectsList(); box.Close(); return(true); }; return(box); }
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(); } }
private void SerializeAll() { System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings { Indent = true, NewLineOnAttributes = true }; foreach (ContentFile configFile in GameMain.Instance.GetFilesOfType(ContentType.LevelGenerationParameters)) { XDocument doc = XMLExtensions.TryLoadXml(configFile.Path); if (doc == null) { continue; } foreach (LevelGenerationParams genParams in LevelGenerationParams.LevelParams) { foreach (XElement element in doc.Root.Elements()) { XElement levelParamElement = element; if (element.IsOverride()) { foreach (XElement subElement in element.Elements()) { string id = element.GetAttributeString("identifier", null) ?? element.Name.ToString(); if (!id.Equals(genParams.Name, StringComparison.OrdinalIgnoreCase)) { continue; } SerializableProperty.SerializeProperties(genParams, element, true); } } else { string id = element.GetAttributeString("identifier", null) ?? element.Name.ToString(); if (!id.Equals(genParams.Name, StringComparison.OrdinalIgnoreCase)) { continue; } SerializableProperty.SerializeProperties(genParams, element, true); } break; } } using (var writer = XmlWriter.Create(configFile.Path, settings)) { doc.WriteTo(writer); writer.Flush(); } } settings.NewLineOnAttributes = false; foreach (ContentFile configFile in GameMain.Instance.GetFilesOfType(ContentType.LevelObjectPrefabs)) { XDocument doc = XMLExtensions.TryLoadXml(configFile.Path); if (doc == null) { continue; } foreach (LevelObjectPrefab levelObjPrefab in LevelObjectPrefab.List) { foreach (XElement element in doc.Root.Elements()) { if (!element.Name.ToString().Equals(levelObjPrefab.Name, StringComparison.OrdinalIgnoreCase)) { continue; } levelObjPrefab.Save(element); break; } } using (var writer = XmlWriter.Create(configFile.Path, settings)) { doc.WriteTo(writer); writer.Flush(); } } RuinGenerationParams.SaveAll(); }
public bool TrySetValue(object value) { if (value == null || obj == null || propertyDescriptor == null) { return(false); } try { string typeName; if (!supportedTypes.TryGetValue(propertyDescriptor.PropertyType, out typeName)) { if (propertyDescriptor.PropertyType.IsEnum) { object enumVal; try { enumVal = Enum.Parse(propertyInfo.PropertyType, value.ToString(), true); } catch (Exception e) { DebugConsole.ThrowError("Failed to set the value of the property \"" + Name + "\" of \"" + obj + "\" to " + value + " (not a valid " + propertyInfo.PropertyType + ")", e); return(false); } propertyInfo.SetValue(obj, enumVal); } else { DebugConsole.ThrowError("Failed to set the value of the property \"" + Name + "\" of \"" + obj + "\" to " + value); DebugConsole.ThrowError("(Type not supported)"); return(false); } } try { if (value.GetType() == typeof(string)) { switch (typeName) { case "string": propertyInfo.SetValue(obj, value, null); return(true); case "vector2": propertyInfo.SetValue(obj, XMLExtensions.ParseVector2((string)value)); return(true); case "vector3": propertyInfo.SetValue(obj, XMLExtensions.ParseVector3((string)value)); return(true); case "vector4": propertyInfo.SetValue(obj, XMLExtensions.ParseVector4((string)value)); return(true); case "color": propertyInfo.SetValue(obj, XMLExtensions.ParseColor((string)value)); return(true); case "rectangle": propertyInfo.SetValue(obj, XMLExtensions.ParseRect((string)value, false)); return(true); default: DebugConsole.ThrowError("Failed to set the value of the property \"" + Name + "\" of \"" + obj.ToString() + "\" to " + value.ToString()); DebugConsole.ThrowError("(Cannot convert a string to a " + propertyDescriptor.PropertyType.ToString() + ")"); return(false); } } else if (propertyDescriptor.PropertyType != value.GetType()) { DebugConsole.ThrowError("Failed to set the value of the property \"" + Name + "\" of \"" + obj.ToString() + "\" to " + value.ToString()); DebugConsole.ThrowError("(Non-matching type, should be " + propertyDescriptor.PropertyType + " instead of " + value.GetType() + ")"); return(false); } propertyInfo.SetValue(obj, value, null); } catch (Exception e) { DebugConsole.ThrowError("Failed to set the value of the property \"" + Name + "\" of \"" + obj.ToString() + "\" to " + value.ToString(), e); return(false); } return(true); } catch { return(false); } }
public static void Init() { Prefabs = new Dictionary <string, Order>(); OrderCategoryIcons = new Dictionary <OrderCategory, Tuple <Sprite, Color> >(); foreach (ContentFile file in GameMain.Instance.GetFilesOfType(ContentType.Orders)) { XDocument doc = XMLExtensions.TryLoadXml(file.Path); if (doc == null) { continue; } var mainElement = doc.Root; bool allowOverriding = false; if (doc.Root.IsOverride()) { mainElement = doc.Root.FirstElement(); allowOverriding = true; } foreach (XElement sourceElement in mainElement.Elements()) { var element = sourceElement.IsOverride() ? sourceElement.FirstElement() : sourceElement; string name = element.Name.ToString(); if (name.Equals("order", StringComparison.OrdinalIgnoreCase)) { string identifier = element.GetAttributeString("identifier", null); if (string.IsNullOrWhiteSpace(identifier)) { DebugConsole.ThrowError($"Error in file {file.Path}: The order element '{name}' does not have an identifier! All orders must have a unique identifier."); continue; } if (Prefabs.TryGetValue(identifier, out Order duplicate)) { if (allowOverriding || sourceElement.IsOverride()) { DebugConsole.NewMessage($"Overriding an existing order '{identifier}' with another one defined in '{file.Path}'", Color.Yellow); Prefabs.Remove(identifier); } else { DebugConsole.ThrowError($"Error in file {file.Path}: Duplicate element with the idenfitier '{identifier}' found in '{file.Path}'! All orders must have a unique identifier. Use <override></override> tags to override an order with the same identifier."); continue; } } var newOrder = new Order(element); newOrder.Prefab = newOrder; Prefabs.Add(identifier, newOrder); } else if (name.Equals("ordercategory", StringComparison.OrdinalIgnoreCase)) { var category = (OrderCategory)Enum.Parse(typeof(OrderCategory), element.GetAttributeString("category", "undefined"), true); if (OrderCategoryIcons.ContainsKey(category)) { if (allowOverriding || sourceElement.IsOverride()) { DebugConsole.NewMessage($"Overriding an existing icon for the '{category}' order category with another one defined in '{file}'", Color.Yellow); OrderCategoryIcons.Remove(category); } else { DebugConsole.ThrowError($"Error in file {file}: Duplicate element for the '{category}' order category found in '{file}'! All order categories must be unique. Use <override></override> tags to override an order category."); continue; } } var spriteElement = element.GetChildElement("sprite"); if (spriteElement != null) { var sprite = new Sprite(spriteElement, lazyLoad: true); var color = element.GetAttributeColor("color", Color.White); OrderCategoryIcons.Add(category, new Tuple <Sprite, Color>(sprite, color)); } } } } PrefabList = new List <Order>(Prefabs.Values); }
public ContentPackage(string filePath, string setPath = "") : this() { filePath = filePath.CleanUpPath(); if (!string.IsNullOrEmpty(setPath)) { setPath = setPath.CleanUpPath(); } XDocument doc = XMLExtensions.TryLoadXml(filePath); Path = setPath == string.Empty ? filePath : setPath; if (doc?.Root == null) { DebugConsole.ThrowError("Couldn't load content package \"" + filePath + "\"!"); IsCorrupt = true; return; } Name = doc.Root.GetAttributeString("name", ""); HideInWorkshopMenu = doc.Root.GetAttributeBool("hideinworkshopmenu", false); isCorePackage = doc.Root.GetAttributeBool("corepackage", false); SteamWorkshopId = doc.Root.GetAttributeUInt64("steamworkshopid", 0); string workshopUrl = doc.Root.GetAttributeString("steamworkshopurl", ""); if (!string.IsNullOrEmpty(workshopUrl)) { SteamWorkshopId = SteamManager.GetWorkshopItemIDFromUrl(workshopUrl); } string versionStr = doc.Root.GetAttributeString("gameversion", "0.0.0.0"); try { GameVersion = new Version(versionStr); } catch { DebugConsole.ThrowError($"Invalid version number in content package \"{Name}\" ({versionStr})."); GameVersion = GameMain.Version; } if (doc.Root.Attribute("installtime") != null) { InstallTime = ToolBox.Epoch.ToDateTime(doc.Root.GetAttributeUInt("installtime", 0)); } List <string> errorMsgs = new List <string>(); foreach (XElement subElement in doc.Root.Elements()) { if (subElement.Name.ToString().Equals("executable", StringComparison.OrdinalIgnoreCase)) { continue; } if (!Enum.TryParse(subElement.Name.ToString(), true, out ContentType type)) { errorMsgs.Add("Error in content package \"" + Name + "\" - \"" + subElement.Name.ToString() + "\" is not a valid content type."); type = ContentType.None; } files.Add(new ContentFile(subElement.GetAttributeString("file", ""), type, this)); } if (Files.Count == 0) { //no files defined, find a submarine in here //because somehow people have managed to upload //mods without contentfile definitions string folder = System.IO.Path.GetDirectoryName(filePath); if (File.Exists(System.IO.Path.Combine(folder, Name + ".sub"))) { files.Add(new ContentFile(System.IO.Path.Combine(folder, Name + ".sub"), ContentType.Submarine, this)); } else { errorMsgs.Add("Error in content package \"" + Name + "\" - no content files defined."); } } bool compatible = IsCompatible(); //If we know that the package is not compatible, don't display error messages. if (compatible) { foreach (string errorMsg in errorMsgs) { DebugConsole.ThrowError(errorMsg); } } }
protected StatusEffect(XElement element, string parentDebugName) { requiredItems = new List <RelatedItem>(); spawnItems = new List <ItemSpawnInfo>(); Afflictions = new List <Affliction>(); ReduceAffliction = new List <Pair <string, float> >(); tags = new HashSet <string>(element.GetAttributeString("tags", "").Split(',')); Range = element.GetAttributeFloat("range", 0.0f); IEnumerable <XAttribute> attributes = element.Attributes(); List <XAttribute> propertyAttributes = new List <XAttribute>(); propertyConditionals = new List <PropertyConditional>(); foreach (XAttribute attribute in attributes) { switch (attribute.Name.ToString()) { case "type": if (!Enum.TryParse(attribute.Value, true, out type)) { DebugConsole.ThrowError("Invalid action type \"" + attribute.Value + "\" in StatusEffect (" + parentDebugName + ")"); } break; case "target": string[] Flags = attribute.Value.Split(','); foreach (string s in Flags) { if (!Enum.TryParse(s, true, out TargetType targetType)) { DebugConsole.ThrowError("Invalid target type \"" + s + "\" in StatusEffect (" + parentDebugName + ")"); } else { targetTypes |= targetType; } } break; case "disabledeltatime": disableDeltaTime = attribute.GetAttributeBool(false); break; case "setvalue": setValue = attribute.GetAttributeBool(false); break; case "targetnames": DebugConsole.ThrowError("Error in StatusEffect config (" + parentDebugName + ") - use identifiers or tags to define the targets instead of names."); break; case "targetidentifiers": string[] identifiers = attribute.Value.Split(','); targetIdentifiers = new HashSet <string>(); for (int i = 0; i < identifiers.Length; i++) { targetIdentifiers.Add(identifiers[i].Trim().ToLowerInvariant()); } break; case "duration": duration = attribute.GetAttributeFloat(0.0f); break; case "stackable": Stackable = attribute.GetAttributeBool(true); break; case "checkconditionalalways": CheckConditionalAlways = attribute.GetAttributeBool(false); break; case "conditionalcomparison": case "comparison": if (!Enum.TryParse(attribute.Value, out conditionalComparison)) { DebugConsole.ThrowError("Invalid conditional comparison type \"" + attribute.Value + "\" in StatusEffect (" + parentDebugName + ")"); } break; case "sound": DebugConsole.ThrowError("Error in StatusEffect " + element.Parent.Name.ToString() + " - sounds should be defined as child elements of the StatusEffect, not as attributes."); break; default: propertyAttributes.Add(attribute); break; } } int count = propertyAttributes.Count; propertyNames = new string[count]; propertyEffects = new object[count]; int n = 0; foreach (XAttribute attribute in propertyAttributes) { propertyNames[n] = attribute.Name.ToString().ToLowerInvariant(); propertyEffects[n] = XMLExtensions.GetAttributeObject(attribute); n++; } foreach (XElement subElement in element.Elements()) { switch (subElement.Name.ToString().ToLowerInvariant()) { case "explosion": explosion = new Explosion(subElement, parentDebugName); break; case "fire": FireSize = subElement.GetAttributeFloat("size", 10.0f); break; case "use": case "useitem": useItemCount++; break; case "remove": case "removeitem": removeItem = true; break; case "requireditem": case "requireditems": RelatedItem newRequiredItem = RelatedItem.Load(subElement, parentDebugName); if (newRequiredItem == null) { DebugConsole.ThrowError("Error in StatusEffect config - requires an item with no identifiers."); continue; } requiredItems.Add(newRequiredItem); break; case "conditional": IEnumerable <XAttribute> conditionalAttributes = subElement.Attributes(); foreach (XAttribute attribute in conditionalAttributes) { if (attribute.Name.ToString().ToLowerInvariant() == "targetitemcomponent") { continue; } propertyConditionals.Add(new PropertyConditional(attribute)); } break; case "affliction": AfflictionPrefab afflictionPrefab; if (subElement.Attribute("name") != null) { DebugConsole.ThrowError("Error in StatusEffect (" + parentDebugName + ") - define afflictions using identifiers instead of names."); string afflictionName = subElement.GetAttributeString("name", "").ToLowerInvariant(); afflictionPrefab = AfflictionPrefab.List.Find(ap => ap.Name.ToLowerInvariant() == afflictionName); if (afflictionPrefab == null) { DebugConsole.ThrowError("Error in StatusEffect (" + parentDebugName + ") - Affliction prefab \"" + afflictionName + "\" not found."); continue; } } else { string afflictionIdentifier = subElement.GetAttributeString("identifier", "").ToLowerInvariant(); afflictionPrefab = AfflictionPrefab.List.Find(ap => ap.Identifier.ToLowerInvariant() == afflictionIdentifier); if (afflictionPrefab == null) { DebugConsole.ThrowError("Error in StatusEffect (" + parentDebugName + ") - Affliction prefab with the identifier \"" + afflictionIdentifier + "\" not found."); continue; } } float afflictionStrength = subElement.GetAttributeFloat(1.0f, "amount", "strength"); Afflictions.Add(afflictionPrefab.Instantiate(afflictionStrength)); break; case "reduceaffliction": if (subElement.Attribute("name") != null) { DebugConsole.ThrowError("Error in StatusEffect (" + parentDebugName + ") - define afflictions using identifiers or types instead of names."); ReduceAffliction.Add(new Pair <string, float>( subElement.GetAttributeString("name", "").ToLowerInvariant(), subElement.GetAttributeFloat(1.0f, "amount", "strength", "reduceamount"))); } else { string name = subElement.GetAttributeString("identifier", null) ?? subElement.GetAttributeString("type", null); name = name.ToLowerInvariant(); if (AfflictionPrefab.List.Any(ap => ap.Identifier == name || ap.AfflictionType == name)) { ReduceAffliction.Add(new Pair <string, float>( name, subElement.GetAttributeFloat(1.0f, "amount", "strength", "reduceamount"))); } else { DebugConsole.ThrowError("Error in StatusEffect (" + parentDebugName + ") - Affliction prefab with the identifier or type \"" + name + "\" not found."); } } break; case "spawnitem": var newSpawnItem = new ItemSpawnInfo(subElement, parentDebugName); if (newSpawnItem.ItemPrefab != null) { spawnItems.Add(newSpawnItem); } break; } } InitProjSpecific(element, parentDebugName); }
public static void LoadAll(IEnumerable <string> filePaths) { foreach (string filePath in filePaths) { XDocument doc = XMLExtensions.TryLoadXml(filePath); if (doc == null || doc.Root == null) { continue; } foreach (XElement element in doc.Root.Elements()) { switch (element.Name.ToString().ToLowerInvariant()) { case "internaldamage": List.Add(InternalDamage = new AfflictionPrefab(element, typeof(Affliction))); break; case "bleeding": List.Add(Bleeding = new AfflictionPrefab(element, typeof(AfflictionBleeding))); break; case "burn": List.Add(Burn = new AfflictionPrefab(element, typeof(Affliction))); break; case "oxygenlow": List.Add(OxygenLow = new AfflictionPrefab(element, typeof(Affliction))); break; case "bloodloss": List.Add(Bloodloss = new AfflictionPrefab(element, typeof(Affliction))); break; case "pressure": List.Add(Pressure = new AfflictionPrefab(element, typeof(Affliction))); break; case "stun": List.Add(Stun = new AfflictionPrefab(element, typeof(Affliction))); break; case "husk": case "afflictionhusk": List.Add(Husk = new AfflictionPrefab(element, typeof(AfflictionHusk))); break; case "cprsettings": CPRSettings.Load(element); break; default: List.Add(new AfflictionPrefab(element)); break; } } } if (InternalDamage == null) { DebugConsole.ThrowError("Affliction \"Internal Damage\" not defined in the affliction prefabs."); } if (Bleeding == null) { DebugConsole.ThrowError("Affliction \"Bleeding\" not defined in the affliction prefabs."); } if (Burn == null) { DebugConsole.ThrowError("Affliction \"Burn\" not defined in the affliction prefabs."); } if (OxygenLow == null) { DebugConsole.ThrowError("Affliction \"OxygenLow\" not defined in the affliction prefabs."); } if (Bloodloss == null) { DebugConsole.ThrowError("Affliction \"Bloodloss\" not defined in the affliction prefabs."); } if (Pressure == null) { DebugConsole.ThrowError("Affliction \"Pressure\" not defined in the affliction prefabs."); } if (Stun == null) { DebugConsole.ThrowError("Affliction \"Stun\" not defined in the affliction prefabs."); } if (Husk == null) { DebugConsole.ThrowError("Affliction \"Husk\" not defined in the affliction prefabs."); } }
public static void LoadPresets() { LevelParams = new List <LevelGenerationParams>(); biomes = new List <Biome>(); var files = GameMain.Instance.GetFilesOfType(ContentType.LevelGenerationParameters); if (!files.Any()) { files = new List <ContentFile>() { new ContentFile("Content/Map/LevelGenerationParameters.xml", ContentType.LevelGenerationParameters) }; } List <XElement> biomeElements = new List <XElement>(); Dictionary <string, XElement> levelParamElements = new Dictionary <string, XElement>(); 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(); biomeElements.Clear(); DebugConsole.NewMessage($"Overriding biomes with '{file.Path}'", Color.Yellow); } else if (biomeElements.Any() && mainElement.Name.ToString().Equals("biomes", StringComparison.OrdinalIgnoreCase)) { DebugConsole.ThrowError($"Error in '{file.Path}': Another level generation parameter file already loaded! Use <override></override> tags to override the biomes."); break; } foreach (XElement element in mainElement.Elements()) { bool isOverride = element.IsOverride(); if (isOverride) { if (element.FirstElement().Name.ToString().Equals("biomes", StringComparison.OrdinalIgnoreCase)) { biomeElements.Clear(); biomeElements.AddRange(element.FirstElement().Elements()); DebugConsole.NewMessage($"Overriding biomes with '{file.Path}'", Color.Yellow); } else { string identifier = element.FirstElement().GetAttributeString("identifier", null) ?? element.GetAttributeString("name", ""); if (levelParamElements.ContainsKey(identifier)) { DebugConsole.NewMessage($"Overriding the level generation parameters '{identifier}' using the file '{file.Path}'", Color.Yellow); levelParamElements.Remove(identifier); } levelParamElements.Add(identifier, element.FirstElement()); } } else if (element.Name.ToString().Equals("biomes", StringComparison.OrdinalIgnoreCase)) { biomeElements.AddRange(element.Elements()); } else { string identifier = element.GetAttributeString("identifier", null) ?? element.GetAttributeString("name", ""); if (levelParamElements.ContainsKey(identifier)) { DebugConsole.ThrowError($"Duplicate level generation parameters: '{identifier}' defined in {element.Name} of '{file.Path}'. Use <override></override> tags to override the generation parameters."); continue; } else { levelParamElements.Add(identifier, element); } } } } foreach (XElement biomeElement in biomeElements) { biomes.Add(new Biome(biomeElement)); } foreach (XElement levelParamElement in levelParamElements.Values) { LevelParams.Add(new LevelGenerationParams(levelParamElement)); } }
public static void LoadAll(IEnumerable <string> filePaths) { //language, identifier, filepath List <Tuple <string, string, string> > contentPackageFiles = new List <Tuple <string, string, string> >(); foreach (string filePath in filePaths) { if (Path.GetExtension(filePath) == ".csv") { continue; // .csv files are not supported } XDocument doc = XMLExtensions.TryLoadXml(filePath); if (doc == null || doc.Root == null) { continue; } string language = doc.Root.GetAttributeString("Language", "English"); string identifier = doc.Root.GetAttributeString("Identifier", "unknown"); contentPackageFiles.Add(new Tuple <string, string, string>(language, identifier, filePath)); } List <Tuple <string, string, string> > translationFiles = new List <Tuple <string, string, string> >(); foreach (string filePath in Directory.GetFiles(Path.Combine("Content", "NPCConversations"))) { if (Path.GetExtension(filePath) == ".csv") { continue; // .csv files are not supported } XDocument doc = XMLExtensions.TryLoadXml(filePath); if (doc == null || doc.Root == null) { continue; } string language = doc.Root.GetAttributeString("Language", "English"); string identifier = doc.Root.GetAttributeString("Identifier", "unknown"); translationFiles.Add(new Tuple <string, string, string>(language, identifier, filePath)); } //get the languages and identifiers of the files for (int i = 0; i < contentPackageFiles.Count; i++) { var contentPackageFile = contentPackageFiles[i]; //correct language, all good if (contentPackageFile.Item1 == TextManager.Language) { continue; } //attempt to find a translation file with the correct language and a matching identifier //if it fails, we'll just use the original file with the incorrect language var translation = translationFiles.Find(t => t.Item1 == TextManager.Language && t.Item2 == contentPackageFile.Item2); if (translation != null) { contentPackageFiles[i] = translation; //replace with the translation file } } foreach (var file in contentPackageFiles) { Load(file.Item3); } }
public static Mission LoadRandom(Location[] locations, MTRandom rand, string missionType = "", bool isSinglePlayer = false) { missionType = missionType.ToLowerInvariant(); var files = GameMain.SelectedPackage.GetFilesOfType(ContentType.Missions); string configFile = files[rand.Next(files.Count)]; XDocument doc = XMLExtensions.TryLoadXml(configFile); if (doc == null) { return(null); } int eventCount = doc.Root.Elements().Count(); //int[] commonness = new int[eventCount]; float[] eventProbability = new float[eventCount]; float probabilitySum = 0.0f; List <XElement> matchingElements = new List <XElement>(); if (missionType == "random") { matchingElements = doc.Root.Elements().ToList(); } else if (missionType == "none") { return(null); } else if (string.IsNullOrWhiteSpace(missionType)) { matchingElements = doc.Root.Elements().ToList(); } else { matchingElements = doc.Root.Elements().ToList().FindAll(m => m.Name.ToString().ToLowerInvariant().Replace("mission", "") == missionType); } if (isSinglePlayer) { matchingElements.RemoveAll(m => m.GetAttributeBool("multiplayeronly", false)); } else { matchingElements.RemoveAll(m => m.GetAttributeBool("singleplayeronly", false)); } int i = 0; foreach (XElement element in matchingElements) { eventProbability[i] = element.GetAttributeInt("commonness", 1); probabilitySum += eventProbability[i]; i++; } float randomNumber = (float)rand.NextDouble() * probabilitySum; i = 0; foreach (XElement element in matchingElements) { if (randomNumber <= eventProbability[i]) { Type t; string type = element.Name.ToString(); try { t = Type.GetType("Barotrauma." + type, true, true); if (t == null) { DebugConsole.ThrowError("Error in " + configFile + "! Could not find a mission class of the type \"" + type + "\"."); continue; } } catch { DebugConsole.ThrowError("Error in " + configFile + "! Could not find a mission class of the type \"" + type + "\"."); continue; } ConstructorInfo constructor = t.GetConstructor(new[] { typeof(XElement), typeof(Location[]) }); object instance = constructor.Invoke(new object[] { element, locations }); Mission mission = (Mission)instance; return(mission); } randomNumber -= eventProbability[i]; i++; } return(null); }
private static void LoadFromFile(ContentFile file) { XDocument doc = XMLExtensions.TryLoadXml(file.Path); var rootElement = doc?.Root; if (rootElement == null) { return; } switch (rootElement.Name.ToString().ToLowerInvariant()) { case "upgrademodule": { new UpgradePrefab(rootElement, file.Path, false) { ContentPackage = file.ContentPackage }; break; } case "upgradecategory": { new UpgradeCategory(rootElement); break; } case "upgrademodules": { foreach (var element in rootElement.Elements()) { if (element.IsOverride()) { var upgradeElement = element.GetChildElement("upgradeprefab"); if (upgradeElement != null) { new UpgradePrefab(upgradeElement, file.Path, true) { ContentPackage = file.ContentPackage }; } else { DebugConsole.ThrowError($"Cannot find an upgrade element from the children of the override element defined in {file.Path}"); } } else { switch (element.Name.ToString().ToLowerInvariant()) { case "upgrademodule": { new UpgradePrefab(element, file.Path, false) { ContentPackage = file.ContentPackage }; break; } case "upgradecategory": { new UpgradeCategory(element); break; } } } } break; } case "override": { var upgrades = rootElement.GetChildElement("upgrademodules"); if (upgrades != null) { foreach (var element in upgrades.Elements()) { new UpgradePrefab(element, file.Path, true) { ContentPackage = file.ContentPackage }; } } foreach (var element in rootElement.GetChildElements("upgrademodule")) { new UpgradePrefab(element, file.Path, true) { ContentPackage = file.ContentPackage }; } break; } default: DebugConsole.ThrowError($"Invalid XML root element: '{rootElement.Name}' in {file.Path}\n " + "Valid elements are: \"UpgradeModule\", \"UpgradeModules\" and \"Override\"."); break; } }
public void StartServer() { string name = "Server"; int port = NetConfig.DefaultPort; int queryPort = NetConfig.DefaultQueryPort; bool publiclyVisible = false; string password = ""; bool enableUpnp = false; int maxPlayers = 10; int? ownerKey = null; UInt64 steamId = 0; XDocument doc = XMLExtensions.TryLoadXml(ServerSettings.SettingsFile); if (doc?.Root == null) { DebugConsole.ThrowError("File \"" + ServerSettings.SettingsFile + "\" not found. Starting the server with default settings."); } else { name = doc.Root.GetAttributeString("name", "Server"); port = doc.Root.GetAttributeInt("port", NetConfig.DefaultPort); queryPort = doc.Root.GetAttributeInt("queryport", NetConfig.DefaultQueryPort); publiclyVisible = doc.Root.GetAttributeBool("public", false); password = doc.Root.GetAttributeString("password", ""); enableUpnp = doc.Root.GetAttributeBool("enableupnp", false); maxPlayers = doc.Root.GetAttributeInt("maxplayers", 10); ownerKey = null; } #if DEBUG foreach (string s in CommandLineArgs) { Console.WriteLine(s); } #endif for (int i = 0; i < CommandLineArgs.Length; i++) { switch (CommandLineArgs[i].Trim()) { case "-name": name = CommandLineArgs[i + 1]; i++; break; case "-port": int.TryParse(CommandLineArgs[i + 1], out port); i++; break; case "-queryport": int.TryParse(CommandLineArgs[i + 1], out queryPort); i++; break; case "-public": bool.TryParse(CommandLineArgs[i + 1], out publiclyVisible); i++; break; case "-password": password = CommandLineArgs[i + 1]; i++; break; case "-nopassword": password = ""; break; case "-upnp": case "-enableupnp": bool.TryParse(CommandLineArgs[i + 1], out enableUpnp); i++; break; case "-maxplayers": int.TryParse(CommandLineArgs[i + 1], out maxPlayers); i++; break; case "-ownerkey": if (int.TryParse(CommandLineArgs[i + 1], out int key)) { ownerKey = key; } i++; break; case "-steamid": UInt64.TryParse(CommandLineArgs[i + 1], out steamId); i++; break; case "-pipes": ChildServerRelay.Start(CommandLineArgs[i + 2], CommandLineArgs[i + 1]); i += 2; break; } } Server = new GameServer( name, port, queryPort, publiclyVisible, password, enableUpnp, maxPlayers, ownerKey, steamId); for (int i = 0; i < CommandLineArgs.Length; i++) { switch (CommandLineArgs[i].Trim()) { case "-playstyle": Enum.TryParse(CommandLineArgs[i + 1], out PlayStyle playStyle); Server.ServerSettings.PlayStyle = playStyle; i++; break; case "-banafterwrongpassword": bool.TryParse(CommandLineArgs[i + 1], out bool banAfterWrongPassword); Server.ServerSettings.BanAfterWrongPassword = banAfterWrongPassword; break; case "-karma": case "-karmaenabled": bool.TryParse(CommandLineArgs[i + 1], out bool karmaEnabled); Server.ServerSettings.KarmaEnabled = karmaEnabled; i++; break; case "-karmapreset": string karmaPresetName = CommandLineArgs[i + 1]; Server.ServerSettings.KarmaPreset = karmaPresetName; i++; break; } } }
public ItemAssemblyPrefab(string filePath, bool allowOverwrite = false) { FilePath = filePath; XDocument doc = XMLExtensions.TryLoadXml(filePath); if (doc == null) { return; } XElement element = doc.Root; if (element.IsOverride()) { element = element.Elements().First(); } originalName = element.GetAttributeString("name", ""); identifier = element.GetAttributeString("identifier", null) ?? originalName.ToLowerInvariant().Replace(" ", ""); configElement = element; Category = MapEntityCategory.ItemAssembly; SerializableProperty.DeserializeProperties(this, configElement); name = TextManager.Get("EntityName." + identifier, returnNull: true) ?? originalName; Description = TextManager.Get("EntityDescription." + identifier, returnNull: true) ?? Description; List <ushort> containedItemIDs = new List <ushort>(); foreach (XElement entityElement in element.Elements()) { var containerElement = entityElement.Elements().FirstOrDefault(e => e.Name.LocalName.Equals("itemcontainer", StringComparison.OrdinalIgnoreCase)); if (containerElement == null) { continue; } string containedString = containerElement.GetAttributeString("contained", ""); string[] itemIdStrings = containedString.Split(','); var itemIds = new List <ushort> [itemIdStrings.Length]; for (int i = 0; i < itemIdStrings.Length; i++) { itemIds[i] ??= new List <ushort>(); foreach (string idStr in itemIdStrings[i].Split(';')) { if (int.TryParse(idStr, out int id)) { itemIds[i].Add((ushort)id); containedItemIDs.Add((ushort)id); } } } } int minX = int.MaxValue, minY = int.MaxValue; int maxX = int.MinValue, maxY = int.MinValue; DisplayEntities = new List <Pair <MapEntityPrefab, Rectangle> >(); foreach (XElement entityElement in element.Elements()) { ushort id = (ushort)entityElement.GetAttributeInt("ID", 0); if (id > 0 && containedItemIDs.Contains(id)) { continue; } string identifier = entityElement.GetAttributeString("identifier", entityElement.Name.ToString().ToLowerInvariant()); MapEntityPrefab mapEntity = List.FirstOrDefault(p => p.Identifier == identifier); if (mapEntity == null) { string entityName = entityElement.GetAttributeString("name", ""); mapEntity = List.FirstOrDefault(p => p.Name == entityName); } Rectangle rect = entityElement.GetAttributeRect("rect", Rectangle.Empty); if (mapEntity != null && !entityElement.Elements().Any(e => e.Name.LocalName.Equals("wire", StringComparison.OrdinalIgnoreCase))) { if (!entityElement.GetAttributeBool("hideinassemblypreview", false)) { DisplayEntities.Add(new Pair <MapEntityPrefab, Rectangle>(mapEntity, rect)); } minX = Math.Min(minX, rect.X); minY = Math.Min(minY, rect.Y - rect.Height); maxX = Math.Max(maxX, rect.Right); maxY = Math.Max(maxY, rect.Y); } } Bounds = minX == int.MaxValue ? new Rectangle(0, 0, 1, 1) : new Rectangle(minX, minY, maxX - minX, maxY - minY); if (allowOverwrite && Prefabs.ContainsKey(identifier)) { Prefabs.Remove(Prefabs[identifier]); } Prefabs.Add(this, doc.Root.IsOverride()); }
public bool TrySetValue(string value) { if (value == null) { return(false); } string typeName; if (!supportedTypes.TryGetValue(propertyDescriptor.PropertyType, out typeName)) { if (propertyDescriptor.PropertyType.IsEnum) { object enumVal; try { enumVal = Enum.Parse(propertyInfo.PropertyType, value, true); } catch (Exception e) { DebugConsole.ThrowError("Failed to set the value of the property \"" + Name + "\" of \"" + obj + "\" to " + value + " (not a valid " + propertyInfo.PropertyType + ")", e); return(false); } try { propertyInfo.SetValue(obj, enumVal); } catch (Exception e) { DebugConsole.ThrowError("Failed to set the value of the property \"" + Name + "\" of \"" + obj.ToString() + "\" to " + value.ToString(), e); return(false); } } else { DebugConsole.ThrowError("Failed to set the value of the property \"" + Name + "\" of \"" + obj + "\" to " + value); DebugConsole.ThrowError("(Type not supported)"); return(false); } } try { switch (typeName) { case "bool": propertyInfo.SetValue(obj, value.ToLowerInvariant() == "true", null); break; case "int": int intVal; if (int.TryParse(value, out intVal)) { propertyInfo.SetValue(obj, intVal, null); } break; case "float": float floatVal; if (float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out floatVal)) { propertyInfo.SetValue(obj, floatVal, null); } break; case "string": propertyInfo.SetValue(obj, value, null); break; case "vector2": propertyInfo.SetValue(obj, XMLExtensions.ParseVector2(value)); break; case "vector3": propertyInfo.SetValue(obj, XMLExtensions.ParseVector3(value)); break; case "vector4": propertyInfo.SetValue(obj, XMLExtensions.ParseVector4(value)); break; case "color": propertyInfo.SetValue(obj, XMLExtensions.ParseColor(value)); break; case "rectangle": propertyInfo.SetValue(obj, XMLExtensions.ParseRect(value, true)); break; } } catch (Exception e) { DebugConsole.ThrowError("Failed to set the value of the property \"" + Name + "\" of \"" + obj.ToString() + "\" to " + value.ToString(), e); return(false); } return(true); }
public override XElement Save(XElement parentElement) { XElement saveElement = null; if (sub == null) { if (this.saveElement == null) { var doc = SubmarineInfo.OpenFile(filePath); saveElement = doc.Root; saveElement.Name = "LinkedSubmarine"; saveElement.Add(new XAttribute("filepath", filePath)); } else { saveElement = this.saveElement; } if (saveElement.Attribute("pos") != null) { saveElement.Attribute("pos").Remove(); } saveElement.Add(new XAttribute("pos", XMLExtensions.Vector2ToString(Position - Submarine.HiddenSubPosition))); var linkedPort = linkedTo.FirstOrDefault(lt => (lt is Item) && ((Item)lt).GetComponent <DockingPort>() != null); if (linkedPort != null) { saveElement.Attribute("linkedto")?.Remove(); saveElement.Add(new XAttribute("linkedto", linkedPort.ID)); } } else { saveElement = new XElement("LinkedSubmarine"); sub.SaveToXElement(saveElement); } saveElement.Attribute("originallinkedto")?.Remove(); saveElement.Add(new XAttribute("originallinkedto", originalLinkedPort != null ? originalLinkedPort.Item.ID : originalLinkedToID)); saveElement.Attribute("originalmyport")?.Remove(); saveElement.Add(new XAttribute("originalmyport", originalMyPortID)); if (sub != null) { bool leaveBehind = false; if (!sub.DockedTo.Contains(Submarine.MainSub)) { System.Diagnostics.Debug.Assert(Submarine.MainSub.AtEndPosition || Submarine.MainSub.AtStartPosition); if (Submarine.MainSub.AtEndPosition) { leaveBehind = sub.AtEndPosition != Submarine.MainSub.AtEndPosition; } else { leaveBehind = sub.AtStartPosition != Submarine.MainSub.AtStartPosition; } } if (leaveBehind) { saveElement.SetAttributeValue("location", Level.Loaded.Seed); saveElement.SetAttributeValue("worldpos", XMLExtensions.Vector2ToString(sub.SubBody.Position)); } else { if (saveElement.Attribute("location") != null) { saveElement.Attribute("location").Remove(); } if (saveElement.Attribute("worldpos") != null) { saveElement.Attribute("worldpos").Remove(); } } saveElement.SetAttributeValue("pos", XMLExtensions.Vector2ToString(Position - Submarine.HiddenSubPosition)); } parentElement.Add(saveElement); return(saveElement); }
public static void SerializeProperties(ISerializableEntity obj, XElement element, bool saveIfDefault = false) { var saveProperties = GetProperties <Serialize>(obj); foreach (var property in saveProperties) { object value = property.GetValue(); if (value == null) { continue; } if (!saveIfDefault) { //only save // - if the attribute is saveable and it's different from the default value // - or can be changed in-game or in the editor bool save = false; foreach (var attribute in property.Attributes.OfType <Serialize>()) { if ((attribute.isSaveable && !attribute.defaultValue.Equals(value)) || property.Attributes.OfType <Editable>().Any()) { save = true; break; } } if (!save) { continue; } } string stringValue; string typeName; if (!supportedTypes.TryGetValue(value.GetType(), out typeName)) { if (property.PropertyType.IsEnum) { stringValue = value.ToString(); } else { DebugConsole.ThrowError("Failed to serialize the property \"" + property.Name + "\" of \"" + obj + "\" (type " + property.PropertyType + " not supported)"); continue; } } else { switch (typeName) { case "float": //make sure the decimal point isn't converted to a comma or anything else stringValue = ((float)value).ToString("G", CultureInfo.InvariantCulture); break; case "vector2": stringValue = XMLExtensions.Vector2ToString((Vector2)value); break; case "vector3": stringValue = XMLExtensions.Vector3ToString((Vector3)value); break; case "vector4": stringValue = XMLExtensions.Vector4ToString((Vector4)value); break; case "color": stringValue = XMLExtensions.ColorToString((Color)value); break; case "rectangle": stringValue = XMLExtensions.RectToString((Rectangle)value); break; default: stringValue = value.ToString(); break; } } element.SetAttributeValue(property.Name.ToLowerInvariant(), stringValue); } }
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); 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()) { InputType inputType; if (Enum.TryParse(attribute.Name.ToString(), true, out inputType)) { int mouseButton; if (int.TryParse(attribute.Value.ToString(), out mouseButton)) { keyMapping[(int)inputType] = new KeyOrMouse(mouseButton); } else { Keys key; if (Enum.TryParse(attribute.Value.ToString(), true, out 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", ""); 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; } } }
public static List <Limb> AttachHuskAppendage(Character character, string afflictionIdentifier, XElement appendageDefinition = null, Ragdoll ragdoll = null) { var appendage = new List <Limb>(); if (!(AfflictionPrefab.List.FirstOrDefault(ap => ap.Identifier == afflictionIdentifier) is AfflictionPrefabHusk matchingAffliction)) { DebugConsole.ThrowError($"Could not find an affliction of type 'huskinfection' that matches the affliction '{afflictionIdentifier}'!"); return(appendage); } string nonhuskedSpeciesName = GetNonHuskedSpeciesName(character.SpeciesName, matchingAffliction); string huskedSpeciesName = GetHuskedSpeciesName(nonhuskedSpeciesName, matchingAffliction); CharacterPrefab huskPrefab = CharacterPrefab.FindBySpeciesName(huskedSpeciesName); if (huskPrefab?.XDocument == null) { DebugConsole.ThrowError($"Failed to find the config file for the husk infected species with the species name '{huskedSpeciesName}'!"); return(appendage); } var mainElement = huskPrefab.XDocument.Root.IsOverride() ? huskPrefab.XDocument.Root.FirstElement() : huskPrefab.XDocument.Root; var element = appendageDefinition; if (element == null) { element = mainElement.GetChildElements("huskappendage").FirstOrDefault(e => e.GetAttributeString("affliction", string.Empty).Equals(afflictionIdentifier)); } if (element == null) { DebugConsole.ThrowError($"Error in '{huskPrefab.FilePath}': Failed to find a huskappendage that matches the affliction with an identifier '{afflictionIdentifier}'!"); return(appendage); } string pathToAppendage = element.GetAttributeString("path", string.Empty); XDocument doc = XMLExtensions.TryLoadXml(pathToAppendage); if (doc == null) { return(appendage); } if (ragdoll == null) { ragdoll = character.AnimController; } if (ragdoll.Dir < 1.0f) { ragdoll.Flip(); } var limbElements = doc.Root.Elements("limb").ToDictionary(e => e.GetAttributeString("id", null), e => e); foreach (var jointElement in doc.Root.Elements("joint")) { if (limbElements.TryGetValue(jointElement.GetAttributeString("limb2", null), out XElement limbElement)) { var jointParams = new RagdollParams.JointParams(jointElement, ragdoll.RagdollParams); Limb attachLimb = null; if (matchingAffliction.AttachLimbId > -1) { attachLimb = ragdoll.Limbs.FirstOrDefault(l => !l.IsSevered && l.Params.ID == matchingAffliction.AttachLimbId); } else if (matchingAffliction.AttachLimbName != null) { attachLimb = ragdoll.Limbs.FirstOrDefault(l => !l.IsSevered && l.Name == matchingAffliction.AttachLimbName); } else if (matchingAffliction.AttachLimbType != LimbType.None) { attachLimb = ragdoll.Limbs.FirstOrDefault(l => !l.IsSevered && l.type == matchingAffliction.AttachLimbType); } if (attachLimb == null) { attachLimb = ragdoll.Limbs.FirstOrDefault(l => !l.IsSevered && l.Params.ID == jointParams.Limb1); } if (attachLimb != null) { jointParams.Limb1 = attachLimb.Params.ID; var appendageLimbParams = new RagdollParams.LimbParams(limbElement, ragdoll.RagdollParams) { // Ensure that we have a valid id for the new limb ID = ragdoll.Limbs.Length }; jointParams.Limb2 = appendageLimbParams.ID; Limb huskAppendage = new Limb(ragdoll, character, appendageLimbParams); huskAppendage.body.Submarine = character.Submarine; huskAppendage.body.SetTransform(attachLimb.SimPosition, attachLimb.Rotation); ragdoll.AddLimb(huskAppendage); ragdoll.AddJoint(jointParams); appendage.Add(huskAppendage); } } } return(appendage); }
public static void LoadFromFile(ContentFile file) { DebugConsole.Log("*** " + file.Path + " ***"); RemoveByFile(file.Path); XDocument doc = XMLExtensions.TryLoadXml(file.Path); if (doc == null) { return; } var rootElement = doc.Root; switch (rootElement.Name.ToString().ToLowerInvariant()) { case "item": new ItemPrefab(rootElement, file.Path, false) { ContentPackage = file.ContentPackage }; break; case "items": foreach (var element in rootElement.Elements()) { if (element.IsOverride()) { var itemElement = element.GetChildElement("item"); if (itemElement != null) { new ItemPrefab(itemElement, file.Path, true) { ContentPackage = file.ContentPackage, IsOverride = true }; } else { DebugConsole.ThrowError($"Cannot find an item element from the children of the override element defined in {file.Path}"); } } else { new ItemPrefab(element, file.Path, false) { ContentPackage = file.ContentPackage }; } } break; case "override": var items = rootElement.GetChildElement("items"); if (items != null) { foreach (var element in items.Elements()) { new ItemPrefab(element, file.Path, true) { ContentPackage = file.ContentPackage, IsOverride = true }; } } foreach (var element in rootElement.GetChildElements("item")) { new ItemPrefab(element, file.Path, true) { ContentPackage = file.ContentPackage }; } break; default: DebugConsole.ThrowError($"Invalid XML root element: '{rootElement.Name.ToString()}' in {file.Path}"); break; } }
public void CheckForDuplicates(int index) { Dictionary <string, int> tagCounts = new Dictionary <string, int>(); Dictionary <string, int> contentCounts = new Dictionary <string, int>(); XDocument doc = XMLExtensions.TryLoadXml(FilePath); if (doc == null) { return; } foreach (XElement subElement in doc.Root.Elements()) { string infoName = subElement.Name.ToString().ToLowerInvariant(); if (!tagCounts.ContainsKey(infoName)) { tagCounts.Add(infoName, 1); } else { tagCounts[infoName] += 1; } string infoContent = subElement.Value; if (string.IsNullOrEmpty(infoContent)) { continue; } if (!contentCounts.ContainsKey(infoContent)) { contentCounts.Add(infoContent, 1); } else { contentCounts[infoContent] += 1; } } StringBuilder sb = new StringBuilder(); sb.Append("Language: " + Language); sb.AppendLine(); sb.Append("Duplicate tags:"); sb.AppendLine(); sb.AppendLine(); for (int i = 0; i < tagCounts.Keys.Count; i++) { if (tagCounts[texts.Keys.ElementAt(i)] > 1) { sb.Append(texts.Keys.ElementAt(i) + " | Count: " + tagCounts[texts.Keys.ElementAt(i)]); sb.AppendLine(); } } sb.AppendLine(); sb.AppendLine(); sb.Append("Duplicate content:"); sb.AppendLine(); sb.AppendLine(); for (int i = 0; i < contentCounts.Keys.Count; i++) { if (contentCounts[contentCounts.Keys.ElementAt(i)] > 1) { sb.Append(contentCounts.Keys.ElementAt(i) + " | Count: " + contentCounts[contentCounts.Keys.ElementAt(i)]); sb.AppendLine(); } } File.WriteAllText(@"duplicate_" + Language.ToLower() + "_" + index + ".txt", sb.ToString()); }
public void StartServer() { string name = "Server"; int port = NetConfig.DefaultPort; int queryPort = NetConfig.DefaultQueryPort; bool publiclyVisible = false; string password = ""; bool enableUpnp = false; int maxPlayers = 10; int ownerKey = 0; XDocument doc = XMLExtensions.TryLoadXml(ServerSettings.SettingsFile); if (doc?.Root == null) { DebugConsole.ThrowError("File \"" + ServerSettings.SettingsFile + "\" not found. Starting the server with default settings."); } else { name = doc.Root.GetAttributeString("name", "Server"); port = doc.Root.GetAttributeInt("port", NetConfig.DefaultPort); queryPort = doc.Root.GetAttributeInt("queryport", NetConfig.DefaultQueryPort); publiclyVisible = doc.Root.GetAttributeBool("public", false); password = doc.Root.GetAttributeString("password", ""); enableUpnp = doc.Root.GetAttributeBool("enableupnp", false); maxPlayers = doc.Root.GetAttributeInt("maxplayers", 10); ownerKey = 0; } for (int i = 0; i < CommandLineArgs.Length; i++) { switch (CommandLineArgs[i].Trim()) { case "-name": name = CommandLineArgs[i + 1]; i++; break; case "-port": int.TryParse(CommandLineArgs[i + 1], out port); i++; break; case "-queryport": int.TryParse(CommandLineArgs[i + 1], out queryPort); i++; break; case "-public": bool.TryParse(CommandLineArgs[i + 1], out publiclyVisible); i++; break; case "-password": password = CommandLineArgs[i + 1]; i++; break; case "-upnp": case "-enableupnp": bool.TryParse(CommandLineArgs[i + 1], out enableUpnp); i++; break; case "-maxplayers": int.TryParse(CommandLineArgs[i + 1], out maxPlayers); i++; break; case "-ownerkey": int.TryParse(CommandLineArgs[i + 1], out ownerKey); i++; break; } } Server = new GameServer( name, port, queryPort, publiclyVisible, password, enableUpnp, maxPlayers, ownerKey); }
public GUIMessageBox Create() { var box = new GUIMessageBox(TextManager.Get("leveleditor.createlevelobj"), string.Empty, new string[] { TextManager.Get("cancel"), TextManager.Get("done") }, new Vector2(0.5f, 0.8f)); box.Content.ChildAnchor = Anchor.TopCenter; box.Content.AbsoluteSpacing = 20; int elementSize = 30; var listBox = new GUIListBox(new RectTransform(new Vector2(1, 0.9f), box.Content.RectTransform)); new GUITextBlock(new RectTransform(new Point(listBox.Content.Rect.Width, elementSize), listBox.Content.RectTransform), TextManager.Get("leveleditor.levelobjname")) { CanBeFocused = false }; var nameBox = new GUITextBox(new RectTransform(new Point(listBox.Content.Rect.Width, elementSize), listBox.Content.RectTransform)); new GUITextBlock(new RectTransform(new Point(listBox.Content.Rect.Width, elementSize), listBox.Content.RectTransform), TextManager.Get("leveleditor.levelobjtexturepath")) { CanBeFocused = false }; var texturePathBox = new GUITextBox(new RectTransform(new Point(listBox.Content.Rect.Width, elementSize), listBox.Content.RectTransform)); foreach (LevelObjectPrefab prefab in LevelObjectPrefab.List) { if (prefab.Sprites.FirstOrDefault() == null) { continue; } texturePathBox.Text = Path.GetDirectoryName(prefab.Sprites.FirstOrDefault().FilePath); break; } newPrefab = new LevelObjectPrefab(null); new SerializableEntityEditor(listBox.Content.RectTransform, newPrefab, false, false); box.Buttons[0].OnClicked += (b, d) => { box.Close(); return(true); }; // Next box.Buttons[1].OnClicked += (b, d) => { if (string.IsNullOrEmpty(nameBox.Text)) { nameBox.Flash(GUI.Style.Red); GUI.AddMessage(TextManager.Get("leveleditor.levelobjnameempty"), GUI.Style.Red); return(false); } if (LevelObjectPrefab.List.Any(obj => obj.Name.ToLower() == nameBox.Text.ToLower())) { nameBox.Flash(GUI.Style.Red); GUI.AddMessage(TextManager.Get("leveleditor.levelobjnametaken"), GUI.Style.Red); return(false); } if (!File.Exists(texturePathBox.Text)) { texturePathBox.Flash(GUI.Style.Red); GUI.AddMessage(TextManager.Get("leveleditor.levelobjtexturenotfound"), GUI.Style.Red); return(false); } newPrefab.Name = nameBox.Text; System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings { Indent = true }; foreach (ContentFile configFile in GameMain.Instance.GetFilesOfType(ContentType.LevelObjectPrefabs)) { XDocument doc = XMLExtensions.TryLoadXml(configFile.Path); if (doc == null) { continue; } var newElement = new XElement(newPrefab.Name); newPrefab.Save(newElement); newElement.Add(new XElement("Sprite", new XAttribute("texture", texturePathBox.Text), new XAttribute("sourcerect", "0,0,100,100"), new XAttribute("origin", "0.5,0.5"))); doc.Root.Add(newElement); using (var writer = XmlWriter.Create(configFile.Path, settings)) { doc.WriteTo(writer); writer.Flush(); } // Recreate the prefab so that the sprite loads correctly: TODO: consider a better way to do this newPrefab = new LevelObjectPrefab(newElement); break; } LevelObjectPrefab.List.Add(newPrefab); GameMain.LevelEditorScreen.UpdateLevelObjectsList(); box.Close(); return(true); }; return(box); }
public static void LoadPrefabs() { #if CLIENT EventSprites.ForEach(pair => pair.Value?.Remove()); EventSprites.Clear(); #endif List = new List <EventSet>(); var configFiles = GameMain.Instance.GetFilesOfType(ContentType.RandomEvents); if (!configFiles.Any()) { DebugConsole.ThrowError("No config files for random events found in the selected content package"); return; } List <XElement> configElements = new List <XElement>(); Dictionary <XElement, string> filePaths = new Dictionary <XElement, string>(); foreach (ContentFile configFile in configFiles) { XDocument doc = XMLExtensions.TryLoadXml(configFile.Path); if (doc == null) { continue; } var mainElement = doc.Root.IsOverride() ? doc.Root.FirstElement() : doc.Root; if (doc.Root.IsOverride()) { DebugConsole.NewMessage($"Overriding all random events using the file {configFile.Path}", Color.Yellow); List.Clear(); } foreach (XElement element in doc.Root.Elements()) { configElements.Add(element); filePaths[element] = configFile.Path; } } //load event prefabs first so we can link to them when loading event sets foreach (XElement element in configElements) { switch (element.Name.ToString().ToLowerInvariant()) { case "eventprefabs": foreach (var subElement in element.Elements()) { // Warn if an event prefab has no identifier as this would make it impossible to refer to if (!element.GetAttributeBool("suppresswarnings", false) && string.IsNullOrWhiteSpace(subElement.GetAttributeString("identifier", string.Empty))) { DebugConsole.AddWarning($"An event prefab {subElement.Name} in {filePaths[element]} is missing an identifier."); } PrefabList.Add(new EventPrefab(subElement)); } break; case "eventsprites": #if CLIENT foreach (var subElement in element.Elements()) { string identifier = subElement.GetAttributeString("identifier", string.Empty); if (EventSprites.ContainsKey(identifier)) { EventSprites[identifier]?.Remove(); EventSprites[identifier] = new Sprite(subElement); continue; } else { EventSprites.Add(identifier, new Sprite(subElement)); } } #endif break; } } int i = 0; foreach (XElement element in configElements) { switch (element.Name.ToString().ToLowerInvariant()) { case "eventset": List.Add(new EventSet(element, i.ToString())); i++; break; } } }
private void SerializeAll() { XmlWriterSettings settings = new XmlWriterSettings { Indent = true, NewLineOnAttributes = true }; foreach (string configFile in GameMain.Instance.GetFilesOfType(ContentType.LevelGenerationParameters)) { XDocument doc = XMLExtensions.TryLoadXml(configFile); if (doc == null || doc.Root == null) { continue; } foreach (LevelGenerationParams genParams in LevelGenerationParams.LevelParams) { foreach (XElement element in doc.Root.Elements()) { if (element.Name.ToString().ToLowerInvariant() != genParams.Name.ToLowerInvariant()) { continue; } SerializableProperty.SerializeProperties(genParams, element, true); break; } } using (var writer = XmlWriter.Create(configFile, settings)) { doc.WriteTo(writer); writer.Flush(); } } settings.NewLineOnAttributes = false; foreach (string configFile in GameMain.Instance.GetFilesOfType(ContentType.LevelObjectPrefabs)) { XDocument doc = XMLExtensions.TryLoadXml(configFile); if (doc == null || doc.Root == null) { continue; } foreach (LevelObjectPrefab levelObjPrefab in LevelObjectPrefab.List) { foreach (XElement element in doc.Root.Elements()) { if (element.Name.ToString().ToLowerInvariant() != levelObjPrefab.Name.ToLowerInvariant()) { continue; } levelObjPrefab.Save(element); break; } } using (var writer = XmlWriter.Create(configFile, settings)) { doc.WriteTo(writer); writer.Flush(); } } RuinGenerationParams.SaveAll(); }
public static IEnumerable <object> Init() { OverrideMusicType = null; List <string> soundFiles = GameMain.Config.SelectedContentPackage.GetFilesOfType(ContentType.Sounds); List <XElement> soundElements = new List <XElement>(); foreach (string soundFile in soundFiles) { XDocument doc = XMLExtensions.TryLoadXml(soundFile); if (doc != null && doc.Root != null) { soundElements.AddRange(doc.Root.Elements()); } } SoundCount = 1 + soundElements.Count(); var startUpSoundElement = soundElements.Find(e => e.Name.ToString().ToLowerInvariant() == "startupsound"); if (startUpSoundElement != null) { startUpSound = Sound.Load(startUpSoundElement, false); startUpSound.Play(); } yield return(CoroutineStatus.Running); List <KeyValuePair <string, Sound> > miscSoundList = new List <KeyValuePair <string, Sound> >(); damageSounds = new List <DamageSound>(); musicClips = new List <BackgroundMusic>(); foreach (XElement soundElement in soundElements) { yield return(CoroutineStatus.Running); switch (soundElement.Name.ToString().ToLowerInvariant()) { case "music": string file = soundElement.GetAttributeString("file", ""); string type = soundElement.GetAttributeString("type", "").ToLowerInvariant(); Vector2 priority = soundElement.GetAttributeVector2("priorityrange", new Vector2(0.0f, 100.0f)); musicClips.Add(new BackgroundMusic(file, type, priority)); break; case "splash": SplashSounds.Add(Sound.Load(soundElement, false)); break; case "flow": FlowSounds.Add(Sound.Load(soundElement, false)); break; case "waterambience": waterAmbiences.Add(Sound.Load(soundElement, false)); break; case "damagesound": Sound damageSound = Sound.Load(soundElement.GetAttributeString("file", ""), false); if (damageSound == null) { continue; } string damageSoundType = soundElement.GetAttributeString("damagesoundtype", "None"); damageSounds.Add(new DamageSound( damageSound, soundElement.GetAttributeVector2("damagerange", new Vector2(0.0f, 100.0f)), damageSoundType, soundElement.GetAttributeString("requiredtag", ""))); break; default: Sound sound = Sound.Load(soundElement.GetAttributeString("file", ""), false); if (sound != null) { miscSoundList.Add(new KeyValuePair <string, Sound>(soundElement.Name.ToString().ToLowerInvariant(), sound)); } break; } } miscSounds = miscSoundList.ToLookup(kvp => kvp.Key, kvp => kvp.Value); Initialized = true; yield return(CoroutineStatus.Success); }
private void LoadSprites() { loadedSprites.ForEach(s => s.Remove()); loadedSprites.Clear(); //foreach (string filePath in ContentPackage.GetAllContentFiles(GameMain.SelectedPackages)) //{ // XDocument doc = XMLExtensions.TryLoadXml(filePath); // if (doc != null && doc.Root != null) // { // LoadSprites(doc.Root); // } //} foreach (string filePath in Directory.GetFiles("Content/", "*.xml", SearchOption.AllDirectories)) { XDocument doc = XMLExtensions.TryLoadXml(filePath); if (doc != null && doc.Root != null) { LoadSprites(doc.Root); } } void LoadSprites(XElement element) { element.Elements("sprite").ForEach(s => CreateSprite(s)); element.Elements("Sprite").ForEach(s => CreateSprite(s)); element.Elements("backgroundsprite").ForEach(s => CreateSprite(s)); element.Elements("BackgroundSprite").ForEach(s => CreateSprite(s)); element.Elements("brokensprite").ForEach(s => CreateSprite(s)); element.Elements("BrokenSprite").ForEach(s => CreateSprite(s)); element.Elements("containedsprite").ForEach(s => CreateSprite(s)); element.Elements("ContainedSprite").ForEach(s => CreateSprite(s)); element.Elements("inventoryicon").ForEach(s => CreateSprite(s)); element.Elements("InventoryIcon").ForEach(s => CreateSprite(s)); //decorativesprites don't necessarily have textures (can be used to hide/disable other sprites) element.Elements("decorativesprite").ForEach(s => { if (s.Attribute("texture") != null) { CreateSprite(s); } }); element.Elements("DecorativeSprite").ForEach(s => { if (s.Attribute("texture") != null) { CreateSprite(s); } }); element.Elements().ForEach(e => LoadSprites(e)); } void CreateSprite(XElement element) { string spriteFolder = ""; string textureElement = element.GetAttributeString("texture", ""); // TODO: parse and create if (textureElement.Contains("[GENDER]") || textureElement.Contains("[HEADID]") || textureElement.Contains("[RACE]")) { return; } if (!textureElement.Contains("/")) { spriteFolder = Path.GetDirectoryName(element.ParseContentPathFromUri()); } // Uncomment if we do multiple passes -> there can be duplicates //string identifier = Sprite.GetID(element); //if (loadedSprites.None(s => s.ID == identifier)) //{ // loadedSprites.Add(new Sprite(element, spriteFolder)); //} loadedSprites.Add(new Sprite(element, spriteFolder)); } }
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; 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; } }