public MyRepairBlueprintToProduce(MyFixedPoint amount, MyBlueprintDefinitionBase blueprint, uint inventoryItemId, MyObjectBuilderType inventoryItemType, MyStringHash inventoryItemSubtypeId) : base(amount, blueprint)
 {
     System.Diagnostics.Debug.Assert(Blueprint is MyRepairBlueprintDefinition, "MyRepairBlueprintToProduce class should be used together with blueprints type of MyRepairBlueprintDefinition only!");
     InventoryItemId = inventoryItemId;
     InventoryItemType = inventoryItemType;
     InventoryItemSubtypeId = inventoryItemSubtypeId;
 }
예제 #2
0
        public void Load(MyCubeSize cubeSize, MyObjectBuilderType typeId, string subTypeId)
        {
            CubeList.Clear();
            var list = new SortedList<string, ComponentItemModel>();
            var contentPath = ToolboxUpdater.GetApplicationContentPath();
            var cubeDefinitions = SpaceEngineersCore.Resources.CubeBlockDefinitions.Where(c => c.CubeSize == cubeSize);

            foreach (var cubeDefinition in cubeDefinitions)
            {
                var c = new ComponentItemModel
                {
                    Name = cubeDefinition.DisplayNameText,
                    TypeId = cubeDefinition.Id.TypeId,
                    TypeIdString = cubeDefinition.Id.TypeId.ToString(),
                    SubtypeId = cubeDefinition.Id.SubtypeName,
                    TextureFile = (cubeDefinition.Icons == null || cubeDefinition.Icons.First() == null) ? null : SpaceEngineersCore.GetDataPathOrDefault(cubeDefinition.Icons.First(), Path.Combine(contentPath, cubeDefinition.Icons.First())),
                    Time = TimeSpan.FromSeconds(cubeDefinition.MaxIntegrity / cubeDefinition.IntegrityPointsPerSec),
                    Accessible = cubeDefinition.Public,
                    Mass = SpaceEngineersApi.FetchCubeBlockMass(cubeDefinition.Id.TypeId, cubeDefinition.CubeSize, cubeDefinition.Id.SubtypeName),
                    CubeSize = cubeDefinition.CubeSize,
                    Size = new BindableSize3DIModel(cubeDefinition.Size),
                };

                list.Add(c.FriendlyName + c.TypeIdString + c.SubtypeId, c);
            }

            foreach (var kvp in list)
            {
                CubeList.Add(kvp.Value);
            }

            CubeItem = CubeList.FirstOrDefault(c => c.TypeId == typeId && c.SubtypeId == subTypeId);
        }
        protected override void Init(MyObjectBuilder_DefinitionBase builder)
        {
            base.Init(builder);

            var ob = builder as MyObjectBuilder_EnvironmentItemsDefinition;
            MyDebug.AssertDebug(ob != null);

            m_itemDefinitions = new HashSet<MyStringHash>(MyStringHash.Comparer);
            m_definitionList = new List<MyStringHash>();

            System.Type classType = builder.Id.TypeId;
            var attribs = classType.GetCustomAttributes(typeof(MyEnvironmentItemsAttribute), inherit: false);
            Debug.Assert(attribs.Length <= 1, "Environment item class can only have one EnvironmentItemDefinition attribute!");
            if (attribs.Length == 1)
            {
                var attrib = attribs[0] as MyEnvironmentItemsAttribute;
                m_itemDefinitionType = attrib.ItemDefinitionType;
            }
            else
            {
                m_itemDefinitionType = typeof(MyObjectBuilder_EnvironmentItemDefinition);
            }

            Channel = ob.Channel;
            MaxViewDistance = ob.MaxViewDistance;
            SectorSize = ob.SectorSize;
            ItemSize = ob.ItemSize;
            Material = MyStringHash.GetOrCompute(ob.PhysicalMaterial);
        }
 public virtual bool CanStack(MyObjectBuilderType typeId, MyStringId subtypeId, MyItemFlags flags)
 {
     if (flags == Flags &&
         typeId == TypeId &&
         subtypeId == SubtypeId)
     {
         return true;
     }
     return false;
 }
예제 #5
0
 static SpaceEngineersTypes()
 {
     AmmoMagazine = new MyObjectBuilderType(typeof(MyObjectBuilder_AmmoMagazine));
     PhysicalGunObject = new MyObjectBuilderType(typeof(MyObjectBuilder_PhysicalGunObject));
     OxygenContainerObject = new MyObjectBuilderType(typeof(MyObjectBuilder_OxygenContainerObject));
     Ore = new MyObjectBuilderType(typeof(MyObjectBuilder_Ore));
     Ingot = new MyObjectBuilderType(typeof(MyObjectBuilder_Ingot));
     Component = new MyObjectBuilderType(typeof(MyObjectBuilder_Component));
     VoxelMaterialDefinition = new MyObjectBuilderType(typeof(MyObjectBuilder_VoxelMaterialDefinition));
     MedicalRoom = new MyObjectBuilderType(typeof(MyObjectBuilder_MedicalRoom));
     Cockpit = new MyObjectBuilderType(typeof(MyObjectBuilder_Cockpit));
     Thrust = new MyObjectBuilderType(typeof(MyObjectBuilder_Thrust));
 }
        public MySessionComponentBase()
        {
            var type = GetType();
            var attr = (MySessionComponentDescriptor)Attribute.GetCustomAttribute(type, typeof(MySessionComponentDescriptor), false);

            DebugName = type.Name;
            Priority = attr.Priority;
            UpdateOrder = attr.UpdateOrder;
            ObjectBuilderType = attr.ObjectBuilderType;

            if (ObjectBuilderType != MyObjectBuilderType.Invalid)
                MySessionComponentMapping.Map(GetType(), ObjectBuilderType);
        }
        public MySessionComponentDescriptor(MyUpdateOrder updateOrder, int priority, Type obType)
        {
            UpdateOrder = updateOrder;
            Priority = priority;
            ObjectBuilderType = obType;

            if (obType != null)
            {
                Debug.Assert(typeof(MyObjectBuilder_SessionComponent).IsAssignableFrom(obType), obType.FullName);

                if (!typeof(MyObjectBuilder_SessionComponent).IsAssignableFrom(obType))
                {
                    ObjectBuilderType = MyObjectBuilderType.Invalid;
                }
            }
        }
        public static MyObjectBuilder_CubeBlock Upgrade(MyObjectBuilder_CubeBlock cubeBlock, MyObjectBuilderType newType, string newSubType)
        {
            var upgraded = MyObjectBuilderSerializer.CreateNewObject(newType, newSubType) as MyObjectBuilder_CubeBlock;
            if (upgraded == null)
            {
                Debug.Fail("Cannot upgrade cube block, upgraded block is not derived from " + typeof(MyObjectBuilder_CubeBlock).Name);
                return null;
            }

            upgraded.EntityId = cubeBlock.EntityId;
            upgraded.Min = cubeBlock.Min;
            upgraded.m_orientation = cubeBlock.m_orientation;
            upgraded.IntegrityPercent = cubeBlock.IntegrityPercent;
            upgraded.BuildPercent = cubeBlock.BuildPercent;
            upgraded.BlockOrientation = cubeBlock.BlockOrientation;
            upgraded.ConstructionInventory = cubeBlock.ConstructionInventory;
            upgraded.ColorMaskHSV = cubeBlock.ColorMaskHSV;

            return upgraded;
        }
        public static bool Map(Type type, MyObjectBuilderType objectBuilderType)
        {
            Debug.Assert(type.IsSubclassOf(typeof(MySessionComponentBase)), "Type is not derived from session component");
            Debug.Assert(!m_objectBuilderTypeByType.ContainsKey(type), "Session component type is already mapped");
            Debug.Assert(!m_typeByObjectBuilderType.ContainsKey(objectBuilderType), "Session object builder is already mapped");

            if (!type.IsSubclassOf(typeof(MySessionComponentBase)))
                return false;

            if (!m_objectBuilderTypeByType.ContainsKey(type))
                m_objectBuilderTypeByType.Add(type, objectBuilderType);
            else
                return false;

            if (!m_typeByObjectBuilderType.ContainsKey(objectBuilderType))
                m_typeByObjectBuilderType.Add(objectBuilderType, type);
            else
                return false;

            return true;
        }
        private void RepairInventoryItem(uint itemId, MyObjectBuilderType objectBuilderType, MyStringHash subtypeId, float amount)
        {
            var inventory = (Entity as MyEntity).GetInventory();

            if (inventory == null)
            {
                System.Diagnostics.Debug.Fail("Inventory was not found on the entity while trying to repair item in it!");
                return;
            }

            var item = inventory.GetItemByID(itemId);
            
            System.Diagnostics.Debug.Assert(item != null, "Item being repaired wasn't found by its Id in inventory");

            if (item.HasValue && item.Value.Content != null && item.Value.Content.TypeId == objectBuilderType && item.Value.Content.SubtypeId == subtypeId)
            {
                float itemHP = item.Value.Content != null && item.Value.Content.DurabilityHP.HasValue ? item.Value.Content.DurabilityHP.Value : 0;

                itemHP += amount;
                itemHP = MathHelper.Clamp(itemHP, 0f, 100f);
                inventory.UpdateItem(item.GetDefinitionId(), itemId, null, itemHP);
            }
        }
예제 #11
0
 public static Type TryGetCreatedInstanceType(MyObjectBuilderType type)
 {
     return m_objectFactory.TryGetProducedType(type);
 }
 public static Type GetProducedType(MyObjectBuilderType objectBuilderType)
 {
     return m_objectFactory.GetProducedType(objectBuilderType);
 }
예제 #13
0
 public static bool PullAllRequest(IMyConveyorEndpointBlock start, MyInventory destinationInventory, long playerId, MyObjectBuilderType? typeId = null)
 {
     SetTraversalPlayerId(playerId);
     m_tmpRequestedItemSet.Set(typeId);
     bool ret = ItemPullAll(start, destinationInventory);
     m_tmpRequestedItemSet.Clear();
     return ret;
 }
        public static HashSet <IMyTerminalBlock> GetGroupedBlocks(this IMyFunctionalBlock reference, MyObjectBuilderType objtype, string subtype = null)
        {
            var blocks = new HashSet <IMyTerminalBlock>();

            if (MyAPIGateway.TerminalActionsHelper == null)
            {
                return(blocks);
            }

            var terminal = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(reference.CubeGrid as IMyCubeGrid);

            if (terminal == null)   // This will get hit when leaving the world
            {
                return(blocks);
            }
            var groups        = new List <IMyBlockGroup>();
            var blocksInGroup = new List <IMyTerminalBlock>();

            terminal.GetBlockGroups(groups);

            // Scan each group, looking for the FTL
            foreach (var group in groups)
            {
                group.GetBlocks(blocksInGroup);
                if (blocksInGroup.Contains(reference))
                {
                    // We found one, grab the blocks we want
                    foreach (var block in blocksInGroup)
                    {
                        // Make sure the blocks match the type we're looking for
                        if (block.BlockDefinition.TypeId == objtype &&
                            (string.IsNullOrEmpty(subtype) ||
                             block.BlockDefinition.SubtypeId.ToUpperInvariant().Contains(subtype)))
                        {
                            blocks.Add(block as IMyTerminalBlock);
                        }
                    }
                }
            }
            return(blocks);
        }
예제 #15
0
 public static MyDefinitionBase GetDefinition(this MyDefinitionManager definitionManager, MyObjectBuilderType typeId, string subTypeId)
 {
     return definitionManager.GetAllDefinitions().FirstOrDefault(e => e.Id.TypeId == typeId && e.Id.SubtypeName == subTypeId);
 }
 public SerializableDefinitionId(MyObjectBuilderType typeId, string subtypeName)
 {
     TypeId = typeId;
     SubtypeName = subtypeName;
 }
예제 #17
0
        public override void ProcessServer()
        {
            // update our own timestamp here
            AccountManager.UpdateLastSeen(SenderSteamId, SenderLanguage);
            EconomyScript.Instance.ServerLogger.WriteVerbose("Price List Request for from '{0}'", SenderSteamId);

            var player    = MyAPIGateway.Players.FindPlayerBySteamId(SenderSteamId);
            var character = player.GetCharacter();

            if (character == null)
            {
                MessageClientTextMessage.SendMessage(SenderSteamId, "PRICELIST", "You are dead. You get market items values while dead.");
                return;
            }

            List <MarketStruct> markets;

            if (string.IsNullOrEmpty(FindMarket))
            {
                var position = ((IMyEntity)character).WorldMatrix.Translation;
                markets = MarketManager.FindMarketsFromLocation(position);
            }
            else
            {
                markets = MarketManager.FindMarketsFromName(FindMarket);
            }

            if (markets.Count == 0)
            {
                MessageClientTextMessage.SendMessage(SenderSteamId, "PRICELIST", "Sorry, your are not in range of any markets!");
                return;
            }

            // TODO: combine multiple markets to list best Buy and Sell prices that isn't blacklisted.


            var market = markets.FirstOrDefault();

            if (market == null) //hmmm looks like market name parameter checking was started but never done
            {
                MessageClientTextMessage.SendMessage(SenderSteamId, "PRICELIST", "That market does not exist.");
                return;  //as I understand it this would only trigger if no markets are defined?
                //in which case should it read no markets exist?  but in that case
                // wont the count check above halt execution before this if statement???
                // remove these comments once read :)
            }

            string reply = null;

            MyAPIGateway.Parallel.StartBackground(delegate()
                                                  // Background processing occurs within this block.
            {
                try
                {
                    bool showAll = !ShowOre && !ShowIngot && !ShowComponent && !ShowAmmo && !ShowTools && !ShowGasses;

                    var orderedList = new Dictionary <MarketItemStruct, string>();
                    foreach (var marketItem in market.MarketItems)
                    {
                        if (marketItem.IsBlacklisted)
                        {
                            continue;
                        }

                        MyObjectBuilderType result;
                        if (MyObjectBuilderType.TryParse(marketItem.TypeId, out result))
                        {
                            var id      = new MyDefinitionId(result, marketItem.SubtypeName);
                            var content = Support.ProducedType(id);

                            // Cannot check the Type of the item, without having to use MyObjectBuilderSerializer.CreateNewObject().

                            if (showAll ||
                                (ShowOre && content is MyObjectBuilder_Ore) ||
                                (ShowIngot && content is MyObjectBuilder_Ingot) ||
                                (ShowComponent && content is MyObjectBuilder_Component) ||
                                (ShowAmmo && content is MyObjectBuilder_AmmoMagazine) ||
                                (ShowTools && content is MyObjectBuilder_PhysicalGunObject) ||   // guns, welders, hand drills, grinders.
                                (ShowGasses && content is MyObjectBuilder_GasContainerObject) || // aka gas bottle.
                                (ShowGasses && content is MyObjectBuilder_GasProperties))
                            // Type check here allows mods that inherit from the same type to also appear in the lists.
                            {
                                var definition = MyDefinitionManager.Static.GetDefinition(marketItem.TypeId, marketItem.SubtypeName);
                                var name       = definition == null ? marketItem.SubtypeName : definition.GetDisplayName();
                                orderedList.Add(marketItem, name);
                            }
                        }
                    }

                    orderedList = orderedList.OrderBy(kvp => kvp.Value).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

                    var str = new SeTextBuilder();
                    str.AppendLine("Market: {0}\r\n", market.DisplayName);
                    str.AddLeftTrim(550, "Item");
                    str.AddRightText(650, "Buy at");
                    str.AddRightText(850, "Sell at");
                    str.AppendLine();

                    foreach (var kvp in orderedList)
                    {
                        decimal showBuy  = kvp.Key.BuyPrice;
                        decimal showSell = kvp.Key.SellPrice;
                        if ((EconomyScript.Instance.ServerConfig.PriceScaling) && (market.MarketId == EconomyConsts.NpcMerchantId))
                        {
                            showBuy  = EconDataManager.PriceAdjust(kvp.Key.BuyPrice, kvp.Key.Quantity, PricingBias.Buy);
                            showSell = EconDataManager.PriceAdjust(kvp.Key.SellPrice, kvp.Key.Quantity, PricingBias.Sell);
                        }
                        // TODO: formatting of numbers, and currency name.
                        str.AddLeftTrim(550, kvp.Value);
                        str.AddRightText(650, showBuy.ToString("0.00", EconomyScript.ServerCulture));
                        str.AddRightText(850, showSell.ToString("0.00", EconomyScript.ServerCulture));
                        str.AppendLine();
                    }
                    reply = str.ToString();
                }
                catch (Exception ex)
                {
                    EconomyScript.Instance.ServerLogger.WriteException(ex);
                    MessageClientTextMessage.SendMessage(SenderSteamId, "PRICELIST", "Failed and died. Please contact the administrator.");
                }
            }, delegate()
                                                  // when the background processing is finished, this block will run foreground.
            {
                if (reply != null)
                {
                    try
                    {
                        MessageClientDialogMessage.SendMessage(SenderSteamId, "PRICELIST", " ", reply);
                    }
                    catch (Exception ex)
                    {
                        EconomyScript.Instance.ServerLogger.WriteException(ex);
                        MessageClientTextMessage.SendMessage(SenderSteamId, "PRICELIST", "Failed and died. Please contact the administrator.");
                    }
                }
            });
        }
예제 #18
0
 public MyDefinitionId(MyRuntimeObjectBuilderId type, MyStringHash subtypeId)
 {
     TypeId    = (MyObjectBuilderType)type;
     SubtypeId = subtypeId;
 }
예제 #19
0
 public static Type GetProducedType(MyObjectBuilderType objectBuilderType) =>
 m_objectFactory.GetProducedType(objectBuilderType);
예제 #20
0
        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?

            MyPhysicalItemDefinition definition = null;
            MyObjectBuilderType      result;

            if (MyObjectBuilderType.TryParse(ItemTypeId, out result))
            {
                var id = new MyDefinitionId(result, ItemSubTypeName);
                MyDefinitionManager.Static.TryGetPhysicalItemDefinition(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 spectified");
                    return;
                }
            }

            // Find the specified market.
            var market = EconomyScript.Instance.Data.Markets.FirstOrDefault(m => m.MarketId == MarketId);

            if (market == null)
            {
                MessageClientTextMessage.SendMessage(SenderSteamId, "SET", "Sorry, the market you are accessing does not exist!");
                return;
            }

            var marketItem = market.MarketItems.FirstOrDefault(e => e.TypeId == ItemTypeId && e.SubtypeName == ItemSubTypeName);

            if (marketItem == null)
            {
                MessageClientTextMessage.SendMessage(SenderSteamId, "SET", "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.
                return;
            }

            MarketItemStruct configItem = null;

            if (player.IsAdmin() && MarketId == EconomyConsts.NpcMerchantId)
            {
                configItem = EconomyScript.Instance.Config.DefaultPrices.FirstOrDefault(e => e.TypeId == ItemTypeId && e.SubtypeName == ItemSubTypeName);
            }

            var msg = new StringBuilder();

            msg.AppendFormat("You just set '{0}'", definition.GetDisplayName());

            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);

                    if (configItem != null)
                    {
                        configItem.BuyPrice = ItemBuyPrice;
                        msg.AppendFormat("; config updated.");
                    }
                }
                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);

                    if (configItem != null)
                    {
                        configItem.SellPrice = ItemSellPrice;
                        msg.AppendFormat("; config updated.");
                    }
                }
                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");

                if (configItem != null)
                {
                    configItem.IsBlacklisted = marketItem.IsBlacklisted;
                    msg.AppendFormat("; config updated.");
                }
            }

            MessageClientTextMessage.SendMessage(SenderSteamId, "SET", msg.ToString());
        }
예제 #21
0
        public static void ProcessLcdBlock(IMyTextPanel textPanel)
        {
            //counter++;

            var writer = TextPanelWriter.Create(textPanel);

            // Use the update interval on the LCD Panel to determine how often the display is updated.
            // It can only go as fast as the timer calling this code is.
            float interval;

            try
            {
                interval = Math.Max((float)EconomyScript.Instance.ServerConfig.MinimumLcdDisplayInterval, textPanel.GetValueFloat("ChangeIntervalSlider"));
            }
            catch (Exception ex)
            {
                // The game may generate an exception from the GetValueFloat(GetValue) call.
                EconomyScript.Instance.ServerLogger.WriteException(ex, UpdateCrashMessage);
                EconomyScript.Instance.ClientLogger.WriteException(ex, UpdateCrashMessage);
                // We can't safely ignore this one if it doesn't work, because this can affect the display timing.
                return;
            }
            if (writer.LastUpdate > DateTime.Now.AddSeconds(-interval))
            {
                return;
            }

            var       checkArray    = textPanel.GetPublicTitle().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            var       showAll       = false;
            bool      showOre       = false;
            bool      showIngot     = false;
            bool      showComponent = false;
            bool      showAmmo      = false;
            bool      showTools     = false;
            bool      showGasses    = false;
            bool      showStock     = false;
            bool      showPrices    = true;
            bool      showTest1     = false;
            bool      showTest2     = false;
            StartFrom startFrom     = StartFrom.None; //if # is specified eg #20  then run the start line logic
            int       startLine     = 0;              //this is where our start line placeholder sits
            int       pageNo        = 1;

            // removed Linq, to reduce the looping through the array. This should only have to do one loop through all items in the array.
            foreach (var str in checkArray)
            {
                if (str.Equals("stock", StringComparison.InvariantCultureIgnoreCase))
                {
                    showStock = true;
                }
                if (str.Contains("#"))
                {
                    string[] lineNo = str.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
                    if (lineNo.Length != 0 && int.TryParse(lineNo[0], out startLine))
                    {
                        //this only runs if they put a number in
                        startFrom = StartFrom.Line;
                    }
                }
                if (str.StartsWith("P", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (int.TryParse(str.Substring(1), out pageNo))
                    {
                        startFrom = StartFrom.Page;
                    }
                }
                if (str.Equals("*", StringComparison.InvariantCultureIgnoreCase))
                {
                    showAll = true;
                }
                if (!showAll)
                {
                    if (str.Equals("test1", StringComparison.InvariantCultureIgnoreCase))
                    {
                        showTest1 = true;
                    }
                    else if (str.Equals("test2", StringComparison.InvariantCultureIgnoreCase))
                    {
                        showTest2 = true;
                    }
                    else if (str.StartsWith("ore", StringComparison.InvariantCultureIgnoreCase))
                    {
                        showOre = true;
                    }
                    else if (str.StartsWith("ingot", StringComparison.InvariantCultureIgnoreCase))
                    {
                        showIngot = true;
                    }
                    else if (str.StartsWith("component", StringComparison.InvariantCultureIgnoreCase))
                    {
                        showComponent = true;
                    }
                    else if (str.StartsWith("ammo", StringComparison.InvariantCultureIgnoreCase))
                    {
                        showAmmo = true;
                    }
                    else if (str.StartsWith("tool", StringComparison.InvariantCultureIgnoreCase))
                    {
                        showTools = true;
                    }
                    else if (str.StartsWith("gas", StringComparison.InvariantCultureIgnoreCase))
                    {
                        showGasses = true;
                    }
                }
            }

            bool showHelp = !showAll && !showOre && !showIngot && !showComponent && !showAmmo && !showTools && !showGasses;



            showPrices = !showStock || writer.IsWide;

            if (showTest1)
            {
                Test1(writer);
                writer.UpdatePublic();
                return;
            }
            if (showTest2)
            {
                Test2(writer);
                writer.UpdatePublic();
                return;
            }

            if (showHelp)
            {
                writer.AddPublicLine("Please add a tag to the private or public title.");
                writer.AddPublicLine("ie., * ingot ore component ammo tools.");
                writer.UpdatePublic();
                return;
            }

            var buyColumn   = TextPanelWriter.LcdLineWidth - 180;
            var sellColumn  = TextPanelWriter.LcdLineWidth - 0;
            var stockColumn = TextPanelWriter.LcdLineWidth - 0;

            if (showPrices && showStock)
            {
                buyColumn   = TextPanelWriter.LcdLineWidth - 280;
                sellColumn  = TextPanelWriter.LcdLineWidth - 180;
                stockColumn = TextPanelWriter.LcdLineWidth - 0;
            }

            // This might be a costly operation to run.
            var markets = MarketManager.FindMarketsFromLocation(textPanel.WorldMatrix.Translation);

            if (markets.Count == 0)
            {
                writer.AddPublicCenterLine(TextPanelWriter.LcdLineWidth / 2f, "« {0} »", EconomyScript.Instance.ServerConfig.TradeNetworkName);
                writer.AddPublicCenterLine(TextPanelWriter.LcdLineWidth / 2f, "« No market in range »");
            }
            else
            {
                // TODO: not sure if we should display all markets, the cheapest market item, or the closet market.
                // LOGIC summary: it needs to show the cheapest in stock(in range) sell(to player) price, and the highest (in range) has funds buy(from player) price
                // but this logic depends on the buy/sell commands defaulting to the same buy/sell rules as above.
                // where buy /sell commands run out of funds or supply in a given market and need to pull from the next market
                //it will either have to stop at each price change and notify the player, and/or prompt to keep transacting at each new price, or blindly keep buying until the
                //order is filled, the market runs out of stock, or the money runs out. Blindly is probably not optimal unless we are using stockmarket logic (buy orders/offers)
                //so the prompt option is the safer
                var market = markets.FirstOrDefault();

                // Build a list of the items, so we can get the name so we can the sort the items by name.
                var list = new Dictionary <MarketItemStruct, string>();

                writer.AddPublicCenterLine(TextPanelWriter.LcdLineWidth / 2f, market.DisplayName);

                if (startFrom == StartFrom.Page)
                {
                    // convert the page to lines required.
                    if (pageNo < 1)
                    {
                        pageNo = 1;
                    }
                    startLine = ((writer.DisplayLines - 2) * (pageNo - 1));
                    startFrom = StartFrom.Line;
                }

                string fromLine = " (From item #" + startLine + ".)";
                writer.AddPublicText("« Market List");
                if (startLine >= 1)
                {
                    writer.AddPublicText(fromLine);
                }
                else
                {
                    startLine = 1; // needed for truncating end line.
                }
                if (showPrices && showStock)
                {
                    writer.AddPublicRightText(buyColumn, "Buy");
                    writer.AddPublicRightText(sellColumn, "Sell");
                    writer.AddPublicRightLine(stockColumn, "Stock »");
                }
                else if (showStock)
                {
                    writer.AddPublicRightLine(stockColumn, "Stock »");
                }
                else if (showPrices)
                {
                    writer.AddPublicRightText(buyColumn, "Buy");
                    writer.AddPublicRightLine(sellColumn, "Sell »");
                }

                foreach (var marketItem in market.MarketItems)
                {
                    if (marketItem.IsBlacklisted)
                    {
                        continue;
                    }

                    MyObjectBuilderType result;
                    if (MyObjectBuilderType.TryParse(marketItem.TypeId, out result))
                    {
                        var id      = new MyDefinitionId(result, marketItem.SubtypeName);
                        var content = Support.ProducedType(id);

                        //if (((Type)id.TypeId).IsSubclassOf(typeof(MyObjectBuilder_GasContainerObject))) // TODO: Not valid call yet.

                        // Cannot check the Type of the item, without having to use MyObjectBuilderSerializer.CreateNewObject().

                        if (showAll ||
                            (showOre && content is MyObjectBuilder_Ore) ||
                            (showIngot && content is MyObjectBuilder_Ingot) ||
                            (showComponent && content is MyObjectBuilder_Component) ||
                            (showAmmo && content is MyObjectBuilder_AmmoMagazine) ||
                            (showTools && content is MyObjectBuilder_PhysicalGunObject) ||   // guns, welders, hand drills, grinders.
                            (showGasses && content is MyObjectBuilder_GasContainerObject) || // aka gas bottle.
                            (showGasses && content is MyObjectBuilder_GasProperties))        // Type check here allows mods that inherit from the same type to also appear in the lists.
                        {
                            MyDefinitionBase definition;
                            if (MyDefinitionManager.Static.TryGetDefinition(id, out definition))
                            {
                                list.Add(marketItem, definition == null ? marketItem.TypeId + "/" + marketItem.SubtypeName : definition.GetDisplayName());
                            }
                        }
                    }
                }
                int line = 0;
                foreach (var kvp in list.OrderBy(k => k.Value))
                {
                    line++;
                    if (startFrom == StartFrom.Line && line < startLine) //if we have a start line specified skip all lines up to that
                    {
                        continue;
                    }
                    if (startFrom == StartFrom.Line && line - startLine >= writer.WholeDisplayLines - 2) // counts 2 lines of headers.
                    {
                        break;                                                                           // truncate the display and don't display the text on the bottom edge of the display.
                    }
                    writer.AddPublicLeftTrim(buyColumn - 120, kvp.Value);

                    decimal showBuy  = kvp.Key.BuyPrice;
                    decimal showSell = kvp.Key.SellPrice;
                    if ((EconomyScript.Instance.ServerConfig.PriceScaling) && (market.MarketId == EconomyConsts.NpcMerchantId))
                    {
                        showBuy  = EconDataManager.PriceAdjust(kvp.Key.BuyPrice, kvp.Key.Quantity, PricingBias.Buy);
                        showSell = EconDataManager.PriceAdjust(kvp.Key.SellPrice, kvp.Key.Quantity, PricingBias.Sell);
                    }

                    if (showPrices && showStock)
                    {
                        writer.AddPublicRightText(buyColumn, showBuy.ToString("\t0.000", EconomyScript.ServerCulture));
                        writer.AddPublicRightText(sellColumn, showSell.ToString("\t0.000", EconomyScript.ServerCulture));

                        // TODO: components and tools should be displayed as whole numbers. Will be hard to align with other values.
                        writer.AddPublicRightText(stockColumn, kvp.Key.Quantity.ToString("\t0.0000", EconomyScript.ServerCulture)); // TODO: recheck number of decimal places.
                    }
                    else if (showStock)                                                                                             //does this ever actually run? seems to already be in the above?
                    {
                        // TODO: components and tools should be displayed as whole numbers. Will be hard to align with other values.

                        writer.AddPublicRightText(stockColumn, kvp.Key.Quantity.ToString("\t0.0000", EconomyScript.ServerCulture)); // TODO: recheck number of decimal places.
                    }
                    else if (showPrices)
                    {
                        writer.AddPublicRightText(buyColumn, showBuy.ToString("\t0.000", EconomyScript.ServerCulture));
                        writer.AddPublicRightText(sellColumn, showSell.ToString("\t0.000", EconomyScript.ServerCulture));
                    }
                    writer.AddPublicLine();
                }
            }

            writer.UpdatePublic();
        }
예제 #22
0
 public static void RegisterFromAssembly(Assembly assembly)
 {
     MyObjectBuilderSerializer.RegisterFromAssembly(assembly);
     MyObjectBuilderType.RegisterFromAssembly(assembly);
     MyDefinitionManagerBase.RegisterTypesFromAssembly(assembly);
 }
        public static IMyTerminalBlock GetShipController(this IMyFunctionalBlock ftl, string tag = "FTL")
        {
            IMyTerminalBlock reference = null;
            var cockpitObjectBuilder   = new MyObjectBuilderType(typeof(MyObjectBuilder_Cockpit));
            var rcObjectBuilder        = new MyObjectBuilderType(typeof(MyObjectBuilder_RemoteControl));

            var cockpitlist = ftl.GetGroupedBlocks(cockpitObjectBuilder);
            var rclist      = ftl.GetGroupedBlocks(rcObjectBuilder);

            cockpitlist.UnionWith(rclist);

            if (cockpitlist.Count != 0)
            {
                // If it's grouped, just find the first non-passenger seat one
                foreach (var cockpit in cockpitlist)
                {
                    var definition = MyDefinitionManager.Static.GetCubeBlockDefinition(cockpit.BlockDefinition);

                    if (definition != null && definition is MyShipControllerDefinition && (definition as MyShipControllerDefinition).EnableShipControl)
                    {
                        //if (Globals.Debug)
                        //    MyAPIGateway.Utilities.ShowNotification("Found grouped cockpit: " + cockpit.CustomName, 5000);

                        reference = cockpit;

                        // If this is a main cockpit, stop searching for any others and use this one
                        if (((cockpit as IMyCubeBlock).GetObjectBuilderCubeBlock() as MyObjectBuilder_ShipController).IsMainCockpit)
                        {
                            break;
                        }
                    }
                }
                return(reference);       // If there were any grouped cockpits, never continue looking
            }

            var blocks       = new List <IMySlimBlock>();
            var filterBlocks = new HashSet <IMySlimBlock>();

            // Get a list of cockpit/remote control blocks
            // Might not work with modded cockpits
            (ftl.CubeGrid as IMyCubeGrid).GetBlocks(blocks,
                                                    (x) => x.FatBlock != null &&
                                                    (x.FatBlock.BlockDefinition.TypeId == cockpitObjectBuilder ||
                                                     x.FatBlock.BlockDefinition.TypeId == rcObjectBuilder
                                                    )
                                                    );

            // Loop through and filter by non-passenger
            foreach (var block in blocks)
            {
                var definition = MyDefinitionManager.Static.GetCubeBlockDefinition(block.FatBlock.BlockDefinition);

                if (definition != null && definition is MyShipControllerDefinition && (definition as MyShipControllerDefinition).EnableShipControl)
                {
                    filterBlocks.Add(block);
                }
            }

            //if (Globals.Debug)
            //    MyAPIGateway.Utilities.ShowNotification("Cockpit count: " + filterBlocks.Count);

            if (filterBlocks.Count == 1)
            {
                //if (Globals.Debug)
                //    MyAPIGateway.Utilities.ShowNotification("Found one cockpit: " + filterBlocks[0].FatBlock.DisplayNameText);
                // If we only found one cockpit, use that
                reference = filterBlocks.FirstElement().FatBlock as IMyTerminalBlock;
            }
            else if (filterBlocks.Count > 1)
            {
                foreach (var block in filterBlocks)
                {
                    if (block.FatBlock.DisplayNameText.Contains(tag))
                    {
                        if (Globals.Debug)
                        {
                            MyAPIGateway.Utilities.ShowNotification("Found named cockpit: " + block.FatBlock.DisplayNameText);
                        }
                        reference = block.FatBlock as IMyTerminalBlock;
                        break;
                    }
                    else if (((block.FatBlock as IMyCubeBlock).GetObjectBuilderCubeBlock() as MyObjectBuilder_ShipController).IsMainCockpit)
                    {
                        if (Globals.Debug)
                        {
                            MyAPIGateway.Utilities.ShowNotification("Found main control cockpit: " + block.FatBlock.DisplayNameText);
                        }
                        reference = block.FatBlock as IMyTerminalBlock;
                        break;
                    }
                    else if (((block.FatBlock as IMyCubeBlock).GetObjectBuilderCubeBlock() as MyObjectBuilder_ShipController).ControlThrusters)
                    {
                        if (Globals.Debug)
                        {
                            MyAPIGateway.Utilities.ShowNotification("Found thruster control cockpit: " + block.FatBlock.DisplayNameText);
                        }
                        reference = block.FatBlock as IMyTerminalBlock;
                    }
                }
            }

            return(reference);
        }
        private void AddItemToRepair_Request(MyFixedPoint amount, SerializableDefinitionId blueprintId, long senderEntityId, uint inventoryItemId, MyObjectBuilderType inventoryItemType, MyStringHash inventoryItemSubtypeId)
        {
            if (IsLocked && senderEntityId != m_lockedByEntityId)
                return;

            MyMultiplayer.RaiseEvent(this, x => x.AddItemToRepair_Implementation, amount, blueprintId, inventoryItemId, inventoryItemType, inventoryItemSubtypeId);
        }
예제 #25
0
 public DefinitionIdBlit(MyObjectBuilderType type, MyStringHash subtypeId)
 {
     TypeId    = (MyRuntimeObjectBuilderId)type;
     SubtypeId = subtypeId;
 }
예제 #26
0
 public override bool CanStack(MyObjectBuilderType type, MyStringHash subtypeId, MyItemFlags flags)
 {
     return(false); // weapons shouldn't stack
 }
예제 #27
0
 /// <summary>
 /// register a constructor Action for a block
 /// </summary>
 /// <param name="objBuildType">type of block to create for</param>
 /// <param name="constructor">construcor wrapped in an Action</param>
 private void RegisterForBlock(MyObjectBuilderType objBuildType, Action<IMyCubeBlock> constructor)
 {
     //myLogger.debugLog("Registered for block: " + objBuildType, "RegisterForBlock()", Logger.severity.DEBUG);
     BlockScriptConstructor(objBuildType).Add(constructor);
 }
예제 #28
0
 public MyDefinitionId(MyObjectBuilderType type, MyStringHash subtypeId)
 {
     TypeId    = type;
     SubtypeId = subtypeId;
 }
예제 #29
0
 public MyDefinitionId(MyObjectBuilderType type, string subtypeName) :
     this(type, MyStringHash.GetOrCompute(subtypeName))
 {
 }
예제 #30
0
        public bool DoDamage(float damage, MyStringHash damageType, bool sync, long attackerId)
        {
            if (base.MarkedForClose)
            {
                return(false);
            }
            if (sync)
            {
                if (!Sync.IsServer)
                {
                    return(false);
                }
                MySyncDamage.DoDamageSynced(this, damage, damageType, attackerId);
                return(true);
            }
            MyDamageInformation information = new MyDamageInformation(false, damage, damageType, attackerId);

            if (this.UseDamageSystem)
            {
                MyDamageSystem.Static.RaiseBeforeDamageApplied(this, ref information);
            }
            MyObjectBuilderType typeId = this.Item.Content.TypeId;

            if ((typeId == typeof(MyObjectBuilder_Ore)) || (typeId == typeof(MyObjectBuilder_Ingot)))
            {
                if (this.Item.Amount >= 1)
                {
                    if (Sync.IsServer)
                    {
                        MyFloatingObjects.RemoveFloatingObject(this, (MyFixedPoint)information.Amount);
                    }
                }
                else
                {
                    MyParticleEffect effect;
                    if (MyParticlesManager.TryCreateParticleEffect("Smoke_Construction", base.WorldMatrix, out effect))
                    {
                        effect.UserScale = 0.4f;
                    }
                    if (Sync.IsServer)
                    {
                        MyFloatingObjects.RemoveFloatingObject(this);
                    }
                }
            }
            else
            {
                this.m_health -= 10f * information.Amount;
                if (this.UseDamageSystem)
                {
                    MyDamageSystem.Static.RaiseAfterDamageApplied(this, information);
                }
                if (this.m_health < 0f)
                {
                    MyParticleEffect         effect2;
                    MyPhysicalItemDefinition definition2;
                    if (MyParticlesManager.TryCreateParticleEffect("Smoke_Construction", base.WorldMatrix, out effect2))
                    {
                        effect2.UserScale = 0.4f;
                    }
                    if (Sync.IsServer)
                    {
                        MyFloatingObjects.RemoveFloatingObject(this);
                    }
                    if ((this.Item.Content.SubtypeId == m_explosives) && Sync.IsServer)
                    {
                        BoundingSphere  sphere        = new BoundingSphere((Vector3)base.WorldMatrix.Translation, (((float)this.Item.Amount) * 0.01f) + 0.5f);
                        MyExplosionInfo explosionInfo = new MyExplosionInfo {
                            PlayerDamage                    = 0f,
                            Damage                          = 800f,
                            ExplosionType                   = MyExplosionTypeEnum.WARHEAD_EXPLOSION_15,
                            ExplosionSphere                 = sphere,
                            LifespanMiliseconds             = 700,
                            HitEntity                       = this,
                            ParticleScale                   = 1f,
                            OwnerEntity                     = this,
                            Direction                       = new Vector3?((Vector3)base.WorldMatrix.Forward),
                            VoxelExplosionCenter            = sphere.Center,
                            ExplosionFlags                  = MyExplosionFlags.APPLY_DEFORMATION | MyExplosionFlags.CREATE_SHRAPNELS | MyExplosionFlags.CREATE_PARTICLE_EFFECT | MyExplosionFlags.CREATE_DECALS | MyExplosionFlags.APPLY_FORCE_AND_DAMAGE | MyExplosionFlags.AFFECT_VOXELS | MyExplosionFlags.CREATE_DEBRIS,
                            VoxelCutoutScale                = 0.5f,
                            PlaySound                       = true,
                            ApplyForceAndDamage             = true,
                            ObjectsRemoveDelayInMiliseconds = 40
                        };
                        if (this.Physics != null)
                        {
                            explosionInfo.Velocity = this.Physics.LinearVelocity;
                        }
                        MyExplosions.AddExplosion(ref explosionInfo, true);
                    }
                    if (MyFakes.ENABLE_SCRAP && Sync.IsServer)
                    {
                        if (this.Item.Content.SubtypeId == ScrapBuilder.SubtypeId)
                        {
                            return(true);
                        }
                        if (this.Item.Content.GetId().TypeId == typeof(MyObjectBuilder_Component))
                        {
                            MyComponentDefinition componentDefinition = MyDefinitionManager.Static.GetComponentDefinition((this.Item.Content as MyObjectBuilder_Component).GetId());
                            if (MyRandom.Instance.NextFloat() < componentDefinition.DropProbability)
                            {
                                MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(this.Item.Amount * 0.8f, ScrapBuilder, 1f), base.PositionComp.GetPosition(), base.WorldMatrix.Forward, base.WorldMatrix.Up, null, null);
                            }
                        }
                    }
                    if (((this.ItemDefinition != null) && ((this.ItemDefinition.DestroyedPieceId != null) && Sync.IsServer)) && MyDefinitionManager.Static.TryGetPhysicalItemDefinition(this.ItemDefinition.DestroyedPieceId.Value, out definition2))
                    {
                        MyFloatingObjects.Spawn(definition2, base.WorldMatrix.Translation, base.WorldMatrix.Forward, base.WorldMatrix.Up, this.ItemDefinition.DestroyedPieces, 1f);
                    }
                    if (this.UseDamageSystem)
                    {
                        MyDamageSystem.Static.RaiseDestroyed(this, information);
                    }
                }
            }
            return(true);
        }
예제 #31
0
 public T CreateNewObject <T>(MyObjectBuilderType typeId, string subtypeId)
     where T : MyObjectBuilder_Base
 {
     return((T)MyObjectBuilderSerializer.CreateNewObject(typeId, subtypeId));
 }
예제 #32
0
		protected Disruption(IMyCubeGrid grid, MyObjectBuilderType[] affects)
		{
			m_logger = new Logger(GetType().Name, () => grid.DisplayName);
			m_cache = CubeGridCache.GetFor(grid);
			m_affects = affects;
		}
예제 #33
0
 public MySessionComponentDescriptor(MyUpdateOrder updateOrder, int priority, Type type)
 {
     UpdateOrder       = updateOrder;
     Priority          = priority;
     ObjectBuilderType = type;
 }
예제 #34
0
 public MyDefinitionId(MyObjectBuilderType type) :
     this(type, MyStringHash.GetOrCompute(null))
 {
 }
 public static Type TryGetMappedSessionComponentType(MyObjectBuilderType objectBuilderType)
 {
     Type output = null;
     m_typeByObjectBuilderType.TryGetValue(objectBuilderType, out output);
     return output;
 }
예제 #36
0
 public static MyComponentBase CreateInstanceByTypeId(MyObjectBuilderType type)
 {
     return(m_objectFactory.CreateInstance(type));
 }
 public MySessionComponentDescriptor(MyUpdateOrder updateOrder, int priority, Type type)
 {
     UpdateOrder = updateOrder;
     Priority = priority;
     ObjectBuilderType = type;
 }
예제 #38
0
 public static Type GetCreatedInstanceType(MyObjectBuilderType type)
 {
     return(m_objectFactory.GetProducedType(type));
 }
예제 #39
0
 public void Set(MyObjectBuilderType? itemTypeId)
 {
     Clear();
     m_obType = itemTypeId;
 }
 public MyInventoryConstraint RemoveObjectBuilderType(MyObjectBuilderType type)
 {
     m_constrainedTypes.Remove(type);
     UpdateIcon();
     return(this);
 }
 private void VerifyInputItemType(MyObjectBuilderType inputType)
 {
     foreach (var item in Prerequisites)
         MyDebug.AssertDebug(inputType == item.Id.TypeId, "Not all input objects are of same type. Is this on purpose?");
 }
예제 #42
0
        public MyGlobalEventHandler(Type objectBuilderType, string subtypeName)
        {
            MyObjectBuilderType type = objectBuilderType;

            EventDefinitionId = new MyDefinitionId(type, subtypeName);
        }
예제 #43
0
 public static MyComponentBase CreateInstanceByTypeId(MyObjectBuilderType type)
 {
     return m_objectFactory.CreateInstance(type);
 }
예제 #44
0
        protected override void Init(MyObjectBuilder_DefinitionBase builder)
        {
            base.Init(builder);

            var definitionBuilder = (builder as MyObjectBuilder_ContainerDefinition);

            Flags = definitionBuilder.Flags;

            if (definitionBuilder.DefaultComponents != null && definitionBuilder.DefaultComponents.Length > 0)
            {
                if (DefaultComponents == null)
                {
                    DefaultComponents = new List <DefaultComponent>();
                }
                foreach (var component in definitionBuilder.DefaultComponents)
                {
                    DefaultComponent defComponent = new DefaultComponent();

                    try
                    {
                        if (component.BuilderType != null)
                        {
                            MyObjectBuilderType obType;
                            obType = MyObjectBuilderType.Parse(component.BuilderType);
                            defComponent.BuilderType = obType;
                        }
                    }
                    catch (Exception)
                    {
                        System.Diagnostics.Debug.Fail(String.Format("Can not parse defined component builder type {0} for container {1}", component.BuilderType.ToString(), Id.ToString()));
                        MyLog.Default.WriteLine(String.Format("Container definition error: can not parse defined component type {0} for container {1}", component, Id.ToString()));
                    }

                    try
                    {
                        if (component.InstanceType != null)
                        {
                            Type runtimeType = Type.GetType(component.InstanceType, true);
                            defComponent.InstanceType = runtimeType;
                        }
                    }
                    catch (Exception)
                    {
                        System.Diagnostics.Debug.Fail(String.Format("Can not parse defined component instance type {0} for container {1}", component.InstanceType.ToString(), Id.ToString()));
                        MyLog.Default.WriteLine(String.Format("Container definition error: can not parse defined component type {0} for container {1}", component, Id.ToString()));
                    }

                    defComponent.ForceCreate = component.ForceCreate;

                    if (component.SubtypeId != null)
                    {
                        defComponent.SubtypeId = MyStringHash.GetOrCompute(component.SubtypeId);
                    }

                    if (defComponent.IsValid())
                    {
                        DefaultComponents.Add(defComponent);
                    }
                    else
                    {
                        System.Diagnostics.Debug.Fail(String.Format("Defined component {0} for container {1} is invalid, none builder type or instance type is defined! Skipping it.", component, Id.ToString()));
                        MyLog.Default.WriteLine(String.Format("Defined component {0} for container {1} is invalid, none builder type or instance type is defined! Skipping it.", component, Id.ToString()));
                    }
                }
            }
        }
        private bool IsItemInInventory(uint itemId, MyObjectBuilderType objectBuilderType, MyStringHash subtypeId)
        {
            var inventory = (Entity as MyEntity).GetInventory();

            if (inventory == null)
            {
                System.Diagnostics.Debug.Fail("Inventory was not found on the entity while trying to repair item in it!");
                return false;
            }

            var item = inventory.GetItemByID(itemId);

            System.Diagnostics.Debug.Assert(item != null, "Item being repaired wasn't found by its Id in inventory");

            if (item.HasValue && item.Value.Content != null)
            {
                return item.Value.Content.TypeId == objectBuilderType && item.Value.Content.SubtypeId == subtypeId;
            }

            return false;
        }
예제 #46
0
        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 void AddItemToRepair(MyFixedPoint amount, MyBlueprintDefinitionBase blueprint, long senderEntityId, uint inventoryItemId, MyObjectBuilderType inventoryItemType, MyStringHash inventoryItemSubtypeId)
 {
     SerializableDefinitionId blueprintId = blueprint.Id;
     MyMultiplayer.RaiseEvent(this, x => x.AddItemToRepair_Request, amount, blueprintId, senderEntityId, inventoryItemId, inventoryItemType, inventoryItemSubtypeId);
 }
예제 #48
0
 public static Type GetProducedType(MyObjectBuilderType objectBuilderType)
 {
     return(m_objectFactory.GetProducedType(objectBuilderType));
 }
        private void AddItemToRepair_Implementation(MyFixedPoint amount, SerializableDefinitionId blueprintId, uint inventoryItemId, MyObjectBuilderType inventoryItemType, MyStringHash inventoryItemSubtypeId)
        {
            System.Diagnostics.Debug.Assert(amount > 0, "Adding zero or negative amount!");

            MyBlueprintDefinitionBase blueprint = MyDefinitionManager.Static.GetBlueprintDefinition(blueprintId);

            if (blueprint == null)
            {
                System.Diagnostics.Debug.Fail("Couldn't find blueprint definition for: " + blueprintId);
                return;
            }

            Predicate<MyBlueprintToProduce> condition = x => (x is MyRepairBlueprintToProduce) && 
                                                             (x as MyRepairBlueprintToProduce).Blueprint == blueprint &&
                                                             (x as MyRepairBlueprintToProduce).InventoryItemId == inventoryItemId &&
                                                             (x as MyRepairBlueprintToProduce).InventoryItemType == inventoryItemType &&
                                                             (x as MyRepairBlueprintToProduce).InventoryItemSubtypeId == inventoryItemSubtypeId;
            MyRepairBlueprintToProduce itemToProduce = m_itemsToProduce.Find(condition) as MyRepairBlueprintToProduce;
            if (itemToProduce != null)
            {
                itemToProduce.Amount = itemToProduce.Amount + amount;
            }
            else
            {
                itemToProduce = new MyRepairBlueprintToProduce(amount, blueprint, inventoryItemId, inventoryItemType, inventoryItemSubtypeId);
                m_itemsToProduce.Add(itemToProduce);                
            }

            var handler = ProductionChanged;
            if (handler != null)
            {
                handler(this, itemToProduce);
            }
        }
예제 #50
0
        public override void ProcessServer()
        {
            EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Buy started by Steam Id '{0}'.", SenderSteamId);

            // Get player steam ID
            var buyingPlayer = MyAPIGateway.Players.FindPlayerBySteamId(SenderSteamId);

            MyPhysicalItemDefinition definition = null;
            MyObjectBuilderType      result;

            if (MyObjectBuilderType.TryParse(ItemTypeId, out result))
            {
                var id = new MyDefinitionId(result, ItemSubTypeName);
                MyDefinitionManager.Static.TryGetPhysicalItemDefinition(id, out definition);
            }

            if (definition == null)
            {
                // Someone hacking, and passing bad data?
                MessageClientTextMessage.SendMessage(SenderSteamId, "BUY", "Sorry, the item you specified doesn't exist!");
                EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Buy aborted by Steam Id '{0}' -- item doesn't exist.", SenderSteamId);
                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, "BUY", "You must provide a whole number for the quantity to buy that item.");
                    EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Buy aborted by Steam Id '{0}' -- invalid qantity.", SenderSteamId);
                    return;
                }
                //ItemQuantity = Math.Round(ItemQuantity, 0);  // Or do we just round the number?
            }

            if (ItemQuantity <= 0)
            {
                MessageClientTextMessage.SendMessage(SenderSteamId, "BUY", "You must provide a valid quantity to buy.");
                EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Buy aborted by Steam Id '{0}' -- invalid qantity.", SenderSteamId);
                return;
            }

            // Who are we buying to?
            BankAccountStruct accountToSell;

            if (BuyFromMerchant)
            {
                accountToSell = AccountManager.FindAccount(EconomyConsts.NpcMerchantId);
            }
            else
            {
                accountToSell = AccountManager.FindAccount(FromUserName);
            }

            if (accountToSell == null)
            {
                MessageClientTextMessage.SendMessage(SenderSteamId, "BUY", "Sorry, player does not exist or have an account!");
                EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Buy aborted by Steam Id '{0}' -- no account.", SenderSteamId);
                return;
            }

            if (MarketManager.IsItemBlacklistedOnServer(ItemTypeId, ItemSubTypeName))
            {
                MessageClientTextMessage.SendMessage(SenderSteamId, "BUY", "Sorry, the item you tried to buy is blacklisted on this server.");
                EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Buy aborted by Steam Id '{0}' -- item blacklisted.", SenderSteamId);
                return;
            }

            // Get the player's inventory, regardless of if they are in a ship, or a remote control cube.
            var character = buyingPlayer.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, "BUY", "You are dead. You cannot trade while dead.");
                EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Buy 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 = buyingPlayer.Identity();
            //MyAPIGateway.Utilities.ShowMessage("CHECK", "Is Dead: {0}", identity.IsDead);

            //if (identity.IsDead)
            //{
            //    MessageClientTextMessage.SendMessage(SenderSteamId, "BUY", "You are dead. You cannot trade while dead.");
            //    return;
            //}

            var position = ((IMyEntity)character).WorldMatrix.Translation;

            MarketItemStruct marketItem = null;

            if (BuyFromMerchant || UseBankSellPrice)
            {
                var markets = MarketManager.FindMarketsFromLocation(position);
                if (markets.Count == 0)
                {
                    MessageClientTextMessage.SendMessage(SenderSteamId, "BUY", "Sorry, your are not in range of any markets!");
                    EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Buy aborted by Steam Id '{0}' -- no market in range.", SenderSteamId);
                    return;
                }

                // TODO: find market with best Sell price that isn't blacklisted.

                var market = markets.FirstOrDefault();
                if (market == null)
                {
                    MessageClientTextMessage.SendMessage(SenderSteamId, "BUY", "Sorry, the market you are accessing does not exist!");
                    EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Buy aborted by Steam Id '{0}' -- no market found.", SenderSteamId);
                    return;
                }

                marketItem = market.MarketItems.FirstOrDefault(e => e.TypeId == ItemTypeId && e.SubtypeName == ItemSubTypeName);
                if (marketItem == null)
                {
                    MessageClientTextMessage.SendMessage(SenderSteamId, "BUY", "Sorry, the items you are trying to buy 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, "BUY", "Sorry, the item you tried to buy is blacklisted in this market.");
                    EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Buy aborted by Steam Id '{0}' -- item is blacklisted in market.", 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.

                if (UseBankSellPrice)
                {
                    // The player is buying, but the *Market* will *sell* it to the player at this price.
                    ItemPrice = marketItem.SellPrice;
                }
            }

            var accountToBuy      = AccountManager.FindOrCreateAccount(SenderSteamId, SenderDisplayName, SenderLanguage);
            var transactionAmount = ItemPrice * ItemQuantity;

            // need fix negative amounts before checking if the player can afford it.
            if (!buyingPlayer.IsAdmin())
            {
                transactionAmount = Math.Abs(transactionAmount);
            }

            // TODO: admin check on ability to afford it?
            //[maybe later, our pay and reset commands let us steal money from npc anyway best to keep admin abuse features to minimum]
            //[we could put an admin check on blacklist however, allow admins to spawn even blacklisted gear]
            if (accountToBuy.BankBalance < transactionAmount)
            {
                MessageClientTextMessage.SendMessage(SenderSteamId, "BUY", "Sorry, you cannot afford {0} {1}!", transactionAmount, EconomyScript.Instance.Config.CurrencyName);
                EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Buy aborted by Steam Id '{0}' -- not enough money.", SenderSteamId);
                return;
            }

            if (BuyFromMerchant) // and supply is not exhausted, or unlimited mode is not on.
                                 //This is a quick fix, ideally it should do a partial buy of what is left and post a buy offer for remainder
            {
                // here we look up item price and transfer items and money as appropriate
                if (marketItem.Quantity >= ItemQuantity || !EconomyScript.Instance.Config.LimitedSupply)
                {
                    marketItem.Quantity -= ItemQuantity; // reduce Market content.
                    EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Buy finalizing by Steam Id '{0}' -- adding to inventory.", SenderSteamId);
                    var remainingToCollect = MessageSell.AddToInventories(buyingPlayer, ItemQuantity, definition.Id);

                    //EconomyScript.Instance.Config.LimitedSupply

                    accountToSell.BankBalance += transactionAmount;
                    accountToSell.Date         = DateTime.Now;

                    accountToBuy.BankBalance -= transactionAmount;
                    accountToBuy.Date         = DateTime.Now;
                    MessageClientTextMessage.SendMessage(SenderSteamId, "BUY", "You just purchased {1} '{2}' for {0} {3}", transactionAmount, ItemQuantity, definition.GetDisplayName(), EconomyScript.Instance.Config.CurrencyName);

                    if (remainingToCollect > 0)
                    {
                        MarketManager.CreateStockHeld(buyingPlayer.SteamUserId, ItemTypeId, ItemSubTypeName, remainingToCollect, ItemPrice);
                        // TODO: there should be a common command to collect items. Not use /sell.
                        MessageClientTextMessage.SendMessage(SenderSteamId, "BUY", "There are {0} remaining to collect. Use '/sell collect'", remainingToCollect);
                    }
                    EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Buy complete by Steam Id '{0}' -- items bought.", SenderSteamId);
                }
                else
                {
                    MessageClientTextMessage.SendMessage(SenderSteamId, "BUY", "There isn't '{0}' of {1} available to purchase! Only {2} available to buy!", ItemQuantity, definition.GetDisplayName(), marketItem.Quantity);
                    EconomyScript.Instance.ServerLogger.WriteVerbose("Action /Buy aborted by Steam Id '{0}' -- not enough stock.", SenderSteamId);
                }

                return;
            }
            else if (FindOnMarket)
            {
                // TODO: Here we find the best offer on the zone market

                return;
            }
            else
            {
                // is it a player then?
                if (accountToSell.SteamId == buyingPlayer.SteamUserId)
                {
                    MessageClientTextMessage.SendMessage(SenderSteamId, "BUY", "Sorry, you cannot buy from yourself!");
                    return;
                }

                // check if selling player is online and in range?
                var payingPlayer = MyAPIGateway.Players.FindPlayerBySteamId(accountToSell.SteamId);

                if (EconomyScript.Instance.Config.LimitedRange && !Support.RangeCheck(buyingPlayer, payingPlayer))
                {
                    MessageClientTextMessage.SendMessage(SenderSteamId, "BUY", "Sorry, you are not in range of that player!");
                    return;
                }

                if (payingPlayer == null)
                {
                    // TODO: other player offline.
                }
                else
                {
                    // TODO: other player is online.
                }
            }

            // this is a fall through from the above conditions not yet complete.
            MessageClientTextMessage.SendMessage(SenderSteamId, "BUY", "Not yet complete.");
        }
 public MyRepairBlueprintToProduce TryGetItemToRepair(uint inventoryItemId, MyObjectBuilderType inventoryItemType, MyStringHash inventoryItemSubtypeId)
 {
     return m_itemsToProduce.Find(x =>
         (x is MyRepairBlueprintToProduce) &&
         (x as MyRepairBlueprintToProduce).InventoryItemId == inventoryItemId &&
         (x as MyRepairBlueprintToProduce).InventoryItemType == inventoryItemType &&
         (x as MyRepairBlueprintToProduce).InventoryItemSubtypeId == inventoryItemSubtypeId) as MyRepairBlueprintToProduce;
 }
예제 #52
0
        public static MyObjectBuilder_CubeBlock Upgrade(MyObjectBuilder_CubeBlock cubeBlock, MyObjectBuilderType newType, string newSubType)
        {
            var upgraded = MyObjectBuilderSerializer.CreateNewObject(newType, newSubType) as MyObjectBuilder_CubeBlock;

            if (upgraded == null)
            {
                Debug.Fail("Cannot upgrade cube block, upgraded block is not derived from " + typeof(MyObjectBuilder_CubeBlock).Name);
                return(null);
            }

            upgraded.EntityId              = cubeBlock.EntityId;
            upgraded.Min                   = cubeBlock.Min;
            upgraded.m_orientation         = cubeBlock.m_orientation;
            upgraded.IntegrityPercent      = cubeBlock.IntegrityPercent;
            upgraded.BuildPercent          = cubeBlock.BuildPercent;
            upgraded.BlockOrientation      = cubeBlock.BlockOrientation;
            upgraded.ConstructionInventory = cubeBlock.ConstructionInventory;
            upgraded.ColorMaskHSV          = cubeBlock.ColorMaskHSV;

            return(upgraded);
        }
예제 #53
0
 /// <summary>
 /// Gets the constructor list mapped to a MyObjectBuilderType
 /// </summary>
 private List<Action<IMyCubeBlock>> BlockScriptConstructor(MyObjectBuilderType objBuildType)
 {
     List<Action<IMyCubeBlock>> scripts;
     if (!AllBlockScriptConstructors.TryGetValue(objBuildType, out scripts))
     {
         scripts = new List<Action<IMyCubeBlock>>();
         AllBlockScriptConstructors.Add(objBuildType, scripts);
     }
     return scripts;
 }
        public void AddItemToRepair(MyFixedPoint amount, MyBlueprintDefinitionBase blueprint, long senderEntityId, uint inventoryItemId, MyObjectBuilderType inventoryItemType, MyStringHash inventoryItemSubtypeId)
        {
            SerializableDefinitionId blueprintId = blueprint.Id;

            MyMultiplayer.RaiseEvent(this, x => x.AddItemToRepair_Request, amount, blueprintId, senderEntityId, inventoryItemId, inventoryItemType, inventoryItemSubtypeId);
        }
예제 #55
0
 public MyInventoryConstraint RemoveObjectBuilderType(MyObjectBuilderType type)
 {
     m_constrainedTypes.Remove(type);
     UpdateIcon();
     return this;
 }
        private void AddItemToRepair_Request(MyFixedPoint amount, SerializableDefinitionId blueprintId, long senderEntityId, uint inventoryItemId, MyObjectBuilderType inventoryItemType, MyStringHash inventoryItemSubtypeId)
        {
            if (IsLocked && senderEntityId != m_lockedByEntityId)
            {
                return;
            }

            MyMultiplayer.RaiseEvent(this, x => x.AddItemToRepair_Implementation, amount, blueprintId, inventoryItemId, inventoryItemType, inventoryItemSubtypeId);
        }
예제 #57
0
        private MyDefinitionId GetBackwardCompatibleDefinitionId(MyObjectBuilderType typeId)
        {
            if (typeId == typeof(MyObjectBuilder_LargeGatlingTurret))
                return new MyDefinitionId(typeof(MyObjectBuilder_WeaponDefinition), "LargeGatlingTurret");
            else if (typeId == typeof(MyObjectBuilder_LargeMissileTurret))
                return new MyDefinitionId(typeof(MyObjectBuilder_WeaponDefinition), "LargeMissileTurret");
            else if (typeId == typeof(MyObjectBuilder_InteriorTurret))
                return new MyDefinitionId(typeof(MyObjectBuilder_WeaponDefinition), "LargeInteriorTurret");
            else if (typeId == typeof(MyObjectBuilder_SmallMissileLauncher)
                || typeId == typeof(MyObjectBuilder_SmallMissileLauncherReload))
                return new MyDefinitionId(typeof(MyObjectBuilder_WeaponDefinition), "SmallMissileLauncher");
            else if (typeId == typeof(MyObjectBuilder_SmallGatlingGun))
                return new MyDefinitionId(typeof(MyObjectBuilder_WeaponDefinition), "GatlingGun");

            return new MyDefinitionId();
        }
        private void AddItemToRepair_Implementation(MyFixedPoint amount, SerializableDefinitionId blueprintId, uint inventoryItemId, MyObjectBuilderType inventoryItemType, MyStringHash inventoryItemSubtypeId)
        {
            System.Diagnostics.Debug.Assert(amount > 0, "Adding zero or negative amount!");

            MyBlueprintDefinitionBase blueprint = MyDefinitionManager.Static.GetBlueprintDefinition(blueprintId);

            if (blueprint == null)
            {
                System.Diagnostics.Debug.Fail("Couldn't find blueprint definition for: " + blueprintId);
                return;
            }

            Predicate <MyBlueprintToProduce> condition = x => (x is MyRepairBlueprintToProduce) &&
                                                         (x as MyRepairBlueprintToProduce).Blueprint == blueprint &&
                                                         (x as MyRepairBlueprintToProduce).InventoryItemId == inventoryItemId &&
                                                         (x as MyRepairBlueprintToProduce).InventoryItemType == inventoryItemType &&
                                                         (x as MyRepairBlueprintToProduce).InventoryItemSubtypeId == inventoryItemSubtypeId;
            MyRepairBlueprintToProduce itemToProduce = m_itemsToProduce.Find(condition) as MyRepairBlueprintToProduce;

            if (itemToProduce != null)
            {
                itemToProduce.Amount = itemToProduce.Amount + amount;
            }
            else
            {
                itemToProduce = new MyRepairBlueprintToProduce(amount, blueprint, inventoryItemId, inventoryItemType, inventoryItemSubtypeId);
                m_itemsToProduce.Add(itemToProduce);
            }

            var handler = ProductionChanged;

            if (handler != null)
            {
                handler(this, itemToProduce);
            }
        }
 public MyRepairBlueprintToProduce(MyFixedPoint amount, MyBlueprintDefinitionBase blueprint, uint inventoryItemId, MyObjectBuilderType inventoryItemType, MyStringHash inventoryItemSubtypeId) : base(amount, blueprint)
 {
     System.Diagnostics.Debug.Assert(Blueprint is MyRepairBlueprintDefinition, "MyRepairBlueprintToProduce class should be used together with blueprints type of MyRepairBlueprintDefinition only!");
     InventoryItemId        = inventoryItemId;
     InventoryItemType      = inventoryItemType;
     InventoryItemSubtypeId = inventoryItemSubtypeId;
 }
예제 #60
0
 public static MyDefinitionBase GetDefinition(this MyDefinitionManager definitionManager, MyObjectBuilderType typeId, string subTypeId)
 {
     return(definitionManager.GetAllDefinitions().FirstOrDefault(e => e.Id.TypeId == typeId && e.Id.SubtypeName == subTypeId));
 }