private SkillSettings(XElement element) { SerializableProperties = SerializableProperty.DeserializeProperties(this, element); }
public JobPrefab(XElement element) { SerializableProperty.DeserializeProperties(this, element); Name = TextManager.Get("JobName." + Identifier); Description = TextManager.Get("JobDescription." + Identifier); ItemNames = new List <string>(); Skills = new List <SkillPrefab>(); foreach (XElement subElement in element.Elements()) { switch (subElement.Name.ToString().ToLowerInvariant()) { case "items": Items = subElement; foreach (XElement itemElement in subElement.Elements()) { if (itemElement.Element("name") != null) { DebugConsole.ThrowError("Error in job config \"" + Name + "\" - use identifiers instead of names to configure the items."); ItemNames.Add(itemElement.GetAttributeString("name", "")); continue; } string itemIdentifier = itemElement.GetAttributeString("identifier", ""); if (string.IsNullOrWhiteSpace(itemIdentifier)) { DebugConsole.ThrowError("Error in job config \"" + Name + "\" - item with no identifier."); ItemNames.Add(""); } else { var prefab = MapEntityPrefab.Find(null, itemIdentifier) as ItemPrefab; if (prefab == null) { DebugConsole.ThrowError("Error in job config \"" + Name + "\" - item prefab \"" + itemIdentifier + "\" not found."); ItemNames.Add(""); } else { ItemNames.Add(prefab.Name); } } } break; case "skills": foreach (XElement skillElement in subElement.Elements()) { Skills.Add(new SkillPrefab(skillElement)); } break; } } Skills.Sort((x, y) => y.LevelRange.X.CompareTo(x.LevelRange.X)); ClothingElement = element.Element("PortraitClothing"); if (ClothingElement == null) { ClothingElement = element.Element("portraitclothing"); } }
public Limb(Ragdoll ragdoll, Character character, LimbParams limbParams) { this.ragdoll = ragdoll; this.character = character; this.limbParams = limbParams; wearingItems = new List <WearableSprite>(); dir = Direction.Right; body = new PhysicsBody(limbParams); type = limbParams.Type; if (limbParams.IgnoreCollisions) { body.CollisionCategories = Category.None; body.CollidesWith = Category.None; ignoreCollisions = true; } else { //limbs don't collide with each other body.CollisionCategories = Physics.CollisionCharacter; body.CollidesWith = Physics.CollisionAll & ~Physics.CollisionCharacter & ~Physics.CollisionItem & ~Physics.CollisionItemBlocking; } body.UserData = this; pullJoint = new FixedMouseJoint(body.FarseerBody, ConvertUnits.ToSimUnits(limbParams.PullPos * Scale)) { Enabled = false, MaxForce = ((type == LimbType.LeftHand || type == LimbType.RightHand) ? 400.0f : 150.0f) * body.Mass }; GameMain.World.AddJoint(pullJoint); var element = limbParams.Element; if (element.Attribute("mouthpos") != null) { MouthPos = ConvertUnits.ToSimUnits(element.GetAttributeVector2("mouthpos", Vector2.Zero)); } body.BodyType = BodyType.Dynamic; body.FarseerBody.AngularDamping = LimbAngularDamping; damageModifiers = new List <DamageModifier>(); foreach (XElement subElement in element.Elements()) { switch (subElement.Name.ToString().ToLowerInvariant()) { case "attack": attack = new Attack(subElement, (character == null ? "null" : character.Name) + ", limb " + type); if (attack.DamageRange <= 0) { switch (body.BodyShape) { case PhysicsBody.Shape.Circle: attack.DamageRange = body.radius; break; case PhysicsBody.Shape.Capsule: attack.DamageRange = body.height / 2 + body.radius; break; case PhysicsBody.Shape.Rectangle: attack.DamageRange = new Vector2(body.width / 2.0f, body.height / 2.0f).Length(); break; } attack.DamageRange = ConvertUnits.ToDisplayUnits(attack.DamageRange); } break; case "damagemodifier": damageModifiers.Add(new DamageModifier(subElement, character.Name)); break; } } SerializableProperties = SerializableProperty.GetProperties(this); InitProjSpecific(element); }
public ItemAssemblyPrefab(string filePath) { 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; } var itemIds = containerElement.GetAttributeIntArray("contained", new int[0]); containedItemIDs.AddRange(itemIds.Select(id => (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); Prefabs.Add(this, doc.Root.IsOverride()); }
public void Deserialize(XElement element) { SerializableProperties = SerializableProperty.DeserializeProperties(this, element); }
public OutpostModuleInfo(SubmarineInfo submarineInfo) { Name = $"OutpostModuleInfo ({submarineInfo.Name})"; SerializableProperties = SerializableProperty.DeserializeProperties(this); }
public static StructurePrefab Load(XElement element) { StructurePrefab sp = new StructurePrefab { name = element.GetAttributeString("name", "") }; sp.ConfigElement = element; if (string.IsNullOrEmpty(sp.name)) { sp.name = element.Name.ToString(); } sp.identifier = element.GetAttributeString("identifier", ""); string translatedName = TextManager.Get("EntityName." + sp.identifier, true); if (!string.IsNullOrEmpty(translatedName)) { sp.name = translatedName; } sp.Tags = new HashSet <string>(); string joinedTags = element.GetAttributeString("tags", ""); if (string.IsNullOrEmpty(joinedTags)) { joinedTags = element.GetAttributeString("Tags", ""); } foreach (string tag in joinedTags.Split(',')) { sp.Tags.Add(tag.Trim().ToLowerInvariant()); } foreach (XElement subElement in element.Elements()) { switch (subElement.Name.ToString()) { case "sprite": sp.sprite = new Sprite(subElement); if (subElement.Attribute("sourcerect") == null) { DebugConsole.ThrowError("Warning - sprite sourcerect not configured for structure \"" + sp.name + "\"!"); } if (subElement.GetAttributeBool("fliphorizontal", false)) { sp.sprite.effects = SpriteEffects.FlipHorizontally; } if (subElement.GetAttributeBool("flipvertical", false)) { sp.sprite.effects = SpriteEffects.FlipVertically; } sp.canSpriteFlipX = subElement.GetAttributeBool("canflipx", true); sp.canSpriteFlipY = subElement.GetAttributeBool("canflipy", true); if (subElement.Attribute("name") == null && !string.IsNullOrWhiteSpace(sp.Name)) { sp.sprite.Name = sp.Name; } sp.sprite.EntityID = sp.identifier; break; case "backgroundsprite": sp.BackgroundSprite = new Sprite(subElement); if (subElement.GetAttributeBool("fliphorizontal", false)) { sp.BackgroundSprite.effects = SpriteEffects.FlipHorizontally; } if (subElement.GetAttributeBool("flipvertical", false)) { sp.BackgroundSprite.effects = SpriteEffects.FlipVertically; } break; } } if (!Enum.TryParse(element.GetAttributeString("category", "Structure"), true, out MapEntityCategory category)) { category = MapEntityCategory.Structure; } sp.Category = category; string aliases = element.GetAttributeString("aliases", ""); if (!string.IsNullOrWhiteSpace(aliases)) { sp.Aliases = aliases.Split(','); } SerializableProperty.DeserializeProperties(sp, element); if (sp.Body) { sp.Tags.Add("wall"); } string translatedDescription = TextManager.Get("EntityDescription." + sp.identifier, true); if (!string.IsNullOrEmpty(translatedDescription)) { sp.Description = translatedDescription; } //backwards compatibility if (element.Attribute("size") == null) { sp.size = Vector2.Zero; if (element.Attribute("width") == null && element.Attribute("height") == null) { sp.size.X = sp.sprite.SourceRect.Width; sp.size.Y = sp.sprite.SourceRect.Height; } else { sp.size.X = element.GetAttributeFloat("width", 0.0f); sp.size.Y = element.GetAttributeFloat("height", 0.0f); } } if (!category.HasFlag(MapEntityCategory.Legacy) && string.IsNullOrEmpty(sp.identifier)) { DebugConsole.ThrowError( "Structure prefab \"" + sp.name + "\" has no identifier. All structure prefabs have a unique identifier string that's used to differentiate between items during saving and loading."); } if (!string.IsNullOrEmpty(sp.identifier)) { MapEntityPrefab existingPrefab = List.Find(e => e.Identifier == sp.identifier); if (existingPrefab != null) { DebugConsole.ThrowError( "Map entity prefabs \"" + sp.name + "\" and \"" + existingPrefab.Name + "\" have the same identifier!"); } } return(sp); }
public Structure(Rectangle rectangle, StructurePrefab sp, Submarine submarine) : base(sp, submarine) { if (rectangle.Width == 0 || rectangle.Height == 0) { return; } System.Diagnostics.Debug.Assert(rectangle.Width > 0 && rectangle.Height > 0); rect = rectangle; prefab = sp; spriteColor = prefab.SpriteColor; isHorizontal = (rect.Width > rect.Height); StairDirection = prefab.StairDirection; SerializableProperties = SerializableProperty.GetProperties(this); if (prefab.Body) { bodies = new List <Body>(); //gaps = new List<Gap>(); Body newBody = BodyFactory.CreateRectangle(GameMain.World, ConvertUnits.ToSimUnits(rect.Width), ConvertUnits.ToSimUnits(rect.Height), 1.5f); newBody.BodyType = BodyType.Static; newBody.Position = ConvertUnits.ToSimUnits(new Vector2(rect.X + rect.Width / 2.0f, rect.Y - rect.Height / 2.0f)); newBody.Friction = 0.5f; newBody.OnCollision += OnWallCollision; newBody.UserData = this; newBody.CollisionCategories = (prefab.Platform) ? Physics.CollisionPlatform : Physics.CollisionWall; bodies.Add(newBody); WallList.Add(this); CreateSections(); } else { sections = new WallSection[1]; sections[0] = new WallSection(rect); if (StairDirection != Direction.None) { CreateStairBodies(); } } #if CLIENT if (prefab.CastShadow) { GenerateConvexHull(); } #endif InsertToList(); }
private LevelGenerationParams(XElement element) { Name = element == null ? "default" : element.Name.ToString(); SerializableProperties = SerializableProperty.DeserializeProperties(this, element); string biomeStr = element.GetAttributeString("biomes", ""); if (string.IsNullOrWhiteSpace(biomeStr)) { allowedBiomes = new List <Biome>(biomes); } else { string[] biomeNames = biomeStr.Split(','); for (int i = 0; i < biomeNames.Length; i++) { string biomeName = biomeNames[i].Trim().ToLowerInvariant(); if (biomeName == "none") { continue; } Biome matchingBiome = biomes.Find(b => b.Name.ToLowerInvariant() == biomeName); if (matchingBiome == null) { DebugConsole.ThrowError("Error in level generation parameters: biome \"" + biomeName + "\" not found."); continue; } allowedBiomes.Add(matchingBiome); } } foreach (XElement subElement in element.Elements()) { switch (subElement.Name.ToString().ToLowerInvariant()) { case "background": BackgroundSprite = new Sprite(subElement); break; case "backgroundtop": BackgroundTopSprite = new Sprite(subElement); break; case "wall": WallSprite = new Sprite(subElement); break; case "wallspecular": WallSpriteSpecular = new Sprite(subElement); break; case "walledge": WallEdgeSprite = new Sprite(subElement); break; case "walledgespecular": WallEdgeSpriteSpecular = new Sprite(subElement); break; case "waterparticles": WaterParticles = new Sprite(subElement); break; } } }
public Structure(Rectangle rectangle, StructurePrefab sp, Submarine submarine) : base(sp, submarine) { if (rectangle.Width == 0 || rectangle.Height == 0) { return; } System.Diagnostics.Debug.Assert(rectangle.Width > 0 && rectangle.Height > 0); rect = rectangle; #if CLIENT TextureScale = sp.TextureScale; #endif spriteColor = prefab.SpriteColor; if (ResizeHorizontal && !ResizeVertical) { IsHorizontal = true; } else if (ResizeVertical && !ResizeHorizontal) { IsHorizontal = false; } else { if (BodyWidth > 0.0f && BodyHeight > 0.0f) { IsHorizontal = BodyWidth > BodyHeight; } else { IsHorizontal = (rect.Width > rect.Height); } } StairDirection = Prefab.StairDirection; SerializableProperties = SerializableProperty.GetProperties(this); InitProjSpecific(); if (Prefab.Body) { Bodies = new List <Body>(); WallList.Add(this); CreateSections(); UpdateSections(); } else { Sections = new WallSection[1]; Sections[0] = new WallSection(rect); if (StairDirection != Direction.None) { CreateStairBodies(); } } // Only add ai targets automatically to walls if (aiTarget == null && HasBody && Tags.Contains("wall")) { aiTarget = new AITarget(this); } InsertToList(); }
public void Deserialize(XElement element) { SerializableProperties = SerializableProperty.DeserializeProperties(this, element); ReloadAfflictions(element); }
public virtual void Reset() { SerializableProperties = SerializableProperty.DeserializeProperties(this, Prefab.ConfigElement); }
private GUIComponent CreateEditingHUD(bool inGame = false) { int width = 450; int height = 150; int x = GameMain.GraphicsWidth / 2 - width / 2, y = 30; editingHUD = new GUIListBox(new Rectangle(x, y, width, height), ""); editingHUD.UserData = this; GUIListBox listBox = (GUIListBox)editingHUD; listBox.Spacing = 5; var itemEditor = new SerializableEntityEditor(this, inGame, editingHUD, true); if (!inGame && Linkable) { itemEditor.AddCustomContent(new GUITextBlock(new Rectangle(0, 0, 0, 20), "Hold space to link to another item", "", null, GUI.SmallFont), 1); } foreach (ItemComponent ic in components) { if (ic.requiredItems.Count == 0) { if (inGame) { if (SerializableProperty.GetProperties <InGameEditable>(ic).Count == 0) { continue; } } else { if (SerializableProperty.GetProperties <Editable>(ic).Count == 0) { continue; } } } var componentEditor = new SerializableEntityEditor(ic, inGame, editingHUD, !inGame); if (inGame) { continue; } foreach (RelatedItem relatedItem in ic.requiredItems) { var textBlock = new GUITextBlock(new Rectangle(0, 0, 0, 20), relatedItem.Type.ToString() + " required", "", Alignment.TopLeft, Alignment.CenterLeft, null, false, GUI.SmallFont); textBlock.Padding = new Vector4(10.0f, 0.0f, 10.0f, 0.0f); componentEditor.AddCustomContent(textBlock, 1); GUITextBox namesBox = new GUITextBox(new Rectangle(0, 0, 180, 20), Alignment.Right, "", textBlock); namesBox.Font = GUI.SmallFont; namesBox.Text = relatedItem.JoinedNames; namesBox.OnDeselected += (textBox, key) => { relatedItem.JoinedNames = textBox.Text; textBox.Text = relatedItem.JoinedNames; }; namesBox.OnEnterPressed += (textBox, text) => { relatedItem.JoinedNames = text; textBox.Text = relatedItem.JoinedNames; return(true); }; y += 20; } } int contentHeight = (int)(editingHUD.children.Sum(c => c.Rect.Height) + (listBox.children.Count - 1) * listBox.Spacing + listBox.Padding.Y + listBox.Padding.W); editingHUD.SetDimensions(new Point(editingHUD.Rect.Width, MathHelper.Clamp(contentHeight, 50, editingHUD.Rect.Height))); return(editingHUD); }
public TriggerEvent(XElement element) { SerializableProperty.DeserializeProperties(this, element); }
public void UpdateValue(SerializableProperty property, object newValue, bool flash = true) { if (!Fields.TryGetValue(property.Name, out GUIComponent[] fields))
public void Save(XElement element) { this.Config = element; SerializableProperty.SerializeProperties(this, element); foreach (XElement subElement in element.Elements().ToList()) { switch (subElement.Name.ToString().ToLowerInvariant()) { case "childobject": subElement.Remove(); break; case "deformablesprite": subElement.RemoveNodes(); foreach (SpriteDeformation deformation in SpriteDeformations) { var deformationElement = new XElement("SpriteDeformation"); deformation.Save(deformationElement); subElement.Add(deformationElement); } break; } } for (int i = 0; i < LightSourceParams.Count; i++) { int elementIndex = 0; bool wasSaved = false; foreach (XElement subElement in element.Elements().ToList()) { switch (subElement.Name.ToString().ToLowerInvariant()) { case "lightsource": if (elementIndex == i) { SerializableProperty.SerializeProperties(LightSourceParams[i], subElement); wasSaved = true; break; } elementIndex++; break; } } if (!wasSaved) { var lightElement = new XElement("LightSource"); SerializableProperty.SerializeProperties(LightSourceParams[i], lightElement); element.Add(lightElement); } } foreach (ChildObject childObj in ChildObjects) { element.Add(new XElement("ChildObject", new XAttribute("names", string.Join(", ", childObj.AllowedNames)), new XAttribute("mincount", childObj.MinCount), new XAttribute("maxcount", childObj.MaxCount))); } foreach (KeyValuePair <string, float> overrideCommonness in OverrideCommonness) { bool elementFound = false; foreach (XElement subElement in element.Elements()) { if (subElement.Name.ToString().Equals("overridecommonness", System.StringComparison.OrdinalIgnoreCase) && subElement.GetAttributeString("leveltype", "").Equals(overrideCommonness.Key, System.StringComparison.OrdinalIgnoreCase)) { subElement.Attribute("commonness").Value = overrideCommonness.Value.ToString("G", CultureInfo.InvariantCulture); elementFound = true; break; } } if (!elementFound) { element.Add(new XElement("overridecommonness", new XAttribute("leveltype", overrideCommonness.Key), new XAttribute("commonness", overrideCommonness.Value.ToString("G", CultureInfo.InvariantCulture)))); } } }
protected virtual bool Deserialize(XElement element = null) { element = element ?? MainElement; SerializableProperties = SerializableProperty.DeserializeProperties(this, element); return(SerializableProperties != null); }
private bool Matches(SerializableProperty property) { object propertyValue = property.GetValue(); if (propertyValue == null) { DebugConsole.ThrowError("Couldn't compare " + Value.ToString() + " (" + Value.GetType() + ") to property \"" + property.Name + "\" - property.GetValue() returns null!"); return(false); } Type type = propertyValue.GetType(); float?floatValue = null; float?floatProperty = null; if (type == typeof(float) || type == typeof(int)) { float parsedFloat; if (Single.TryParse(Value, NumberStyles.Float, CultureInfo.InvariantCulture, out parsedFloat)) { floatValue = parsedFloat; } floatProperty = (float)propertyValue; } switch (Operator) { case OperatorType.Equals: if (floatValue == null) { return(property.GetValue().Equals(floatValue)); } else { return(property.GetValue().Equals(Value)); } case OperatorType.NotEquals: if (floatValue == null) { return(!property.GetValue().Equals(floatValue)); } else { return(!property.GetValue().Equals(Value)); } case OperatorType.GreaterThan: if (floatValue == null) { DebugConsole.ThrowError("Couldn't compare " + Value.ToString() + " (" + Value.GetType() + ") to property \"" + property.Name + "\" (" + type + ")! " + "Make sure the type of the value set in the config files matches the type of the property."); } else if (floatProperty > floatValue) { return(true); } break; case OperatorType.LessThan: if (floatValue == null) { DebugConsole.ThrowError("Couldn't compare " + Value.ToString() + " (" + Value.GetType() + ") to property \"" + property.Name + "\" (" + type + ")! " + "Make sure the type of the value set in the config files matches the type of the property."); } else if (floatProperty < floatValue) { return(true); } break; case OperatorType.GreaterThanEquals: if (floatValue == null) { DebugConsole.ThrowError("Couldn't compare " + Value.ToString() + " (" + Value.GetType() + ") to property \"" + property.Name + "\" (" + type + ")! " + "Make sure the type of the value set in the config files matches the type of the property."); } else if (floatProperty >= floatValue) { return(true); } break; case OperatorType.LessThanEquals: if (floatValue == null) { DebugConsole.ThrowError("Couldn't compare " + Value.ToString() + " (" + Value.GetType() + ") to property \"" + property.Name + "\" (" + type + ")! " + "Make sure the type of the value set in the config files matches the type of the property."); } else if (floatProperty <= floatValue) { return(true); } break; } return(false); }
public JobPrefab(XElement element, string filePath) { FilePath = filePath; SerializableProperty.DeserializeProperties(this, element); Name = TextManager.Get("JobName." + Identifier); Description = TextManager.Get("JobDescription." + Identifier); Identifier = Identifier.ToLowerInvariant(); Element = element; int variant = 0; foreach (XElement subElement in element.Elements()) { switch (subElement.Name.ToString().ToLowerInvariant()) { case "itemset": ItemSets.Add(variant, subElement); ItemIdentifiers[variant] = new List <string>(); ShowItemPreview[variant] = new Dictionary <string, bool>(); loadItemIdentifiers(subElement, variant); variant++; break; case "skills": foreach (XElement skillElement in subElement.Elements()) { Skills.Add(new SkillPrefab(skillElement)); } break; case "autonomousobjectives": subElement.Elements().ForEach(order => AutonomousObjectives.Add(new AutonomousObjective(order))); break; case "appropriateobjectives": case "appropriateorders": subElement.Elements().ForEach(order => AppropriateOrders.Add(order.GetAttributeString("identifier", "").ToLowerInvariant())); break; case "jobicon": Icon = new Sprite(subElement.FirstElement()); break; case "jobiconsmall": IconSmall = new Sprite(subElement.FirstElement()); break; } } void loadItemIdentifiers(XElement parentElement, int variant) { foreach (XElement itemElement in parentElement.GetChildElements("Item")) { if (itemElement.Element("name") != null) { DebugConsole.ThrowError("Error in job config \"" + Name + "\" - use identifiers instead of names to configure the items."); continue; } string itemIdentifier = itemElement.GetAttributeString("identifier", ""); if (string.IsNullOrWhiteSpace(itemIdentifier)) { DebugConsole.ThrowError("Error in job config \"" + Name + "\" - item with no identifier."); } else { ItemIdentifiers[variant].Add(itemIdentifier); ShowItemPreview[variant][itemIdentifier] = itemElement.GetAttributeBool("showpreview", true); } loadItemIdentifiers(itemElement, variant); } } Variants = variant; Skills.Sort((x, y) => y.LevelRange.X.CompareTo(x.LevelRange.X)); ClothingElement = element.GetChildElement("PortraitClothing"); }
public ItemPrefab(XElement element, string filePath, bool allowOverriding) { configFile = filePath; ConfigElement = element; OriginalName = element.GetAttributeString("name", ""); identifier = element.GetAttributeString("identifier", ""); //nameidentifier can be used to make multiple items use the same names and descriptions string nameIdentifier = element.GetAttributeString("nameidentifier", ""); if (string.IsNullOrEmpty(nameIdentifier)) { name = TextManager.Get("EntityName." + identifier, true) ?? OriginalName; } else { name = TextManager.Get("EntityName." + nameIdentifier, true) ?? OriginalName; } if (name == "") { DebugConsole.ThrowError("Unnamed item in " + filePath + "!"); } DebugConsole.Log(" " + name); Aliases = new HashSet <string> (element.GetAttributeStringArray("aliases", null, convertToLowerInvariant: true) ?? element.GetAttributeStringArray("Aliases", new string[0], convertToLowerInvariant: true)); Aliases.Add(OriginalName.ToLowerInvariant()); if (!Enum.TryParse(element.GetAttributeString("category", "Misc"), true, out MapEntityCategory category)) { category = MapEntityCategory.Misc; } Category = category; Triggers = new List <Rectangle>(); DeconstructItems = new List <DeconstructItem>(); FabricationRecipes = new List <FabricationRecipe>(); DeconstructTime = 1.0f; Tags = new HashSet <string>(element.GetAttributeStringArray("tags", new string[0], convertToLowerInvariant: true)); if (!Tags.Any()) { Tags = new HashSet <string>(element.GetAttributeStringArray("Tags", new string[0], convertToLowerInvariant: true)); } if (element.Attribute("cargocontainername") != null) { DebugConsole.ThrowError("Error in item prefab \"" + name + "\" - cargo container should be configured using the item's identifier, not the name."); } SerializableProperty.DeserializeProperties(this, element); string translatedDescription = ""; if (string.IsNullOrEmpty(nameIdentifier)) { translatedDescription = TextManager.Get("EntityDescription." + identifier, true); } else { translatedDescription = TextManager.Get("EntityDescription." + nameIdentifier, true); } if (!string.IsNullOrEmpty(translatedDescription)) { Description = translatedDescription; } foreach (XElement subElement in element.Elements()) { switch (subElement.Name.ToString().ToLowerInvariant()) { case "sprite": string spriteFolder = ""; if (!subElement.GetAttributeString("texture", "").Contains("/")) { spriteFolder = Path.GetDirectoryName(filePath); } canSpriteFlipX = subElement.GetAttributeBool("canflipx", true); canSpriteFlipY = subElement.GetAttributeBool("canflipy", true); sprite = new Sprite(subElement, spriteFolder, lazyLoad: true); if (subElement.Attribute("sourcerect") == null) { DebugConsole.ThrowError("Warning - sprite sourcerect not configured for item \"" + Name + "\"!"); } size = sprite.size; if (subElement.Attribute("name") == null && !string.IsNullOrWhiteSpace(Name)) { sprite.Name = Name; } sprite.EntityID = identifier; break; case "price": string locationType = subElement.GetAttributeString("locationtype", ""); if (prices == null) { prices = new Dictionary <string, PriceInfo>(); } prices[locationType.ToLowerInvariant()] = new PriceInfo(subElement); break; #if CLIENT case "inventoryicon": string iconFolder = ""; if (!subElement.GetAttributeString("texture", "").Contains("/")) { iconFolder = Path.GetDirectoryName(filePath); } InventoryIcon = new Sprite(subElement, iconFolder, lazyLoad: true); break; case "brokensprite": string brokenSpriteFolder = ""; if (!subElement.GetAttributeString("texture", "").Contains("/")) { brokenSpriteFolder = Path.GetDirectoryName(filePath); } var brokenSprite = new BrokenItemSprite( new Sprite(subElement, brokenSpriteFolder, lazyLoad: true), subElement.GetAttributeFloat("maxcondition", 0.0f), subElement.GetAttributeBool("fadein", false)); int spriteIndex = 0; for (int i = 0; i < BrokenSprites.Count && BrokenSprites[i].MaxCondition < brokenSprite.MaxCondition; i++) { spriteIndex = i; } BrokenSprites.Insert(spriteIndex, brokenSprite); break; case "decorativesprite": string decorativeSpriteFolder = ""; if (!subElement.GetAttributeString("texture", "").Contains("/")) { decorativeSpriteFolder = Path.GetDirectoryName(filePath); } int groupID = 0; DecorativeSprite decorativeSprite = null; if (subElement.Attribute("texture") == null) { groupID = subElement.GetAttributeInt("randomgroupid", 0); } else { decorativeSprite = new DecorativeSprite(subElement, decorativeSpriteFolder, lazyLoad: true); DecorativeSprites.Add(decorativeSprite); groupID = decorativeSprite.RandomGroupID; } if (!DecorativeSpriteGroups.ContainsKey(groupID)) { DecorativeSpriteGroups.Add(groupID, new List <DecorativeSprite>()); } DecorativeSpriteGroups[groupID].Add(decorativeSprite); break; case "containedsprite": string containedSpriteFolder = ""; if (!subElement.GetAttributeString("texture", "").Contains("/")) { containedSpriteFolder = Path.GetDirectoryName(filePath); } var containedSprite = new ContainedItemSprite(subElement, containedSpriteFolder, lazyLoad: true); if (containedSprite.Sprite != null) { ContainedSprites.Add(containedSprite); } break; #endif case "deconstruct": DeconstructTime = subElement.GetAttributeFloat("time", 1.0f); foreach (XElement deconstructItem in subElement.Elements()) { if (deconstructItem.Attribute("name") != null) { DebugConsole.ThrowError("Error in item config \"" + Name + "\" - use item identifiers instead of names to configure the deconstruct items."); continue; } DeconstructItems.Add(new DeconstructItem(deconstructItem)); } break; case "fabricate": case "fabricable": case "fabricableitem": fabricationRecipeElements.Add(subElement); break; case "trigger": Rectangle trigger = new Rectangle(0, 0, 10, 10) { X = subElement.GetAttributeInt("x", 0), Y = subElement.GetAttributeInt("y", 0), Width = subElement.GetAttributeInt("width", 0), Height = subElement.GetAttributeInt("height", 0) }; Triggers.Add(trigger); break; case "levelresource": foreach (XElement levelCommonnessElement in subElement.Elements()) { string levelName = levelCommonnessElement.GetAttributeString("levelname", "").ToLowerInvariant(); if (!LevelCommonness.ContainsKey(levelName)) { LevelCommonness.Add(levelName, levelCommonnessElement.GetAttributeFloat("commonness", 0.0f)); } } break; case "suitabletreatment": if (subElement.Attribute("name") != null) { DebugConsole.ThrowError("Error in item prefab \"" + Name + "\" - suitable treatments should be defined using item identifiers, not item names."); } string treatmentIdentifier = subElement.GetAttributeString("identifier", "").ToLowerInvariant(); List <AfflictionPrefab> matchingAfflictions = AfflictionPrefab.List.FindAll(a => a.Identifier == treatmentIdentifier || a.AfflictionType == treatmentIdentifier); if (matchingAfflictions.Count == 0) { DebugConsole.ThrowError("Error in item prefab \"" + Name + "\" - couldn't define as a treatment, no treatments with the identifier or type \"" + treatmentIdentifier + "\" were found."); continue; } float suitability = subElement.GetAttributeFloat("suitability", 0.0f); foreach (AfflictionPrefab matchingAffliction in matchingAfflictions) { if (matchingAffliction.TreatmentSuitability.ContainsKey(identifier)) { matchingAffliction.TreatmentSuitability[identifier] = Math.Max(matchingAffliction.TreatmentSuitability[identifier], suitability); } else { matchingAffliction.TreatmentSuitability.Add(identifier, suitability); } } break; } } if (sprite == null) { DebugConsole.ThrowError("Item \"" + Name + "\" has no sprite!"); #if SERVER sprite = new Sprite("", Vector2.Zero); sprite.SourceRect = new Rectangle(0, 0, 32, 32); #else sprite = new Sprite(TextureLoader.PlaceHolderTexture, null, null) { Origin = TextureLoader.PlaceHolderTexture.Bounds.Size.ToVector2() / 2 }; #endif size = sprite.size; sprite.EntityID = identifier; } if (!category.HasFlag(MapEntityCategory.Legacy) && string.IsNullOrEmpty(identifier)) { DebugConsole.ThrowError( "Item prefab \"" + name + "\" has no identifier. All item prefabs have a unique identifier string that's used to differentiate between items during saving and loading."); } AllowedLinks = element.GetAttributeStringArray("allowedlinks", new string[0], convertToLowerInvariant: true).ToList(); if (HandleExisting(identifier, allowOverriding, filePath)) { List.Add(this); } }
public ItemPrefab(XElement element, string filePath) { configFile = filePath; ConfigElement = element; name = element.GetAttributeString("name", ""); if (name == "") { DebugConsole.ThrowError("Unnamed item in " + filePath + "!"); } DebugConsole.Log(" " + name); string aliases = element.GetAttributeString("aliases", ""); if (!string.IsNullOrWhiteSpace(aliases)) { Aliases = aliases.Split(','); } MapEntityCategory category; if (!Enum.TryParse(element.GetAttributeString("category", "Misc"), true, out category)) { category = MapEntityCategory.Misc; } Category = category; Triggers = new List <Rectangle>(); DeconstructItems = new List <DeconstructItem>(); DeconstructTime = 1.0f; Tags = new List <string>(); Tags.AddRange(element.GetAttributeString("tags", "").Split(',')); SerializableProperty.DeserializeProperties(this, element); foreach (XElement subElement in element.Elements()) { switch (subElement.Name.ToString().ToLowerInvariant()) { case "sprite": string spriteFolder = ""; if (!subElement.GetAttributeString("texture", "").Contains("/")) { spriteFolder = Path.GetDirectoryName(filePath); } canSpriteFlipX = subElement.GetAttributeBool("canflipx", true); sprite = new Sprite(subElement, spriteFolder); if (subElement.Attribute("sourcerect") == null) { DebugConsole.ThrowError("Warning - sprite sourcerect not configured for item \"" + Name + "\"!"); } size = sprite.size; break; #if CLIENT case "brokensprite": string brokenSpriteFolder = ""; if (!subElement.GetAttributeString("texture", "").Contains("/")) { brokenSpriteFolder = Path.GetDirectoryName(filePath); } var brokenSprite = new BrokenItemSprite( new Sprite(subElement, brokenSpriteFolder), subElement.GetAttributeFloat("maxcondition", 0.0f), subElement.GetAttributeBool("fadein", false)); int spriteIndex = 0; for (int i = 0; i < BrokenSprites.Count && BrokenSprites[i].MaxCondition < brokenSprite.MaxCondition; i++) { spriteIndex = i; } BrokenSprites.Insert(spriteIndex, brokenSprite); break; #endif case "deconstruct": DeconstructTime = subElement.GetAttributeFloat("time", 10.0f); foreach (XElement deconstructItem in subElement.Elements()) { string deconstructItemName = deconstructItem.GetAttributeString("name", "not found"); //minCondition does <= check, meaning that below or equeal to min condition will be skipped. float minCondition = deconstructItem.GetAttributeFloat("mincondition", -0.1f); //maxCondition does > check, meaning that above this max the deconstruct item will be skipped. float maxCondition = deconstructItem.GetAttributeFloat("maxcondition", 1.0f); //Condition of item on creation float outCondition = deconstructItem.GetAttributeFloat("outcondition", 1.0f); DeconstructItems.Add(new DeconstructItem(deconstructItemName, minCondition, maxCondition, outCondition)); } break; case "trigger": Rectangle trigger = new Rectangle(0, 0, 10, 10); trigger.X = subElement.GetAttributeInt("x", 0); trigger.Y = subElement.GetAttributeInt("y", 0); trigger.Width = subElement.GetAttributeInt("width", 0); trigger.Height = subElement.GetAttributeInt("height", 0); Triggers.Add(trigger); break; } } List.Add(this); }
public ItemPrefab(XElement element, string filePath, bool allowOverriding) { FilePath = filePath; ConfigElement = element; originalName = element.GetAttributeString("name", ""); name = originalName; identifier = element.GetAttributeString("identifier", ""); if (!Enum.TryParse(element.GetAttributeString("category", "Misc"), true, out MapEntityCategory category)) { category = MapEntityCategory.Misc; } Category = category; var parentType = element.Parent?.GetAttributeString("itemtype", "") ?? string.Empty; //nameidentifier can be used to make multiple items use the same names and descriptions string nameIdentifier = element.GetAttributeString("nameidentifier", ""); //works the same as nameIdentifier, but just replaces the description string descriptionIdentifier = element.GetAttributeString("descriptionidentifier", ""); if (string.IsNullOrEmpty(originalName)) { if (string.IsNullOrEmpty(nameIdentifier)) { name = TextManager.Get("EntityName." + identifier, true) ?? string.Empty; } else { name = TextManager.Get("EntityName." + nameIdentifier, true) ?? string.Empty; } } else if (Category.HasFlag(MapEntityCategory.Legacy)) { // Legacy items use names as identifiers, so we have to define them in the xml. But we also want to support the translations. Therefore if (string.IsNullOrEmpty(nameIdentifier)) { name = TextManager.Get("EntityName." + identifier, true) ?? originalName; } else { name = TextManager.Get("EntityName." + nameIdentifier, true) ?? originalName; } if (string.IsNullOrWhiteSpace(identifier)) { identifier = GenerateLegacyIdentifier(originalName); } } if (string.Equals(parentType, "wrecked", StringComparison.OrdinalIgnoreCase)) { if (!string.IsNullOrEmpty(name)) { name = TextManager.GetWithVariable("wreckeditemformat", "[name]", name); } } if (string.IsNullOrEmpty(name)) { DebugConsole.ThrowError($"Unnamed item ({identifier})in {filePath}!"); } DebugConsole.Log(" " + name); Aliases = new HashSet <string> (element.GetAttributeStringArray("aliases", null, convertToLowerInvariant: true) ?? element.GetAttributeStringArray("Aliases", new string[0], convertToLowerInvariant: true)); Aliases.Add(originalName.ToLowerInvariant()); Triggers = new List <Rectangle>(); DeconstructItems = new List <DeconstructItem>(); FabricationRecipes = new List <FabricationRecipe>(); DeconstructTime = 1.0f; Tags = new HashSet <string>(element.GetAttributeStringArray("tags", new string[0], convertToLowerInvariant: true)); if (!Tags.Any()) { Tags = new HashSet <string>(element.GetAttributeStringArray("Tags", new string[0], convertToLowerInvariant: true)); } if (element.Attribute("cargocontainername") != null) { DebugConsole.ThrowError("Error in item prefab \"" + name + "\" - cargo container should be configured using the item's identifier, not the name."); } SerializableProperty.DeserializeProperties(this, element); if (string.IsNullOrEmpty(Description)) { if (!string.IsNullOrEmpty(descriptionIdentifier)) { Description = TextManager.Get("EntityDescription." + descriptionIdentifier, true) ?? string.Empty; } else if (string.IsNullOrEmpty(nameIdentifier)) { Description = TextManager.Get("EntityDescription." + identifier, true) ?? string.Empty; } else { Description = TextManager.Get("EntityDescription." + nameIdentifier, true) ?? string.Empty; } } foreach (XElement subElement in element.Elements()) { switch (subElement.Name.ToString().ToLowerInvariant()) { case "sprite": string spriteFolder = ""; if (!subElement.GetAttributeString("texture", "").Contains("/")) { spriteFolder = Path.GetDirectoryName(filePath); } CanSpriteFlipX = subElement.GetAttributeBool("canflipx", true); CanSpriteFlipY = subElement.GetAttributeBool("canflipy", true); sprite = new Sprite(subElement, spriteFolder, lazyLoad: true); if (subElement.Attribute("sourcerect") == null) { DebugConsole.ThrowError("Warning - sprite sourcerect not configured for item \"" + Name + "\"!"); } size = sprite.size; if (subElement.Attribute("name") == null && !string.IsNullOrWhiteSpace(Name)) { sprite.Name = Name; } sprite.EntityID = identifier; break; case "price": if (locationPrices == null) { locationPrices = new Dictionary <string, PriceInfo>(); } if (subElement.Attribute("baseprice") != null) { foreach (Tuple <string, PriceInfo> priceInfo in PriceInfo.CreatePriceInfos(subElement, out defaultPrice)) { if (priceInfo == null) { continue; } locationPrices.Add(priceInfo.Item1, priceInfo.Item2); } } else if (subElement.Attribute("buyprice") != null) { string locationType = subElement.GetAttributeString("locationtype", "").ToLowerInvariant(); locationPrices.Add(locationType, new PriceInfo(subElement)); } break; case "upgradeoverride": { #if CLIENT var sprites = new List <DecorativeSprite>(); foreach (XElement decorSprite in subElement.Elements()) { if (decorSprite.Name.ToString().Equals("decorativesprite", StringComparison.OrdinalIgnoreCase)) { sprites.Add(new DecorativeSprite(decorSprite)); } } UpgradeOverrideSprites.Add(subElement.GetAttributeString("identifier", ""), sprites); #endif break; } #if CLIENT case "inventoryicon": { string iconFolder = ""; if (!subElement.GetAttributeString("texture", "").Contains("/")) { iconFolder = Path.GetDirectoryName(filePath); } InventoryIcon = new Sprite(subElement, iconFolder, lazyLoad: true); } break; case "minimapicon": { string iconFolder = ""; if (!subElement.GetAttributeString("texture", "").Contains("/")) { iconFolder = Path.GetDirectoryName(filePath); } MinimapIcon = new Sprite(subElement, iconFolder, lazyLoad: true); } break; case "brokensprite": string brokenSpriteFolder = ""; if (!subElement.GetAttributeString("texture", "").Contains("/")) { brokenSpriteFolder = Path.GetDirectoryName(filePath); } var brokenSprite = new BrokenItemSprite( new Sprite(subElement, brokenSpriteFolder, lazyLoad: true), subElement.GetAttributeFloat("maxcondition", 0.0f), subElement.GetAttributeBool("fadein", false), subElement.GetAttributePoint("offset", Point.Zero)); int spriteIndex = 0; for (int i = 0; i < BrokenSprites.Count && BrokenSprites[i].MaxCondition < brokenSprite.MaxCondition; i++) { spriteIndex = i; } BrokenSprites.Insert(spriteIndex, brokenSprite); break; case "decorativesprite": string decorativeSpriteFolder = ""; if (!subElement.GetAttributeString("texture", "").Contains("/")) { decorativeSpriteFolder = Path.GetDirectoryName(filePath); } int groupID = 0; DecorativeSprite decorativeSprite = null; if (subElement.Attribute("texture") == null) { groupID = subElement.GetAttributeInt("randomgroupid", 0); } else { decorativeSprite = new DecorativeSprite(subElement, decorativeSpriteFolder, lazyLoad: true); DecorativeSprites.Add(decorativeSprite); groupID = decorativeSprite.RandomGroupID; } if (!DecorativeSpriteGroups.ContainsKey(groupID)) { DecorativeSpriteGroups.Add(groupID, new List <DecorativeSprite>()); } DecorativeSpriteGroups[groupID].Add(decorativeSprite); break; case "containedsprite": string containedSpriteFolder = ""; if (!subElement.GetAttributeString("texture", "").Contains("/")) { containedSpriteFolder = Path.GetDirectoryName(filePath); } var containedSprite = new ContainedItemSprite(subElement, containedSpriteFolder, lazyLoad: true); if (containedSprite.Sprite != null) { ContainedSprites.Add(containedSprite); } break; #endif case "deconstruct": DeconstructTime = subElement.GetAttributeFloat("time", 1.0f); AllowDeconstruct = true; foreach (XElement deconstructItem in subElement.Elements()) { if (deconstructItem.Attribute("name") != null) { DebugConsole.ThrowError("Error in item config \"" + Name + "\" - use item identifiers instead of names to configure the deconstruct items."); continue; } DeconstructItems.Add(new DeconstructItem(deconstructItem)); } break; case "fabricate": case "fabricable": case "fabricableitem": fabricationRecipeElements.Add(subElement); break; case "preferredcontainer": var preferredContainer = new PreferredContainer(subElement); if (preferredContainer.Primary.Count == 0 && preferredContainer.Secondary.Count == 0) { DebugConsole.ThrowError($"Error in item prefab {Name}: preferred container has no preferences defined ({subElement.ToString()})."); } else { PreferredContainers.Add(preferredContainer); } break; case "trigger": Rectangle trigger = new Rectangle(0, 0, 10, 10) { X = subElement.GetAttributeInt("x", 0), Y = subElement.GetAttributeInt("y", 0), Width = subElement.GetAttributeInt("width", 0), Height = subElement.GetAttributeInt("height", 0) }; Triggers.Add(trigger); break; case "levelresource": foreach (XElement levelCommonnessElement in subElement.Elements()) { string levelName = levelCommonnessElement.GetAttributeString("levelname", "").ToLowerInvariant(); if (!LevelCommonness.ContainsKey(levelName)) { LevelCommonness.Add(levelName, levelCommonnessElement.GetAttributeFloat("commonness", 0.0f)); } } break; case "suitabletreatment": if (subElement.Attribute("name") != null) { DebugConsole.ThrowError("Error in item prefab \"" + Name + "\" - suitable treatments should be defined using item identifiers, not item names."); } string treatmentIdentifier = subElement.GetAttributeString("identifier", "").ToLowerInvariant(); float suitability = subElement.GetAttributeFloat("suitability", 0.0f); treatmentSuitability.Add(treatmentIdentifier, suitability); break; } } // Set the default price in case the prices are defined in the old way // with separate Price elements and there is no default price explicitly set if (locationPrices != null && locationPrices.Any()) { defaultPrice ??= new PriceInfo(GetMinPrice() ?? 0, false); } if (sprite == null) { DebugConsole.ThrowError("Item \"" + Name + "\" has no sprite!"); #if SERVER sprite = new Sprite("", Vector2.Zero); sprite.SourceRect = new Rectangle(0, 0, 32, 32); #else sprite = new Sprite(TextureLoader.PlaceHolderTexture, null, null) { Origin = TextureLoader.PlaceHolderTexture.Bounds.Size.ToVector2() / 2 }; #endif size = sprite.size; sprite.EntityID = identifier; } if (string.IsNullOrEmpty(identifier)) { DebugConsole.ThrowError( "Item prefab \"" + name + "\" has no identifier. All item prefabs have a unique identifier string that's used to differentiate between items during saving and loading."); } AllowedLinks = element.GetAttributeStringArray("allowedlinks", new string[0], convertToLowerInvariant: true).ToList(); Prefabs.Add(this, allowOverriding); }
// TODO: refactor and add tests private bool Matches(ISerializableEntity target, SerializableProperty property) { object propertyValue = property.GetValue(target); if (propertyValue == null) { DebugConsole.ThrowError("Couldn't compare " + AttributeValue.ToString() + " (" + AttributeValue.GetType() + ") to property \"" + property.Name + "\" - property.GetValue() returns null!"); return(false); } Type type = propertyValue.GetType(); float?floatProperty = null; if (type == typeof(float) || type == typeof(int)) { floatProperty = (float)propertyValue; } switch (Operator) { case OperatorType.Equals: if (type == typeof(bool)) { return(((bool)propertyValue) == (AttributeValue == "true")); } else if (FloatValue == null) { return(propertyValue.ToString().Equals(AttributeValue)); } else { return(propertyValue.Equals(FloatValue)); } case OperatorType.NotEquals: if (type == typeof(bool)) { return(((bool)propertyValue) != (AttributeValue == "true")); } else if (FloatValue == null) { return(!propertyValue.ToString().Equals(AttributeValue)); } else { return(!propertyValue.Equals(FloatValue)); } case OperatorType.GreaterThan: if (FloatValue == null) { DebugConsole.ThrowError("Couldn't compare " + AttributeValue.ToString() + " (" + AttributeValue.GetType() + ") to property \"" + property.Name + "\" (" + type + ")! " + "Make sure the type of the value set in the config files matches the type of the property."); } else if (floatProperty > FloatValue) { return(true); } break; case OperatorType.LessThan: if (FloatValue == null) { DebugConsole.ThrowError("Couldn't compare " + AttributeValue.ToString() + " (" + AttributeValue.GetType() + ") to property \"" + property.Name + "\" (" + type + ")! " + "Make sure the type of the value set in the config files matches the type of the property."); } else if (floatProperty < FloatValue) { return(true); } break; case OperatorType.GreaterThanEquals: if (FloatValue == null) { DebugConsole.ThrowError("Couldn't compare " + AttributeValue.ToString() + " (" + AttributeValue.GetType() + ") to property \"" + property.Name + "\" (" + type + ")! " + "Make sure the type of the value set in the config files matches the type of the property."); } else if (floatProperty >= FloatValue) { return(true); } break; case OperatorType.LessThanEquals: if (FloatValue == null) { DebugConsole.ThrowError("Couldn't compare " + AttributeValue.ToString() + " (" + AttributeValue.GetType() + ") to property \"" + property.Name + "\" (" + type + ")! " + "Make sure the type of the value set in the config files matches the type of the property."); } else if (floatProperty <= FloatValue) { return(true); } break; } return(false); }
private MapGenerationParams(XElement element) { SerializableProperties = SerializableProperty.DeserializeProperties(this, element); GateCount = element.GetAttributeIntArray("gatecount", null) ?? element.GetAttributeIntArray("GateCount", null); if (GateCount == null) { GateCount = new int[DifficultyZones]; for (int i = 0; i < DifficultyZones; i++) { GateCount[i] = 1; } } foreach (XElement subElement in element.Elements()) { switch (subElement.Name.ToString().ToLowerInvariant()) { #if CLIENT case "connectionsprite": ConnectionSprite = new Sprite(subElement); break; case "passedconnectionsprite": PassedConnectionSprite = new Sprite(subElement); break; case "maptile": string biome = subElement.GetAttributeString("biome", ""); if (!mapTiles.ContainsKey(biome)) { mapTiles[biome] = new List <Sprite>(); } mapTiles[biome].Add(new Sprite(subElement)); break; case "fogofwarsprite": FogOfWarSprite = new Sprite(subElement); break; case "locationindicator": case "currentlocationindicator": CurrentLocationIndicator = new Sprite(subElement); break; case "selectedlocationindicator": SelectedLocationIndicator = new Sprite(subElement); break; case "decorativegraphsprite": DecorativeGraphSprite = new SpriteSheet(subElement); break; case "missionicon": MissionIcon = new Sprite(subElement); break; case "typechangeicon": TypeChangeIcon = new Sprite(subElement); break; #endif case "radiationparams": RadiationParams = new RadiationParams(subElement); break; } } }
public SubParam(XElement element, CharacterParams character) { Element = element; Character = character; SerializableProperties = SerializableProperty.DeserializeProperties(this, element); }
public HeadPreset(XElement element) { SerializableProperties = SerializableProperty.DeserializeProperties(this, element); }
private static StructurePrefab Load(XElement element, bool allowOverride, ContentFile file) { StructurePrefab sp = new StructurePrefab { originalName = element.GetAttributeString("name", ""), FilePath = file.Path, ContentPackage = file.ContentPackage }; sp.name = sp.originalName; sp.ConfigElement = element; sp.identifier = element.GetAttributeString("identifier", ""); var parentType = element.Parent?.GetAttributeString("prefabtype", "") ?? string.Empty; string nameIdentifier = element.GetAttributeString("nameidentifier", ""); string descriptionIdentifier = element.GetAttributeString("descriptionidentifier", ""); if (string.IsNullOrEmpty(sp.originalName)) { if (string.IsNullOrEmpty(nameIdentifier)) { sp.name = TextManager.Get("EntityName." + sp.identifier, true) ?? string.Empty; } else { sp.name = TextManager.Get("EntityName." + nameIdentifier, true) ?? string.Empty; } } if (string.IsNullOrEmpty(sp.name)) { sp.name = TextManager.Get("EntityName." + sp.identifier, returnNull: true) ?? $"Not defined ({sp.identifier})"; } sp.Tags = new HashSet <string>(); string joinedTags = element.GetAttributeString("tags", ""); if (string.IsNullOrEmpty(joinedTags)) { joinedTags = element.GetAttributeString("Tags", ""); } foreach (string tag in joinedTags.Split(',')) { sp.Tags.Add(tag.Trim().ToLowerInvariant()); } if (element.Attribute("ishorizontal") != null) { sp.IsHorizontal = element.GetAttributeBool("ishorizontal", false); } foreach (XElement subElement in element.Elements()) { switch (subElement.Name.ToString()) { case "sprite": sp.sprite = new Sprite(subElement, lazyLoad: true); if (subElement.Attribute("sourcerect") == null) { DebugConsole.ThrowError("Warning - sprite sourcerect not configured for structure \"" + sp.name + "\"!"); } #if CLIENT if (subElement.GetAttributeBool("fliphorizontal", false)) { sp.sprite.effects = SpriteEffects.FlipHorizontally; } if (subElement.GetAttributeBool("flipvertical", false)) { sp.sprite.effects = SpriteEffects.FlipVertically; } #endif sp.canSpriteFlipX = subElement.GetAttributeBool("canflipx", true); sp.canSpriteFlipY = subElement.GetAttributeBool("canflipy", true); if (subElement.Attribute("name") == null && !string.IsNullOrWhiteSpace(sp.Name)) { sp.sprite.Name = sp.Name; } sp.sprite.EntityID = sp.identifier; break; case "backgroundsprite": sp.BackgroundSprite = new Sprite(subElement, lazyLoad: true); if (subElement.Attribute("sourcerect") == null && sp.sprite != null) { sp.BackgroundSprite.SourceRect = sp.sprite.SourceRect; sp.BackgroundSprite.size = sp.sprite.size; sp.BackgroundSprite.size.X *= sp.sprite.SourceRect.Width; sp.BackgroundSprite.size.Y *= sp.sprite.SourceRect.Height; sp.BackgroundSprite.RelativeOrigin = subElement.GetAttributeVector2("origin", new Vector2(0.5f, 0.5f)); } #if CLIENT if (subElement.GetAttributeBool("fliphorizontal", false)) { sp.BackgroundSprite.effects = SpriteEffects.FlipHorizontally; } if (subElement.GetAttributeBool("flipvertical", false)) { sp.BackgroundSprite.effects = SpriteEffects.FlipVertically; } sp.BackgroundSpriteColor = subElement.GetAttributeColor("color", Color.White); #endif break; case "decorativesprite": #if CLIENT string decorativeSpriteFolder = ""; if (!subElement.GetAttributeString("texture", "").Contains("/")) { decorativeSpriteFolder = Path.GetDirectoryName(file.Path); } int groupID = 0; DecorativeSprite decorativeSprite = null; if (subElement.Attribute("texture") == null) { groupID = subElement.GetAttributeInt("randomgroupid", 0); } else { decorativeSprite = new DecorativeSprite(subElement, decorativeSpriteFolder, lazyLoad: true); sp.DecorativeSprites.Add(decorativeSprite); groupID = decorativeSprite.RandomGroupID; } if (!sp.DecorativeSpriteGroups.ContainsKey(groupID)) { sp.DecorativeSpriteGroups.Add(groupID, new List <DecorativeSprite>()); } sp.DecorativeSpriteGroups[groupID].Add(decorativeSprite); #endif break; } } if (string.Equals(parentType, "wrecked", StringComparison.OrdinalIgnoreCase)) { if (!string.IsNullOrEmpty(sp.Name)) { sp.name = TextManager.GetWithVariable("wreckeditemformat", "[name]", sp.name); } } string categoryStr = element.GetAttributeString("category", "Structure"); if (!Enum.TryParse(categoryStr, true, out MapEntityCategory category)) { category = MapEntityCategory.Structure; } sp.Category = category; if (category.HasFlag(MapEntityCategory.Legacy)) { if (string.IsNullOrWhiteSpace(sp.identifier)) { sp.identifier = "legacystructure_" + sp.name.ToLowerInvariant().Replace(" ", ""); } } sp.Aliases = (element.GetAttributeStringArray("aliases", null) ?? element.GetAttributeStringArray("Aliases", new string[0])).ToHashSet(); string nonTranslatedName = element.GetAttributeString("name", null) ?? element.Name.ToString(); sp.Aliases.Add(nonTranslatedName.ToLowerInvariant()); SerializableProperty.DeserializeProperties(sp, element); if (sp.Body) { sp.Tags.Add("wall"); } if (string.IsNullOrEmpty(sp.Description)) { if (!string.IsNullOrEmpty(descriptionIdentifier)) { sp.Description = TextManager.Get("EntityDescription." + descriptionIdentifier, returnNull: true) ?? string.Empty; } else if (string.IsNullOrEmpty(nameIdentifier)) { sp.Description = TextManager.Get("EntityDescription." + sp.identifier, returnNull: true) ?? string.Empty; } else { sp.Description = TextManager.Get("EntityDescription." + nameIdentifier, true) ?? string.Empty; } } //backwards compatibility if (element.Attribute("size") == null) { sp.size = Vector2.Zero; if (element.Attribute("width") == null && element.Attribute("height") == null) { sp.size.X = sp.sprite.SourceRect.Width; sp.size.Y = sp.sprite.SourceRect.Height; } else { sp.size.X = element.GetAttributeFloat("width", 0.0f); sp.size.Y = element.GetAttributeFloat("height", 0.0f); } } //backwards compatibility if (categoryStr.Equals("Thalamus", StringComparison.OrdinalIgnoreCase)) { sp.Category = MapEntityCategory.Wrecked; sp.Subcategory = "Thalamus"; } if (string.IsNullOrEmpty(sp.identifier)) { DebugConsole.ThrowError( "Structure prefab \"" + sp.name + "\" has no identifier. All structure prefabs have a unique identifier string that's used to differentiate between items during saving and loading."); } Prefabs.Add(sp, allowOverride); return(sp); }
private void SerializeAll() { XmlWriterSettings settings = new 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()) { if (subElement.Name.ToString().Equals(genParams.Name, StringComparison.OrdinalIgnoreCase)) { SerializableProperty.SerializeProperties(genParams, subElement, true); } } } else if (element.Name.ToString().Equals(genParams.Name, StringComparison.OrdinalIgnoreCase)) { 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(); }
private LevelGenerationParams(XElement element) { Identifier = element == null ? "default" : element.GetAttributeString("identifier", null) ?? element.Name.ToString(); SerializableProperties = SerializableProperty.DeserializeProperties(this, element); if (element == null) { return; } string biomeStr = element.GetAttributeString("biomes", ""); if (string.IsNullOrWhiteSpace(biomeStr) || biomeStr.Equals("any", StringComparison.OrdinalIgnoreCase)) { allowedBiomes = new List <Biome>(biomes); } else { string[] biomeNames = biomeStr.Split(','); for (int i = 0; i < biomeNames.Length; i++) { string biomeName = biomeNames[i].Trim().ToLowerInvariant(); if (biomeName == "none") { continue; } Biome matchingBiome = biomes.Find(b => b.Identifier.Equals(biomeName, StringComparison.OrdinalIgnoreCase)); if (matchingBiome == null) { matchingBiome = biomes.Find(b => b.DisplayName.Equals(biomeName, StringComparison.OrdinalIgnoreCase)); if (matchingBiome == null) { DebugConsole.ThrowError("Error in level generation parameters: biome \"" + biomeName + "\" not found."); continue; } else { DebugConsole.NewMessage("Please use biome identifiers instead of names in level generation parameter \"" + Identifier + "\".", Color.Orange); } } allowedBiomes.Add(matchingBiome); } } foreach (XElement subElement in element.Elements()) { switch (subElement.Name.ToString().ToLowerInvariant()) { case "background": BackgroundSprite = new Sprite(subElement); break; case "backgroundtop": BackgroundTopSprite = new Sprite(subElement); break; case "wall": WallSprite = new Sprite(subElement); break; case "wallspecular": WallSpriteSpecular = new Sprite(subElement); break; case "walledge": WallEdgeSprite = new Sprite(subElement); break; case "walledgespecular": WallEdgeSpriteSpecular = new Sprite(subElement); break; case "waterparticles": WaterParticles = new Sprite(subElement); 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(); }