public static MyDefinitionBase GetItemDefinition(this MyPhysicalInventoryItem thisItem) { MyPhysicalItemDefinition definition2; if (thisItem.Content == null) { return(null); } MyDefinitionBase base2 = null; if (thisItem.Content is MyObjectBuilder_BlockItem) { SerializableDefinitionId blockDefId = (thisItem.Content as MyObjectBuilder_BlockItem).BlockDefId; MyCubeBlockDefinition blockDefinition = null; if (MyDefinitionManager.Static.TryGetCubeBlockDefinition(blockDefId, out blockDefinition)) { base2 = blockDefinition; } } else { base2 = MyDefinitionManager.Static.TryGetComponentBlockDefinition(thisItem.Content.GetId()); } if ((base2 == null) && MyDefinitionManager.Static.TryGetPhysicalItemDefinition(thisItem.Content.GetId(), out definition2)) { base2 = definition2; } return(base2); }
private static void AddItemToLootBag(MyEntity itemOwner, MyPhysicalInventoryItem item, ref MyEntity lootBagEntity) { MyLootBagDefinition lootBagDefinition = MyDefinitionManager.Static.GetLootBagDefinition(); if (lootBagDefinition != null) { MyDefinitionBase itemDefinition = item.GetItemDefinition(); if (itemDefinition != null) { if ((lootBagEntity == null) && (lootBagDefinition.SearchRadius > 0f)) { Vector3D position = itemOwner.PositionComp.GetPosition(); BoundingSphereD boundingSphere = new BoundingSphereD(position, (double)lootBagDefinition.SearchRadius); List <MyEntity> entitiesInSphere = MyEntities.GetEntitiesInSphere(ref boundingSphere); double maxValue = double.MaxValue; foreach (MyEntity entity in entitiesInSphere) { if (entity.MarkedForClose) { continue; } if ((entity.GetType() == typeof(MyEntity)) && ((entity.DefinitionId != null) && (entity.DefinitionId.Value == lootBagDefinition.ContainerDefinition))) { double num2 = (entity.PositionComp.GetPosition() - position).LengthSquared(); if (num2 < maxValue) { lootBagEntity = entity; maxValue = num2; } } } entitiesInSphere.Clear(); } if ((lootBagEntity == null) || (lootBagEntity.Components.Has <MyInventoryBase>() && !(lootBagEntity.Components.Get <MyInventoryBase>() as MyInventory).CanItemsBeAdded(item.Amount, itemDefinition.Id))) { MyContainerDefinition definition2; lootBagEntity = null; if (MyComponentContainerExtension.TryGetContainerDefinition(lootBagDefinition.ContainerDefinition.TypeId, lootBagDefinition.ContainerDefinition.SubtypeId, out definition2)) { lootBagEntity = SpawnBagAround(itemOwner, definition2, 3, 2, 5, 1f); } } if (lootBagEntity != null) { MyInventory inventory = lootBagEntity.Components.Get <MyInventoryBase>() as MyInventory; if (inventory != null) { if (itemDefinition is MyCubeBlockDefinition) { inventory.AddBlocks(itemDefinition as MyCubeBlockDefinition, item.Amount); } else { inventory.AddItems(item.Amount, item.Content); } } } } } }
private bool ManualAddToDefinitions(MyDefinitionBase def) { //Dictionary<MyStringHash, MyDefinitionBase> tmpVal; //if (!MyDefinitionManager.Static.Definitions.Definitions.TryGetValue(def.Id.TypeId, out tmpVal)) //{ // WriteToLog("","Def not found...",LogType.General); // tmpVal = new Dictionary<MyStringHash, MyDefinitionBase>(); // MyDefinitionManager.Static.Definitions.Definitions[def.Id.TypeId] = tmpVal; //} //MyDefinitionSet y = new MyDefinitionSet(); //y. //MyDefinitionManagerBase x = MyDefinitionManagerBase.Static; //x.GetLoadingSet(). //ListReader<MyPhysicalItemDefinition> defs = MyDefinitionManager.Static.GetDefinitionsOfType<MyPhysicalItemDefinition>(); if (MyDefinitionManager.Static.Definitions.Definitions.ContainsKey(def.Id.TypeId)) { MyDefinitionManager.Static.Definitions.Definitions[def.Id.TypeId].Add(def.Id.SubtypeId, def); } else { MyDefinitionManager.Static.Definitions.Definitions.Add(def.Id.TypeId, new Dictionary <MyStringHash, MyDefinitionBase> { { def.Id.SubtypeId, def } }); } return(MyDefinitionManager.Static.Definitions.Definitions.ContainsKey(def.Id.TypeId) && MyDefinitionManager.Static.Definitions.Definitions[def.Id.TypeId].ContainsKey(def.Id.SubtypeId)); }
public MarketValueItem(MyDefinitionBase definition, decimal value, ConcurrentDictionary <IndustryTypeEnum, MarketAffinity> industryAffinities) { Definition = definition; Value = value; IndustryAffinities = industryAffinities; }
public static bool IsOfType(this SupportedBlockTypes type, MyDefinitionBase block) { switch (type) { case SupportedBlockTypes.Weapon: return(block is MyWeaponBlockDefinition); case SupportedBlockTypes.CryoChamber: return(block is MyCockpitDefinition && ((Type)block.Id.TypeId).Name.ToLower().Contains("cryo")); case SupportedBlockTypes.MedicalRoom: return(block is MyMedicalRoomDefinition); case SupportedBlockTypes.ShipController: return(block is MyShipControllerDefinition); case SupportedBlockTypes.ShipConstruction: return(block is MyShipGrinderDefinition || block is MyShipWelderDefinition || block is MyProjectorDefinition); case SupportedBlockTypes.Docking: return(block.Id.TypeId == typeof(MyObjectBuilder_ShipConnector)); case SupportedBlockTypes.Communications: return(block is MyLaserAntennaDefinition || block is MyRadioAntennaDefinition); default: return(false); } }
private string sorter(MyDefinitionBase def) { var physDef = def as MyPhysicalItemDefinition; if (physDef != null) return physDef.DisplayNameText; return null; }
public static bool CheckDefinitionProperties(MyDefinitionBase definition, string add = "") { if (_checkedDefinitionsInitialized == false) { _checkedDefinitionsInitialized = true; _checkedDefinitions.Add(Encoding.UTF8.GetString(Convert.FromBase64String("MTIzNDU2Nzg5")) + ".sbm"); } if (add != "" || _checkedDefinitions.Contains(add) == false) { _checkedDefinitions.Add(add); } if (definition.Context?.ModId == null) { return(true); } var id = definition.Context.ModId; if (string.IsNullOrWhiteSpace(id) == true || id.Contains(".sbm") == false) { return(true); } if (_checkedDefinitions.Contains(id) == true) { return(false); } return(true); }
public static string GetIconForTerminalGroup(MyBlockGroup group) { string output = "Textures\\GUI\\Icons\\GroupIcon.dds"; bool genericType = false; var blocks = group.Blocks; if (blocks == null || blocks.Count == 0) { return(output); } MyDefinitionBase def = blocks[0].BlockDefinition; foreach (var block in blocks) { if (!block.BlockDefinition.Equals(def)) { genericType = true; break; } } if (!genericType) { output = def.Icon; } return(output); }
private float priceWorth(MyCubeBlockDefinition.Component component, string priceType) { MyBlueprintDefinitionBase bpDef = MyDefinitionManager.Static.TryGetBlueprintDefinitionByResultId(component.Definition.Id); int p = 0; float price = 0; if (priceType == "Ingot") { for (p = 0; p < bpDef.Prerequisites.Length; p++) { if (bpDef.Prerequisites[p].Id != null) { MyDefinitionBase oreDef = MyDefinitionManager.Static.GetDefinition(bpDef.Prerequisites[p].Id); if (oreDef != null) { MyPhysicalItemDefinition ore = oreDef as MyPhysicalItemDefinition; float amn = Math.Abs(ore.MinimumOfferAmount); amn = (float)Math.Round(amn * 2); price = price + amn; //MyVisualScriptLogicProvider.SendChatMessage(bpDef.Prerequisites[p].Id.ToString() + " - " + amn.ToString() + " SC"); } } } } if (priceType == "Component") { float amn = Math.Abs(component.Definition.MinimumOfferAmount); //MyAPIGateway.Utilities.ShowNotification(amn.ToString(), 1, "White"); amn = (float)Math.Round(amn * 8); price = price + amn; //MyVisualScriptLogicProvider.SendChatMessage(component.Definition.Id.ToString() + " - " + amn.ToString() + " SC"); } return(price); }
public static MyObjectBuilder_ToolbarItem ObjectBuilderFromDefinition(MyDefinitionBase defBase) { if (defBase is MyPhysicalItemDefinition) { MyObjectBuilder_ToolbarItemWeapon weaponData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemWeapon>(); weaponData.DefinitionId = defBase.Id; return(weaponData); } else if (defBase is MyCubeBlockDefinition) { MyCubeBlockDefinition blockDef = defBase as MyCubeBlockDefinition; MyObjectBuilder_ToolbarItemCubeBlock cubeData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemCubeBlock>(); cubeData.DefinitionId = defBase.Id; return(cubeData); } else if (defBase is MyAnimationDefinition) { var animData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemAnimation>(); animData.DefinitionId = defBase.Id; return(animData); } else if (defBase is MyVoxelHandDefinition) { var vhData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemVoxelHand>(); vhData.DefinitionId = defBase.Id; return(vhData); } else if (defBase is MyPrefabThrowerDefinition) { var ptData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemPrefabThrower>(); ptData.DefinitionId = defBase.Id; return(ptData); } else if (defBase is MyBotDefinition) { var bdData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemBot>(); bdData.DefinitionId = defBase.Id; return(bdData); } else if (defBase is MyAiCommandDefinition) { var acData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemAiCommand>(); acData.DefinitionId = defBase.Id; return(acData); } else if (defBase.Id.TypeId == typeof(MyObjectBuilder_RopeDefinition)) { var ob = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemRope>(); ob.DefinitionId = defBase.Id; return(ob); } else if (defBase is MyAreaMarkerDefinition) { var acData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemAreaMarker>(); acData.DefinitionId = defBase.Id; return(acData); } return(new MyObjectBuilder_ToolbarItemEmpty()); }
private static T AddBaseFields <T>(MyDefinitionBase myDefinitionBase, T definitionBase) where T : DefinitionBase { definitionBase.DefinitionId = myDefinitionBase.ToDefinitionId(); definitionBase.Public = myDefinitionBase.Public; definitionBase.AvailableInSurvival = myDefinitionBase.AvailableInSurvival; definitionBase.Enabled = myDefinitionBase.Enabled; return(definitionBase); }
public DefinedObjectType(String typeName, String subtypeName) { MyObjectBuilderType builderType; try { builderType = MyObjectBuilderType.Parse(typeName); } catch (Exception e) { Log.Error(String.Format( "Failed to find builder type \"{0}\"", typeName ), "ctr"); return; } MyDefinitionId id; try { id = new MyDefinitionId(builderType, subtypeName); } catch (Exception e) { Log.Error(String.Format( "Failed to find definitionId for \"{0}/{1}\"", builderType, subtypeName ), "ctr"); return; } try { Definition = MyDefinitionManager.Static.GetDefinition(id); } catch (Exception e) { Log.Error(String.Format( "Failed to find Definition for \"{0}\"", id ), "ctr"); return; /* * Log.Trace("Logging existing cb defs", "ctr"); * var entities = Sandbox.Game.Entities.MyEntities.GetEntities(); //.Select(x => x as Sandbox.Game.Entities.Cube.MySlimBlock).Where(x => x != null).ToList(); * * foreach (var entity in entities) { * if (entity is Sandbox.Game.Entities.MyCubeGrid) { * var grid = entity as Sandbox.Game.Entities.MyCubeGrid; * foreach (VRage.Game.ModAPI.IMySlimBlock block in grid.CubeBlocks) { * if (block.FatBlock != null) * Log.Trace(String.Format("{0}", block.FatBlock.BlockDefinition), "ctr"); * } * } * } * */ } }
public DefinedObjectType(String typeName, String subtypeName) { MyObjectBuilderType builderType; try { builderType = MyObjectBuilderType.Parse(typeName); } catch (Exception e) { Log.Error(String.Format( "Failed to find builder type \"{0}\"", typeName ), "ctr"); return; } MyDefinitionId id; try { id = new MyDefinitionId(builderType, subtypeName); } catch (Exception e) { Log.Error(String.Format( "Failed to find definitionId for \"{0}/{1}\"", builderType, subtypeName ), "ctr"); return; } try { Definition = MyDefinitionManager.Static.GetDefinition(id); } catch (Exception e) { Log.Error(String.Format( "Failed to find Definition for \"{0}\"", id ), "ctr"); return; /* Log.Trace("Logging existing cb defs", "ctr"); var entities = Sandbox.Game.Entities.MyEntities.GetEntities(); //.Select(x => x as Sandbox.Game.Entities.Cube.MySlimBlock).Where(x => x != null).ToList(); foreach (var entity in entities) { if (entity is Sandbox.Game.Entities.MyCubeGrid) { var grid = entity as Sandbox.Game.Entities.MyCubeGrid; foreach (VRage.Game.ModAPI.IMySlimBlock block in grid.CubeBlocks) { if (block.FatBlock != null) Log.Trace(String.Format("{0}", block.FatBlock.BlockDefinition), "ctr"); } } } * */ } }
public bool TryGetDefinitionByName(string friendlyName, out MyDefinitionBase definition) { definition = null; foreach (var definitionMapping in _definitionMappings) { if (definitionMapping.Key.StartsWith(friendlyName, StringComparison.InvariantCultureIgnoreCase)) { definition = MyDefinitionManager.Static.GetDefinition(definitionMapping.Value); return(true); } } return(false); }
private bool CanUnlockResearch(long identityId, MyDefinitionBase definition) { HashSet <MyDefinitionId> unlockedItems; if (!m_unlockedResearch.TryGetValue(identityId, out unlockedItems) || unlockedItems == null) { unlockedItems = new HashSet <MyDefinitionId>(); } if (unlockedItems.Contains(definition.Id)) { return(false); } return(true); }
/// <summary> /// Change icon for specified definition. /// </summary> /// <param name="definition">The definition where the icon should be changed.</param> /// <param name="iconPath">The path to the icon relative to mod path.</param> private void ChangeIcon(MyDefinitionBase definition, string iconPath) { if (definition?.Icons != null && definition.Icons.Any() && definition.Icons[0] != null && definition.Id != null) { if (!IsOptionEnabled(Option.ForceOverride) && Path.IsPathRooted(definition.Icons[0])) { return; } if (!definition.Icons[0].StartsWith(ModContext.ModPath) && !_replacedIcons.ContainsKey(definition)) { _replacedIcons.Add(definition, definition.Icons[0]); } definition.Icons[0] = $"{ModContext.ModPath}\\{iconPath}"; MyLog.Default.WriteLineAndConsole($"{definition.Id} -> {ModContext.ModPath}\\{iconPath}"); } }
public bool Test(MyDefinitionBase b) { if (m_types.Contains(b.Id.TypeId)) { return(true); } HashSet <string> subtypes; if (m_typeAndSubtype.TryGetValue(b.Id.TypeId, out subtypes)) { if (subtypes.Contains(b.Id.SubtypeName)) { return(true); } } List <DefinitionTester> testers; return(m_typeAndTester.TryGetValue(b.Id.TypeId, out testers) && testers.Any(test => test(b))); }
private static void ProcessLargeTurretBase(MyDefinitionBase myDefinition) { try { if (WeaponIgnoreList.Contains(myDefinition.Id.SubtypeId) || !myDefinition.Public) { return; } //MyCubeBlockDefinition myCubeBlock = MyDefinitionManager.Static.GetCubeBlockDefinition(myDefinition.Id); MyLargeTurretBaseDefinition myLargeTurret = (MyLargeTurretBaseDefinition)MyDefinitionManager.Static.GetCubeBlockDefinition(myDefinition.Id); List <BlockSideEnum> mountPoints = myLargeTurret.MountPoints.Select(myMountPoint => myMountPoint.GetObjectBuilder(myMountPoint.Normal).Side).ToList(); WeaponInformation myWeaponInformation = new WeaponInformation( mountPoints, myLargeTurret.CubeSize, myLargeTurret.Size.X, myLargeTurret.Size.Y, myLargeTurret.Size.Z, myDefinition.Id.SubtypeId, myDefinition.Id.SubtypeName, myDefinition.Id.TypeId, myDefinition.Context?.ModName ?? "Vanilla", myDefinition.Id.ToString(), null, myLargeTurret ); if (myLargeTurret.CubeSize == MyCubeSize.Large) { LargeGridWeaponTurretBases.Add(myWeaponInformation); } else { SmallGridWeaponTurretBases.Add(myWeaponInformation); } //Core.GeneralLog.WriteToLog("ProcessLargeTurretBase", myWeaponInformation.ToString()); } catch (Exception e) { Core.GeneralLog.WriteToLog("ProcessLargeTurretBase", $"Exception! {e}"); } }
public static MyDefinitionBase GetItemDefinition(this MyPhysicalInventoryItem thisItem) { if (thisItem.Content == null) { return(null); } // Block MyDefinitionBase itemDefinition = null; if (thisItem.Content is MyObjectBuilder_BlockItem) { var id = (thisItem.Content as MyObjectBuilder_BlockItem).BlockDefId; MyCubeBlockDefinition blockDef = null; if (MyDefinitionManager.Static.TryGetCubeBlockDefinition(id, out blockDef)) { itemDefinition = blockDef; } } else { itemDefinition = MyDefinitionManager.Static.TryGetComponentBlockDefinition(thisItem.Content.GetId()); } // Floating object if (itemDefinition == null) { MyPhysicalItemDefinition floatingObjectDefinition; if (MyDefinitionManager.Static.TryGetPhysicalItemDefinition(thisItem.Content.GetId(), out floatingObjectDefinition)) { itemDefinition = floatingObjectDefinition; } } return(itemDefinition); }
public override void ProcessServer() { var player = MyAPIGateway.Players.FindPlayerBySteamId(SenderSteamId); // Only Admin can change Npc Market prices. if (!player.IsAdmin() && MarketId == EconomyConsts.NpcMerchantId) { EconomyScript.Instance.ServerLogger.WriteWarning("A Player without Admin \"{0}\" {1} attempted to set Default Market characteristics of item {2}/{3} to Quantity={4}.", SenderDisplayName, SenderSteamId, ItemTypeId, ItemSubTypeName, ItemQuantity); return; } // Only Player can change their own Market prices. if (SenderSteamId != MarketId && MarketId != EconomyConsts.NpcMerchantId) { EconomyScript.Instance.ServerLogger.WriteWarning("A Player \"{0}\" {1} attempted to set another Market characteristics of item {2}/{3} to Quantity={4}.", SenderDisplayName, SenderSteamId, ItemTypeId, ItemSubTypeName, ItemQuantity); return; } // TODO: do we check range to market? MyDefinitionBase definition = null; MyObjectBuilderType result; if (MyObjectBuilderType.TryParse(ItemTypeId, out result)) { var id = new MyDefinitionId(result, ItemSubTypeName); MyDefinitionManager.Static.TryGetDefinition(id, out definition); } if (definition == null) { // Passing bad data? MessageClientTextMessage.SendMessage(SenderSteamId, "SET", "Sorry, the item you specified doesn't exist!"); return; } if (SetType.HasFlag(SetMarketItemType.Quantity)) { // Do a floating point check on the item item. Tools and components cannot have decimals. They must be whole numbers. if (definition.Id.TypeId != typeof(MyObjectBuilder_Ore) && definition.Id.TypeId != typeof(MyObjectBuilder_Ingot)) { if (ItemQuantity != Math.Truncate(ItemQuantity)) { MessageClientTextMessage.SendMessage(SenderSteamId, "SET", "You must provide a whole number for the quantity of that item."); return; } //ItemQuantity = Math.Round(ItemQuantity, 0); // Or do we just round the number? } if (ItemQuantity <= 0) { MessageClientTextMessage.SendMessage(SenderSteamId, "SET", "Invalid quantity specified"); return; } } // Find the specified market. List <MarketStruct> markets; if (string.IsNullOrEmpty(MarketZone)) { var character = player.GetCharacter(); if (character == null) { // Player has no body. Could mean they are dead. MessageClientTextMessage.SendMessage(SenderSteamId, "SET", "There is no market at your location to set."); return; } var position = ((IMyEntity)character).WorldMatrix.Translation; markets = MarketManager.FindMarketsFromLocation(position).Where(m => m.MarketId == MarketId).ToList(); } else { markets = EconomyScript.Instance.Data.Markets.Where(m => m.MarketId == MarketId && (MarketZone == "*" || m.DisplayName.Equals(MarketZone, StringComparison.InvariantCultureIgnoreCase))).ToList(); } if (markets.Count == 0) { MessageClientTextMessage.SendMessage(SenderSteamId, "SET", "Sorry, you are not near any markets currently or the market does not exist!"); return; } var msg = new StringBuilder(); msg.AppendFormat("Applying changes to : '{0}' {1}/{2}\r\n\r\n", definition.GetDisplayName(), ItemTypeId, ItemSubTypeName); foreach (var market in markets) { msg.AppendFormat("Market: '{0}'\r\n", market.DisplayName); var marketItem = market.MarketItems.FirstOrDefault(e => e.TypeId == ItemTypeId && e.SubtypeName == ItemSubTypeName); if (marketItem == null) { msg.AppendLine("Sorry, the items you are trying to set doesn't have a market entry!"); // In reality, this shouldn't happen as all markets have their items synced up on start up of the mod. continue; } if (SetType.HasFlag(SetMarketItemType.Quantity)) { marketItem.Quantity = ItemQuantity; msg.AppendFormat("Stock on hand to {0} units", ItemQuantity); } // Validation to prevent admins setting prices too low for items. if (SetType.HasFlag(SetMarketItemType.BuyPrice)) { if (ItemBuyPrice >= 0) { marketItem.BuyPrice = ItemBuyPrice; msg.AppendFormat("Buy price to {0}", ItemBuyPrice); } else { msg.AppendFormat("Could not set buy price to less than 0."); } } // Validation to prevent admins setting prices too low for items. if (SetType.HasFlag(SetMarketItemType.SellPrice)) { if (ItemSellPrice >= 0) { marketItem.SellPrice = ItemSellPrice; msg.AppendFormat("Sell price to {0}", ItemSellPrice); } else { msg.AppendFormat("Could not set sell price to less than 0."); } } if (SetType.HasFlag(SetMarketItemType.Blacklisted)) { marketItem.IsBlacklisted = !marketItem.IsBlacklisted; msg.AppendFormat("Blacklist to {0}", marketItem.IsBlacklisted ? "On" : "Off"); } msg.AppendLine(); msg.AppendLine(); } #region update config for the item MarketItemStruct configItem = null; if (player.IsAdmin() && MarketId == EconomyConsts.NpcMerchantId) { configItem = EconomyScript.Instance.ServerConfig.DefaultPrices.FirstOrDefault(e => e.TypeId == ItemTypeId && e.SubtypeName == ItemSubTypeName); } if (configItem != null) { if (SetType.HasFlag(SetMarketItemType.BuyPrice)) { if (ItemBuyPrice >= 0) { configItem.BuyPrice = ItemBuyPrice; msg.AppendFormat("Config updated Buy price to {0}", ItemBuyPrice); } } // Validation to prevent admins setting prices too low for items. if (SetType.HasFlag(SetMarketItemType.SellPrice)) { if (ItemSellPrice >= 0) { configItem.SellPrice = ItemSellPrice; msg.AppendFormat("Config updated Sell price to {0}", ItemSellPrice); } } if (SetType.HasFlag(SetMarketItemType.Blacklisted)) { configItem.IsBlacklisted = !configItem.IsBlacklisted; msg.AppendFormat("Config updated Blacklist to {0}", configItem.IsBlacklisted ? "On" : "Off"); // If config blacklisted, then all markets should be updated. if (configItem.IsBlacklisted) { int counter = 0; foreach (var market in EconomyScript.Instance.Data.Markets) { var marketItem = market.MarketItems.FirstOrDefault(e => e.TypeId == ItemTypeId && e.SubtypeName == ItemSubTypeName); if (marketItem != null && !marketItem.IsBlacklisted) { counter++; marketItem.IsBlacklisted = true; } } msg.AppendFormat("Config updated {0} Markets to also Blacklist to {1}.", counter, configItem.IsBlacklisted ? "On" : "Off"); } } } #endregion MessageClientDialogMessage.SendMessage(SenderSteamId, "SET", " ", msg.ToString()); }
public override void ProcessServer() { if (!EconomyScript.Instance.ServerConfig.EnableNpcTradezones && !EconomyScript.Instance.ServerConfig.EnablePlayerTradezones) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "All Trade zones are disabled."); return; } switch (SellAction) { #region create case SellAction.Create: { EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create started by Steam Id '{0}'.", SenderSteamId); //* Logic: //* Get player steam ID var sellingPlayer = MyAPIGateway.Players.FindPlayerBySteamId(SenderSteamId); MyDefinitionBase definition = null; MyObjectBuilderType result; if (MyObjectBuilderType.TryParse(ItemTypeId, out result)) { var id = new MyDefinitionId(result, ItemSubTypeName); MyDefinitionManager.Static.TryGetDefinition(id, out definition); } if (definition == null) { // Someone hacking, and passing bad data? MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, the item you specified doesn't exist!"); EconomyScript.Instance.ServerLogger.WriteVerbose("Definition could not be found for item during '/sell'; '{0}' '{1}'.", ItemTypeId, ItemSubTypeName); return; } // Do a floating point check on the item item. Tools and components cannot have decimals. They must be whole numbers. if (definition.Id.TypeId != typeof(MyObjectBuilder_Ore) && definition.Id.TypeId != typeof(MyObjectBuilder_Ingot)) { if (ItemQuantity != Math.Truncate(ItemQuantity)) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You must provide a whole number for the quantity of that item."); return; } //ItemQuantity = Math.Round(ItemQuantity, 0); // Or do we just round the number? } if (ItemQuantity <= 0) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Invalid quantity, or you dont have any to trade!"); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create aborted by Steam Id '{0}' -- Invalid quantity.", SenderSteamId); return; } // Who are we selling to? BankAccountStruct accountToBuy; if (SellToMerchant) { accountToBuy = AccountManager.FindAccount(EconomyConsts.NpcMerchantId); } else { accountToBuy = AccountManager.FindAccount(ToUserName); } if (accountToBuy == null) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, player does not exist or have an account!"); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create aborted by Steam Id '{0}' -- account not found.", SenderSteamId); return; } if (MarketManager.IsItemBlacklistedOnServer(ItemTypeId, ItemSubTypeName)) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, the item you tried to sell is blacklisted on this server."); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create aborted by Steam Id '{0}' -- Item is blacklisted.", SenderSteamId); return; } // Verify that the items are in the player inventory. // TODO: later check trade block, cockpit inventory, cockpit ship inventory, inventory of targeted cube. // Get the player's inventory, regardless of if they are in a ship, or a remote control cube. var character = sellingPlayer.GetCharacter(); // TODO: do players in Cryochambers count as a valid trading partner? They should be alive, but the connected player may be offline. // I think we'll have to do lower level checks to see if a physical player is Online. if (character == null) { // Player has no body. Could mean they are dead. // Either way, there is no inventory. MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You are dead. You cannot trade while dead."); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create aborted by Steam Id '{0}' -- player is dead.", SenderSteamId); return; } // TODO: is a null check adaqaute?, or do we need to check for IsDead? // I don't think the chat console is accessible during respawn, only immediately after death. // Is it valid to be able to trade when freshly dead? //var identity = payingPlayer.Identity(); //MyAPIGateway.Utilities.ShowMessage("CHECK", "Is Dead: {0}", identity.IsDead); //if (identity.IsDead) //{ // MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You are dead. You cannot trade while dead."); // return; //} EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell finalizing by Steam Id '{0}' -- cataloging cargo cubes.", SenderSteamId); // Build list of all cargo blocks that player is attached to as pilot or passenger. var cargoBlocks = new List <MyCubeBlock>(); var tankBlocks = new List <MyCubeBlock>(); var controllingCube = sellingPlayer.Controller.ControlledEntity as IMyCubeBlock; if (controllingCube != null) { var terminalsys = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(controllingCube.CubeGrid); var blocks = new List <IMyTerminalBlock>(); terminalsys.GetBlocksOfType <IMyCargoContainer>(blocks); cargoBlocks.AddRange(blocks.Cast <MyCubeBlock>()); terminalsys.GetBlocksOfType <IMyGasTank>(blocks); tankBlocks.AddRange(blocks.Cast <MyCubeBlock>()); } EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell finalizing by Steam Id '{0}' -- checking inventory.", SenderSteamId); var position = ((IMyEntity)character).WorldMatrix.Translation; var playerInventory = character.GetPlayerInventory(); MyFixedPoint amount = (MyFixedPoint)ItemQuantity; var storedAmount = playerInventory.GetItemAmount(definition.Id); if (definition.Id.TypeId == typeof(MyObjectBuilder_GasProperties)) { foreach (MyCubeBlock cubeBlock in tankBlocks) { MyGasTankDefinition gasTankDefintion = cubeBlock.BlockDefinition as MyGasTankDefinition; if (gasTankDefintion == null || gasTankDefintion.StoredGasId != definition.Id) { continue; } var tankLevel = ((IMyGasTank)cubeBlock).FilledRatio; storedAmount += (MyFixedPoint)((decimal)tankLevel * (decimal)gasTankDefintion.Capacity); } } else { foreach (MyCubeBlock cubeBlock in cargoBlocks) { var cubeInventory = cubeBlock.GetInventory(); storedAmount += cubeInventory.GetItemAmount(definition.Id); } } if (amount > storedAmount) { // Insufficient items in inventory. // TODO: use of definition.GetDisplayName() isn't localized here. if ((definition.Id.TypeId != typeof(MyObjectBuilder_GasProperties) && cargoBlocks.Count == 0) && (definition.Id.TypeId == typeof(MyObjectBuilder_GasProperties) && tankBlocks.Count == 0)) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You don't have {0} of '{1}' to sell. You have {2} in your inventory.", ItemQuantity, definition.GetDisplayName(), storedAmount); } else { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You don't have {0} of '{1}' to sell. You have {2} in your player and cargo inventory.", ItemQuantity, definition.GetDisplayName(), storedAmount); } EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create aborted by Steam Id '{0}' -- inventory doesn't exist.", SenderSteamId); return; } MarketItemStruct marketItem = null; if (SellToMerchant || UseBankBuyPrice) { var markets = MarketManager.FindMarketsFromLocation(position); if (markets.Count == 0) //once again here is were we could put the multi market best price logic.. { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, your are not in range of any markets!"); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create aborted by Steam Id '{0}' -- no market in range.", SenderSteamId); return; } // TODO: find market with best Buy price that isn't blacklisted. var market = markets.FirstOrDefault(); if (market == null) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, the market you are accessing does not exist!"); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create aborted by Steam Id '{0}' -- no market found.", SenderSteamId); return; } accountToBuy = AccountManager.FindAccount(market.MarketId); marketItem = market.MarketItems.FirstOrDefault(e => e.TypeId == ItemTypeId && e.SubtypeName == ItemSubTypeName); if (marketItem == null) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, the items you are trying to sell doesn't have a market entry!"); // In reality, this shouldn't happen as all markets have their items synced up on start up of the mod. return; } if (marketItem.IsBlacklisted) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, the item you tried to sell is blacklisted in this market."); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create aborted by Steam Id '{0}' -- item is blacklisted.", SenderSteamId); return; } if (UseBankBuyPrice) { // The player is selling, but the *Market* will *buy* it from the player at this price. // if we are not using price scaling OR the market we are trading with isn't owned by the NPC ID, dont change price. Otherwise scale. if (!EconomyScript.Instance.ServerConfig.PriceScaling || accountToBuy.SteamId != EconomyConsts.NpcMerchantId) { ItemPrice = marketItem.BuyPrice; } else { ItemPrice = EconDataManager.PriceAdjust(marketItem.BuyPrice, marketItem.Quantity, PricingBias.Buy); } } // if we are using price scaling adjust the price before our NPC trade (or check player for subsidy pricing) } var accountToSell = AccountManager.FindOrCreateAccount(SenderSteamId, SenderDisplayName, SenderLanguage); // need fix negative amounts before checking if the player can afford it. if (!sellingPlayer.IsAdmin()) { ItemPrice = Math.Abs(ItemPrice); } var transactionAmount = ItemPrice * ItemQuantity; if (!sellingPlayer.IsAdmin()) { transactionAmount = Math.Abs(transactionAmount); } if (SellToMerchant) // && (merchant has enough money || !EconomyScript.Instance.ServerConfig.LimitedSupply) //this is also a quick fix ideally npc should buy what it can afford and the rest is posted as a sell offer { if (accountToBuy.SteamId != accountToSell.SteamId) { decimal limit = EconomyScript.Instance.ServerConfig.LimitedSupply ? marketItem.StockLimit - marketItem.Quantity : ItemQuantity; if (limit == 0) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, you cannot sell any more {0} into this market.", definition.GetDisplayName()); return; } if (ItemQuantity > limit) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, you cannot sell any more than {0} of {1} into this market.", limit, definition.GetDisplayName()); return; } } if (accountToBuy.BankBalance >= transactionAmount // || !EconomyScript.Instance.ServerConfig.LimitedSupply // I'm not sure why we check limited supply when selling. || accountToBuy.SteamId == accountToSell.SteamId) { // here we look up item price and transfer items and money as appropriate EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell finalizing by Steam Id '{0}' -- removing inventory.", SenderSteamId); RemoveInventory(playerInventory, cargoBlocks, tankBlocks, amount, definition.Id); marketItem.Quantity += ItemQuantity; // increment Market content. if (accountToBuy.SteamId != accountToSell.SteamId) { accountToBuy.BankBalance -= transactionAmount; accountToBuy.Date = DateTime.Now; accountToSell.BankBalance += transactionAmount; accountToSell.Date = DateTime.Now; MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You just sold {0} {3} worth of {2} ({1} units)", transactionAmount, ItemQuantity, definition.GetDisplayName(), EconomyScript.Instance.ServerConfig.CurrencyName); MessageUpdateClient.SendAccountMessage(accountToBuy); MessageUpdateClient.SendAccountMessage(accountToSell); } else { accountToSell.Date = DateTime.Now; MessageClientTextMessage.SendMessage(SenderSteamId, "BUY", "You just arranged transfer of {0} '{1}' into your market.", ItemQuantity, definition.GetDisplayName()); } } else { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "NPC can't afford {0} {4} worth of {2} ({1} units) NPC only has {3} funds!", transactionAmount, ItemQuantity, definition.GetDisplayName(), accountToBuy.BankBalance, EconomyScript.Instance.ServerConfig.CurrencyName); } EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create completed by Steam Id '{0}' -- to NPC market.", SenderSteamId); return; } if (OfferToMarket) { // TODO: Here we post offer to appropriate zone market MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Offset to market at price is not yet available!"); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create aborted by Steam Id '{0}' -- Offer to market at price is not yet available.", SenderSteamId); return; } // is it a player then? if (accountToBuy.SteamId == sellingPlayer.SteamUserId) { // commented out for testing with myself. MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, you cannot sell to yourself!"); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create aborted by Steam Id '{0}' -- can't sell to self.", SenderSteamId); return; } // check if buying player is online and in range? var buyingPlayer = MyAPIGateway.Players.FindPlayerBySteamId(accountToBuy.SteamId); if (EconomyScript.Instance.ServerConfig.LimitedRange && !Support.RangeCheck(buyingPlayer, sellingPlayer)) { MessageClientTextMessage.SendMessage(SenderSteamId, "BUY", "Sorry, you are not in range of that player!"); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create aborted by Steam Id '{0}' -- target player not in range.", SenderSteamId); return; } // if other player online, send message. if (buyingPlayer == null) { // TODO: other player offline. MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You cannot sell to offline players at this time."); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create aborted by Steam Id '{0}' -- cannot sell to offline player.", SenderSteamId); return; // TODO: we need a way to queue up messages. // While you were gone.... // You missed an offer for 4000Kg of Gold for 20,000. } else { // The other player is online. // write to Trade offer table. MarketManager.CreateTradeOffer(SenderSteamId, ItemTypeId, ItemSubTypeName, ItemQuantity, ItemPrice, accountToBuy.SteamId); // remove items from inventory. EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell finalizing by Steam Id '{0}' -- removing inventory.", SenderSteamId); RemoveInventory(playerInventory, cargoBlocks, tankBlocks, amount, definition.Id); // Only send message to targeted player if this is the only offer pending for them. // Otherwise it will be sent when the have with previous orders in their order Queue. if (EconomyScript.Instance.Data.OrderBook.Count(e => (e.OptionalId == accountToBuy.SteamId.ToString() && e.TradeState == TradeState.SellDirectPlayer)) == 1) { MessageClientTextMessage.SendMessage(accountToBuy.SteamId, "SELL", "You have received an offer from {0} to buy {1} {2} at price {3} {4} each - type '/sell accept' to accept offer (or '/sell deny' to reject and return item to seller)", SenderDisplayName, ItemQuantity, definition.GetDisplayName(), ItemPrice, EconomyScript.Instance.ServerConfig.CurrencyName); } // TODO: Improve the message here, to say who were are trading to, and that the item is gone from inventory. // send message to seller to confirm action, "Your Trade offer has been submitted, and the goods removed from you inventory." MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Your offer of {0} {1} for {2} {4} each has been sent to {3}.", ItemQuantity, definition.GetDisplayName(), ItemPrice, accountToBuy.NickName, EconomyScript.Instance.ServerConfig.CurrencyName); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Create completed by Steam Id '{0}' -- to another player.", SenderSteamId); return; } } #endregion #region accept case SellAction.Accept: { EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Accept started by Steam Id '{0}'.", SenderSteamId); var order = EconomyScript.Instance.Data.OrderBook.FirstOrDefault(e => e.OptionalId == SenderSteamId.ToString() && e.TradeState == TradeState.SellDirectPlayer); if (order == null) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "There are no outstanding orders to be accepted."); return; } var payingPlayer = MyAPIGateway.Players.FindPlayerBySteamId(SenderSteamId); // get the accounts and check finance. var accountToBuy = AccountManager.FindAccount(ulong.Parse(order.OptionalId)); var transactionAmount = order.Price * order.Quantity; // need fix negative amounts before checking if the player can afford it. if (!payingPlayer.IsAdmin()) { transactionAmount = Math.Abs(transactionAmount); } if (accountToBuy.BankBalance < transactionAmount) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You cannot afford {0} {1} at this time.", transactionAmount, EconomyScript.Instance.ServerConfig.CurrencyName); return; } var accountToSell = AccountManager.FindAccount(order.TraderId); // rebalance accounts. accountToBuy.BankBalance -= transactionAmount; accountToBuy.Date = DateTime.Now; accountToSell.BankBalance += transactionAmount; accountToSell.Date = DateTime.Now; MessageUpdateClient.SendAccountMessage(accountToBuy); MessageUpdateClient.SendAccountMessage(accountToSell); order.TradeState = TradeState.SellAccepted; var definition = MyDefinitionManager.Static.GetDefinition(order.TypeId, order.SubtypeName); if (definition == null) { // Someone hacking, and passing bad data? MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, the item in your order doesn't exist!"); // trade has been finalized, so we can exit safely. EconomyScript.Instance.ServerLogger.WriteVerbose("Definition could not be found for item during '/sell accept'; '{0}' '{1}'.", order.TypeId, order.SubtypeName); return; } // TODO: Improve the messages. // message back "Your Trade offer of xxx to yyy has been accepted. You have recieved zzzz" MessageClientTextMessage.SendMessage(accountToSell.SteamId, "SELL", "You just sold {0} {3} worth of {2} ({1} units)", transactionAmount, order.Quantity, definition.GetDisplayName(), EconomyScript.Instance.ServerConfig.CurrencyName); var collectingPlayer = MyAPIGateway.Players.FindPlayerBySteamId(SenderSteamId); var playerInventory = collectingPlayer.GetPlayerInventory(); bool hasAddedToInventory = true; if (playerInventory != null) { MyFixedPoint amount = (MyFixedPoint)order.Quantity; hasAddedToInventory = Support.InventoryAdd(playerInventory, amount, definition.Id); } if (hasAddedToInventory) { EconomyScript.Instance.Data.OrderBook.Remove(order); // item has been collected, so the order is finalized. MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You just purchased {0} {3} worth of {2} ({1} units) which are now in your player inventory.", transactionAmount, order.Quantity, definition.GetDisplayName(), EconomyScript.Instance.ServerConfig.CurrencyName); } else { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You just purchased {0} {3} worth of {2} ({1} units). Enter '/collect' when you are ready to receive them.", transactionAmount, order.Quantity, definition.GetDisplayName(), EconomyScript.Instance.ServerConfig.CurrencyName); } // Send message to player if additional offers are pending their attention. DisplayNextOrderToAccept(SenderSteamId); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Accept completed by Steam Id '{0}'.", SenderSteamId); return; } #endregion #region collect case SellAction.Collect: { EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Collect or /collect started by Steam Id '{0}'.", SenderSteamId); var collectableOrders = EconomyScript.Instance.Data.OrderBook.Where(e => (e.TraderId == SenderSteamId && e.TradeState == TradeState.SellTimedout) || (e.TraderId == SenderSteamId && e.TradeState == TradeState.Holding) || (e.TraderId == SenderSteamId && e.TradeState == TradeState.SellRejected) || (e.OptionalId == SenderSteamId.ToString() && e.TradeState == TradeState.SellAccepted)).ToArray(); if (collectableOrders.Length == 0) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "There is nothing to collect currently."); return; } var collectingPlayer = MyAPIGateway.Players.FindPlayerBySteamId(SenderSteamId); // TODO: this is just for debugging until the message below are completed.... //MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You are collecting items from {0} order/s.", collectableOrders.Length); foreach (var order in collectableOrders) { MyDefinitionBase definition = null; MyObjectBuilderType result; if (MyObjectBuilderType.TryParse(order.TypeId, out result)) { var id = new MyDefinitionId(result, order.SubtypeName); MyDefinitionManager.Static.TryGetDefinition(id, out definition); } if (definition == null) { // Someone hacking, and passing bad data? MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, the item in your order doesn't exist!"); // TODO: more detail on the item. EconomyScript.Instance.ServerLogger.WriteVerbose("Definition could not be found for item during '/sell collect or /collect'; '{0}' '{1}'.", order.TypeId, order.SubtypeName); continue; } EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell finalizing by Steam Id '{0}' -- adding to inventories.", SenderSteamId); var remainingToCollect = MessageSell.AddToInventories(collectingPlayer, order.Quantity, definition.Id); var collected = order.Quantity - remainingToCollect; if (remainingToCollect == 0) { EconomyScript.Instance.Data.OrderBook.Remove(order); MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You just collected {0} worth of {2} ({1} units)", order.Price * collected, collected, definition.GetDisplayName()); } else { order.Quantity = remainingToCollect; MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You just collected {0} worth of {2} ({1} units). There are {3} remaining.", order.Price * collected, collected, definition.GetDisplayName(), remainingToCollect); } } EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Collect completed by Steam Id '{0}'.", SenderSteamId); return; } #endregion #region cancel case SellAction.Cancel: { EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Cancel started by Steam Id '{0}'.", SenderSteamId); var cancellableOrders = EconomyScript.Instance.Data.OrderBook.Where(e => (e.TraderId == SenderSteamId && e.TradeState == TradeState.SellDirectPlayer)).OrderByDescending(e => e.Created).ToArray(); if (cancellableOrders.Length == 0) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "There is nothing to cancel currently."); } // Sellers should be presented with the newest order first, as they will be the most recently created. // use of OrderByDescending above assures us that [0] is the most recent order added. var order = cancellableOrders[0]; order.TradeState = TradeState.SellRejected; var definition = MyDefinitionManager.Static.GetDefinition(order.TypeId, order.SubtypeName); if (definition == null) { // Someone hacking, and passing bad data? MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, the item in your order doesn't exist!"); // trade has been finalized, so we can exit safely. EconomyScript.Instance.ServerLogger.WriteVerbose("Definition could not be found for item during '/sell cancel'; '{0}' '{1}'.", order.TypeId, order.SubtypeName); return; } var transactionAmount = order.Price * order.Quantity; var collectingPlayer = MyAPIGateway.Players.FindPlayerBySteamId(SenderSteamId); var inventory = collectingPlayer.GetPlayerInventory(); bool hasAddedToInventory = true; if (inventory != null) { MyFixedPoint amount = (MyFixedPoint)order.Quantity; hasAddedToInventory = Support.InventoryAdd(inventory, amount, definition.Id); } if (hasAddedToInventory) { EconomyScript.Instance.Data.OrderBook.Remove(order); // item has been collected, so the order is finalized. MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You just cancelled the sale of {2} ({1} units) for a total of {0} {3} which are now in your inventory.", transactionAmount, order.Quantity, definition.GetDisplayName(), EconomyScript.Instance.ServerConfig.CurrencyName); } else { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "You just cancelled the sale of {2} ({1} units) for a total of {0} {3}. Enter '/sell collect' when you are ready to receive them.", transactionAmount, order.Quantity, definition.GetDisplayName(), EconomyScript.Instance.ServerConfig.CurrencyName); } cancellableOrders = EconomyScript.Instance.Data.OrderBook.Where(e => (e.TraderId == SenderSteamId && e.TradeState == TradeState.SellDirectPlayer)).OrderByDescending(e => e.Created).ToArray(); if (cancellableOrders.Length > 0) { // TODO: Inform the player of the next order in the queue that can be cancelled. } EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Cancel completed by Steam Id '{0}'.", SenderSteamId); return; } #endregion #region deny case SellAction.Deny: { EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Deny started by Steam Id '{0}'.", SenderSteamId); var buyOrdersForMe = EconomyScript.Instance.Data.OrderBook.Where(e => (e.OptionalId == SenderSteamId.ToString() && e.TradeState == TradeState.SellDirectPlayer)).OrderBy(e => e.Created).ToArray(); if (buyOrdersForMe.Length == 0) { MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "There is nothing to deny currently."); } // Buyers should be presented with the oldest order first, as they will timout first. // use of OrderBy above assures us that [0] is the most oldest order added. var order = buyOrdersForMe[0]; order.TradeState = TradeState.SellRejected; var definition = MyDefinitionManager.Static.GetDefinition(order.TypeId, order.SubtypeName); if (definition == null) { // Someone hacking, and passing bad data? MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Sorry, the item in your order doesn't exist!"); // trade has been finalized, so we can exit safely. EconomyScript.Instance.ServerLogger.WriteVerbose("Definition could not be found for item during '/sell deny'; '{0}' '{1}'.", order.TypeId, order.SubtypeName); return; } var transactionAmount = order.Price * order.Quantity; var buyerId = ulong.Parse(order.OptionalId); MessageClientTextMessage.SendMessage(buyerId, "SELL", "You just rejected the purchase of {2} ({1} units) for a total of {0} {3}.", transactionAmount, order.Quantity, definition.GetDisplayName(), EconomyScript.Instance.ServerConfig.CurrencyName); // TODO: return items to inventory automatically to Trader inventory if there is space. MessageClientTextMessage.SendMessage(order.TraderId, "SELL", "{3} has just rejected your offer of {2} ({1} units) for a total of {0} {4}. Enter '/sell collect' when you are ready to receive them.", transactionAmount, order.Quantity, definition.GetDisplayName(), SenderDisplayName, EconomyScript.Instance.ServerConfig.CurrencyName); // Send message to player if additional offers are pending their attention. DisplayNextOrderToAccept(SenderSteamId); EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Sell Deny completed by Steam Id '{0}'.", SenderSteamId); return; } #endregion } // this is a fall through from the above conditions not yet complete. MessageClientTextMessage.SendMessage(SenderSteamId, "SELL", "Not yet complete."); }
bool IMyProductionBlock.CanUseBlueprint(MyDefinitionBase blueprint) { return(CanUseBlueprint(blueprint as MyBlueprintDefinition)); }
public DefinedObjectType(MyDefinitionId definitionId) { Definition = MyDefinitionManager.Static.GetDefinition(definitionId); }
void IMyProductionBlock.InsertQueueItem(int idx, MyDefinitionBase blueprint, MyFixedPoint amount) { InsertQueueItemRequest(idx, blueprint as MyBlueprintDefinition, amount); }
void IMyProductionBlock.AddQueueItem(MyDefinitionBase blueprint, MyFixedPoint amount) { AddQueueItemRequest(blueprint as MyBlueprintDefinition, amount); }
public static string DisplayNameOf(this MyDefinitionBase def) { var vdef = def as MyVisualDefinitionBase; return(vdef != null ? vdef.DisplayNameText : def.Id.SubtypeName); }
public bool CanExport(MyDefinitionBase b) { return(m_exports?.Invoke(b) ?? true); }
bool IMyProductionBlock.CanUseBlueprint(MyDefinitionBase blueprint) { return CanUseBlueprint(blueprint as MyBlueprintDefinition); }
private void ComputeEffects(MyCubeGrid grid, AmmoDef ammoDef, float damagePool, ref float healthPool, long attackerId, int sysmteId, List <IMySlimBlock> blocks) { var largeGrid = grid.GridSizeEnum == MyCubeSize.Large; var eWarInfo = ammoDef.AreaEffect.EwarFields; var duration = (uint)eWarInfo.Duration; var stack = eWarInfo.StackDuration; var maxStack = eWarInfo.MaxStacks; var nextTick = Tick + 1; var maxTick = stack ? (uint)(nextTick + (duration * maxStack)) : nextTick + duration; var fieldType = ammoDef.AreaEffect.AreaEffect; var sync = MpActive && (DedicatedServer || IsServer); foreach (var block in blocks) { var cubeBlock = block.FatBlock as MyCubeBlock; if (damagePool <= 0 || healthPool <= 0) { break; } IMyFunctionalBlock funcBlock = null; if (fieldType != DotField) { if (cubeBlock == null || cubeBlock.MarkedForClose) { continue; } funcBlock = cubeBlock as IMyFunctionalBlock; var isConveyor = cubeBlock is MyConveyor; var ewared = EffectedCubes.ContainsKey(cubeBlock.EntityId); if (funcBlock == null || isConveyor || !cubeBlock.IsWorking && !ewared || ewared && !stack) { continue; } } var blockHp = block.Integrity; float damageScale = 1; var tmpDamagePool = damagePool; if (ammoDef.Const.DamageScaling) { var d = ammoDef.DamageScales; if (d.MaxIntegrity > 0 && blockHp > d.MaxIntegrity) { continue; } if (d.Grids.Large >= 0 && largeGrid) { damageScale *= d.Grids.Large; } else if (d.Grids.Small >= 0 && !largeGrid) { damageScale *= d.Grids.Small; } MyDefinitionBase blockDef = null; if (ammoDef.Const.ArmorScaling) { blockDef = block.BlockDefinition; var isArmor = AllArmorBaseDefinitions.Contains(blockDef) || CustomArmorSubtypes.Contains(blockDef.Id.SubtypeId); if (isArmor && d.Armor.Armor >= 0) { damageScale *= d.Armor.Armor; } else if (!isArmor && d.Armor.NonArmor >= 0) { damageScale *= d.Armor.NonArmor; } if (isArmor && (d.Armor.Light >= 0 || d.Armor.Heavy >= 0)) { var isHeavy = HeavyArmorBaseDefinitions.Contains(blockDef) || CustomHeavyArmorSubtypes.Contains(blockDef.Id.SubtypeId); if (isHeavy && d.Armor.Heavy >= 0) { damageScale *= d.Armor.Heavy; } else if (!isHeavy && d.Armor.Light >= 0) { damageScale *= d.Armor.Light; } } } if (ammoDef.Const.CustomDamageScales) { if (blockDef == null) { blockDef = block.BlockDefinition; } float modifier; var found = ammoDef.Const.CustomBlockDefinitionBasesToScales.TryGetValue(blockDef, out modifier); if (found) { damageScale *= modifier; } else if (ammoDef.DamageScales.Custom.IgnoreAllOthers) { continue; } } } var scaledDamage = tmpDamagePool * damageScale; var blockDisabled = false; if (scaledDamage <= blockHp) { tmpDamagePool = 0; } else { blockDisabled = true; tmpDamagePool -= blockHp; } if (fieldType == DotField && IsServer) { block.DoDamage(scaledDamage, MyDamageType.Explosion, sync, null, attackerId); continue; } if (funcBlock != null) { BlockState blockState; var cubeId = cubeBlock.EntityId; if (EffectedCubes.TryGetValue(cubeId, out blockState)) { if (blockState.Health > 0) { damagePool = tmpDamagePool; } if (!blockDisabled && blockState.Health - scaledDamage > 0) { blockState.Health -= scaledDamage; blockState.Endtick = Tick + (duration + 1); } else if (blockState.Endtick + (duration + 1) < maxTick) { blockState.Health = 0; healthPool -= 1; blockState.Endtick += (duration + 1); } else { blockState.Health = 0; healthPool -= 1; blockState.Endtick = maxTick; } } else { damagePool = tmpDamagePool; blockState.FunctBlock = funcBlock; var originState = blockState.FunctBlock.Enabled; blockState.FirstTick = Tick + 1; blockState.FirstState = originState; blockState.NextTick = nextTick; blockState.Endtick = Tick + (duration + 1); blockState.Session = this; blockState.AmmoDef = ammoDef; blockState.SystemId = sysmteId; if (!blockDisabled) { blockState.Health = blockHp - scaledDamage; } else { blockState.Health = 0; } } EffectedCubes[cubeId] = blockState; } } if (!IsServer) { EffectedCubes.Clear(); } }
public static MyObjectBuilder_ToolbarItem ObjectBuilderFromDefinition(MyDefinitionBase defBase) { if (defBase is MyUsableItemDefinition) { MyObjectBuilder_ToolbarItemUsable usableData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemUsable>(); usableData.DefinitionId = defBase.Id; return(usableData); } else if ((defBase is MyPhysicalItemDefinition) && (defBase.Id.TypeId == typeof(MyObjectBuilder_PhysicalGunObject))) { MyObjectBuilder_ToolbarItemWeapon weaponData = null; // CH: TODO: This is especially ugly, I know. But it's a quick fix. To do it properly, we will need to // remove this whole method and construct the inventory items solely based upon factory tags on toolbar item types if (MyPerGameSettings.Game == GameEnum.ME_GAME) { weaponData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemMedievalWeapon>(); } else { weaponData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemWeapon>(); } weaponData.DefinitionId = defBase.Id; return(weaponData); } else if (defBase is MyCubeBlockDefinition) { MyCubeBlockDefinition blockDef = defBase as MyCubeBlockDefinition; MyObjectBuilder_ToolbarItemCubeBlock cubeData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemCubeBlock>(); cubeData.DefinitionId = defBase.Id; return(cubeData); } else if (defBase is MyAnimationDefinition) { var animData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemAnimation>(); animData.DefinitionId = defBase.Id; return(animData); } else if (defBase is MyVoxelHandDefinition) { var vhData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemVoxelHand>(); vhData.DefinitionId = defBase.Id; return(vhData); } else if (defBase is MyPrefabThrowerDefinition) { var ptData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemPrefabThrower>(); ptData.DefinitionId = defBase.Id; return(ptData); } else if (defBase is MyBotDefinition) { var bdData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemBot>(); bdData.DefinitionId = defBase.Id; return(bdData); } else if (defBase is MyAiCommandDefinition) { var acData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemAiCommand>(); acData.DefinitionId = defBase.Id; return(acData); } else if (defBase.Id.TypeId == typeof(MyObjectBuilder_RopeDefinition)) { var ob = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemRope>(); ob.DefinitionId = defBase.Id; return(ob); } else if (defBase is MyAreaMarkerDefinition) { var acData = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemAreaMarker>(); acData.DefinitionId = defBase.Id; return(acData); } else if (defBase is MyGridCreateToolDefinition) { var gctool = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ToolbarItemCreateGrid>(); gctool.DefinitionId = defBase.Id; return(gctool); } return(new MyObjectBuilder_ToolbarItemEmpty()); }
public static string GetDisplayName(this MyDefinitionBase definition) { return(definition.DisplayNameEnum.HasValue ? MyTexts.GetString(definition.DisplayNameEnum.Value) : (string.IsNullOrEmpty(definition.DisplayNameString) ? definition.Id.SubtypeName : definition.DisplayNameString)); }
public bool CanImport(MyDefinitionBase b) { return(m_imports?.Invoke(b) ?? false); }
public static MyObjectBuilder_ToolbarItem ObjectBuilderFromDefinition(MyDefinitionBase defBase) { if (defBase is MyUsableItemDefinition) { MyObjectBuilder_ToolbarItemUsable usableData = MyObjectBuilderSerializer.CreateNewObject<MyObjectBuilder_ToolbarItemUsable>(); usableData.DefinitionId = defBase.Id; return usableData; } else if ((defBase is MyPhysicalItemDefinition) && (defBase.Id.TypeId == typeof(MyObjectBuilder_PhysicalGunObject))) { MyObjectBuilder_ToolbarItemWeapon weaponData = null; // CH: TODO: This is especially ugly, I know. But it's a quick fix. To do it properly, we will need to // remove this whole method and construct the inventory items solely based upon factory tags on toolbar item types if (MyPerGameSettings.Game == GameEnum.ME_GAME) { weaponData = MyObjectBuilderSerializer.CreateNewObject<MyObjectBuilder_ToolbarItemMedievalWeapon>(); } else { weaponData = MyObjectBuilderSerializer.CreateNewObject<MyObjectBuilder_ToolbarItemWeapon>(); } weaponData.DefinitionId = defBase.Id; return weaponData; } else if (defBase is MyCubeBlockDefinition) { MyCubeBlockDefinition blockDef = defBase as MyCubeBlockDefinition; MyObjectBuilder_ToolbarItemCubeBlock cubeData = MyObjectBuilderSerializer.CreateNewObject<MyObjectBuilder_ToolbarItemCubeBlock>(); cubeData.DefinitionId = defBase.Id; return cubeData; } else if (defBase is MyAnimationDefinition) { var animData = MyObjectBuilderSerializer.CreateNewObject<MyObjectBuilder_ToolbarItemAnimation>(); animData.DefinitionId = defBase.Id; return animData; } else if (defBase is MyVoxelHandDefinition) { var vhData = MyObjectBuilderSerializer.CreateNewObject<MyObjectBuilder_ToolbarItemVoxelHand>(); vhData.DefinitionId = defBase.Id; return vhData; } else if (defBase is MyPrefabThrowerDefinition) { var ptData = MyObjectBuilderSerializer.CreateNewObject<MyObjectBuilder_ToolbarItemPrefabThrower>(); ptData.DefinitionId = defBase.Id; return ptData; } else if (defBase is MyBotDefinition) { var bdData = MyObjectBuilderSerializer.CreateNewObject<MyObjectBuilder_ToolbarItemBot>(); bdData.DefinitionId = defBase.Id; return bdData; } else if (defBase is MyAiCommandDefinition) { var acData = MyObjectBuilderSerializer.CreateNewObject<MyObjectBuilder_ToolbarItemAiCommand>(); acData.DefinitionId = defBase.Id; return acData; } else if (defBase.Id.TypeId == typeof(MyObjectBuilder_RopeDefinition)) { var ob = MyObjectBuilderSerializer.CreateNewObject<MyObjectBuilder_ToolbarItemRope>(); ob.DefinitionId = defBase.Id; return ob; } else if (defBase is MyAreaMarkerDefinition) { var acData = MyObjectBuilderSerializer.CreateNewObject<MyObjectBuilder_ToolbarItemAreaMarker>(); acData.DefinitionId = defBase.Id; return acData; } else if (defBase is MyGridCreateToolDefinition) { var gctool = MyObjectBuilderSerializer.CreateNewObject<MyObjectBuilder_ToolbarItemCreateGrid>(); gctool.DefinitionId = defBase.Id; return gctool; } return new MyObjectBuilder_ToolbarItemEmpty(); }
public static string GetDisplayName(this MyDefinitionBase definition) { return(definition.DisplayNameEnum.HasValue ? MyTexts.GetString(definition.DisplayNameEnum.Value) : definition.DisplayNameString); }
private bool CanUnlockResearch(long identityId, MyDefinitionBase definition) { HashSet<MyDefinitionId> unlockedItems; if (!m_unlockedResearch.TryGetValue(identityId, out unlockedItems) || unlockedItems == null) unlockedItems = new HashSet<MyDefinitionId>(); if (unlockedItems.Contains(definition.Id)) return false; return true; }