Exemple #1
0
            static public string GetType(MyProductionItem production_item)
            {
                MyDefinitionId itemDefinitionId;
                string         subtypeName = production_item.BlueprintId.SubtypeName;
                string         typeName    = Util.GetName(production_item);

                if ((subtypeName.EndsWith("Rifle") || subtypeName.StartsWith("Welder") || subtypeName.StartsWith("HandDrill") || subtypeName.StartsWith("AngleGrinder")) &&
                    MyDefinitionId.TryParse("MyObjectBuilder_PhysicalGunObject", typeName, out itemDefinitionId))
                {
                    return(itemDefinitionId.TypeId.ToString());
                }
                if (subtypeName.StartsWith("Hydrogen") && MyDefinitionId.TryParse("MyObjectBuilder_GasContainerObject", typeName, out itemDefinitionId))
                {
                    return(itemDefinitionId.TypeId.ToString());
                }
                if (subtypeName.StartsWith("Oxygen") && MyDefinitionId.TryParse("MyObjectBuilder_OxygenContainerObject", typeName, out itemDefinitionId))
                {
                    return(itemDefinitionId.TypeId.ToString());
                }
                if ((subtypeName.Contains("Missile") || subtypeName.EndsWith("Magazine")) && MyDefinitionId.TryParse("MyObjectBuilder_AmmoMagazine", typeName, out itemDefinitionId))
                {
                    return(itemDefinitionId.TypeId.ToString());
                }
                if (MyDefinitionId.TryParse("MyObjectBuilder_Component", typeName, out itemDefinitionId))
                {
                    return(itemDefinitionId.TypeId.ToString());
                }
                return(production_item.BlueprintId.TypeId.ToString());
            }
        void ProcessProjection(IMyAssembler assembler, IMyProjector projector, bool allBlocks)
        {
            var queueDictionary = GetBlocksForQueue(projector, allBlocks);

            if (allBlocks == false)
            {
                var existingParts = GetExistingParts(assembler);

                foreach (var component in existingParts.Keys.Where(component => queueDictionary.ContainsKey(component)))
                {
                    if (existingParts[component] >= queueDictionary[component])
                    {
                        queueDictionary[component] = 0;
                    }
                    else
                    {
                        queueDictionary[component] -= existingParts[component];
                    }
                }
            }

            foreach (var component in queueDictionary.Keys.Where(component => blueprintDictionary.ContainsKey(component)))
            {
                var blueprint  = new MyDefinitionId();
                var definition = $"MyObjectBuilder_BlueprintDefinition/{blueprintDictionary[component]}";

                if (MyDefinitionId.TryParse(definition, out blueprint) && assembler.CanUseBlueprint(blueprint))
                {
                    assembler.AddQueueItem(blueprint, (MyFixedPoint)queueDictionary[component]);
                }
            }
        }
Exemple #3
0
        public static MyDefinitionId MockBlueprint(String itemId)
        {
            MyDefinitionId definition;

            MyDefinitionId.TryParse("MyObjectBuilder_BlueprintDefinition", itemId, out definition);
            return(definition);
        }
Exemple #4
0
        static MyDefinitionId?CreateBlueprint(string name)
        {
            switch (name)
            {
            case "RadioCommunication":
            case "Computer":
            case "Reactor":
            case "Detector":
            case "Construction":
            case "Thrust":
            case "Motor":
            case "Explosives":
            case "Girder":
            case "GravityGenerator":
            case "Medical": name += "Component"; break;

            case "NATO_25x184mm":
            case "NATO_5p56x45mm": name += "Magazine"; break;
            }
            MyDefinitionId id;

            if (MyDefinitionId.TryParse("MyObjectBuilder_BlueprintDefinition/" + name, out id) && (id.SubtypeId != null))
            {
                return(id);
            }
            else
            {
                return(null);
            }
        }
Exemple #5
0
        public void DeliverContract()
        {
            Contract      contract        = TruckingPlugin.getActiveContract(Context.Player.SteamUserId);
            StringBuilder contractDetails = new StringBuilder();

            if (contract != null)
            {
                Vector3D coords   = contract.GetDeliveryLocation().Coords;
                float    distance = Vector3.Distance(coords, Context.Player.Character.PositionComp.GetPosition());
                if (distance <= 1000)
                {
                    List <VRage.ModAPI.IMyEntity> l = new List <VRage.ModAPI.IMyEntity>();

                    BoundingSphereD sphere = new BoundingSphereD(Context.Player.Character.PositionComp.GetPosition(), 1000);
                    l = MyAPIGateway.Entities.GetEntitiesInSphere(ref sphere);

                    Dictionary <MyDefinitionId, int> itemsToRemove = new Dictionary <MyDefinitionId, int>();
                    int pay = 0;
                    foreach (ContractItems item in contract.getItemsInContract())
                    {
                        if (MyDefinitionId.TryParse("MyObjectBuilder_" + item.ItemType, item.SubType, out MyDefinitionId id))
                        {
                            itemsToRemove.Add(id, item.AmountToDeliver);
                            pay += item.AmountToDeliver * item.GetPrice();
                        }
                        else
                        {
                            Context.Respond("Theres an error in the config for this item, report in a ticket " + id.SubtypeName + " " + id.TypeId);
                        }
                    }

                    foreach (IMyEntity entity in l)
                    {
                        if (entity is MyCubeGrid grid)
                        {
                            List <VRage.Game.ModAPI.IMyInventory> inventories = TakeTheItems.GetInventories(grid);
                            if (FacUtils.IsOwnerOrFactionOwned(grid, Context.Player.IdentityId, true))
                            {
                                if (TakeTheItems.ConsumeComponents(inventories, itemsToRemove, Context.Player.SteamUserId))
                                {
                                    MyBankingSystem.ChangeBalance(Context.Player.Identity.IdentityId, pay);
                                    Database.RemoveContract(Context.Player.SteamUserId, true, contract, Context.Player.IdentityId);
                                    TruckingPlugin.SendMessage("The Boss", "Contract Complete, Payment delivered to bank account.", Color.Purple, Context.Player.SteamUserId);
                                    return;
                                }
                            }
                        }
                    }
                    Context.Respond("Could not find owned grid in vicinity with the required items.", "The Boss");
                }
                else
                {
                    Context.Respond("You arent close enough to the delivery point! Must be within 1km of signal", "The Boss");
                }
            }
            else
            {
                Context.Respond("You dont have an active contract.", "The Boss");
            }
        }
        private void OnExtraCompSubmit(string s)
        {
            if (string.IsNullOrWhiteSpace(s))
            {
                config.ExtraComponent = null;
                return;
            }

            string[] args = s.Trim().Split(new[] { ' ', '/' }, StringSplitOptions.RemoveEmptyEntries);
            if (args.Length != 2)
            {
                return;
            }

            string typeId = args[0];

            if (!typeId.StartsWith("MyObjectBuilder_"))
            {
                typeId = "MyObjectBuilder_" + typeId;
            }
            string subtypeId = args[1];

            MyDefinitionId           id;
            MyPhysicalItemDefinition comp;

            if (MyDefinitionId.TryParse(typeId, subtypeId, out id) && MyDefinitionManager.Static.TryGetPhysicalItemDefinition(id, out comp))
            {
                config.ExtraComponent = id;
            }
        }
 public void loadFromString()
 {
     foreach (KeyValuePair <String, int> key in componentsString)
     {
         MyDefinitionId.TryParse(key.Key, out MyDefinitionId temp);
         components.Add(temp, key.Value);
     }
 }
            public Target(String t, long a, String r)
            {
                target = new MyItemType(objectType, t);
                recipe = new MyDefinitionId();
                bool _ = MyDefinitionId.TryParse("MyObjectBuilder_BlueprintDefinition", r, out recipe);

                amount = fromLong(a);
            }
Exemple #9
0
        public static MyDefinitionId DefinitionFromString(string definition)
        {
            if (string.IsNullOrWhiteSpace(definition) || definition.Contains("(null)"))
            {
                throw new UnknownItemException("<Empty definition>");
            }

            definition = "MyObjectBuilder_" + definition;

            var            input = definition.Trim();
            MyDefinitionId foundDefinitionId;

            if (MyDefinitionId.TryParse(input, out foundDefinitionId))
            {
                return(foundDefinitionId);
            }

            Type   objectBuilder;
            string subType = input;

            if (input.EndsWith("Ore", StringComparison.InvariantCultureIgnoreCase))
            {
                objectBuilder = typeof(MyObjectBuilder_Ore);
                subType       = subType.Substring(0, subType.Length - 3);
            }
            else if (input.EndsWith("Ingot", StringComparison.InvariantCultureIgnoreCase))
            {
                objectBuilder = typeof(MyObjectBuilder_Ingot);
                subType       = subType.Substring(0, subType.Length - 5);
            }
            else if (input.Equals("Stone", StringComparison.InvariantCultureIgnoreCase))
            {
                objectBuilder = typeof(MyObjectBuilder_Ore);
                subType       = "Stone";
            }
            else
            {
                objectBuilder = typeof(MyObjectBuilder_Component);
            }


            var definitionId = new MyDefinitionId(objectBuilder, subType);

            if (!MyDefinitionManager.Static.GetAllDefinitions().Any(d => d.Id.Equals(definitionId)))
            {
                definitionId = new MyDefinitionId(typeof(MyObjectBuilder_PhysicalGunObject), subType);
                if (MyDefinitionManager.Static.GetAllDefinitions().Any(d => d.Id.Equals(definitionId)))
                {
                    return(definitionId);
                }

                throw new UnknownItemException(definitionId);
            }


            return(definitionId);
        }
Exemple #10
0
        internal void LoadData()
        {
            if (Entity.Storage == null)
            {
                // DebugLog.Write("storage is null, exiting loadData().");
                return;
            }
            string Data;

            if (Entity.Storage.TryGetValue(FilterStateGUID, out Data))
            {
                // DebugLog.Write(Data);
                Filterdata loadedfilterdata = new Filterdata();

                var base64 = Convert.FromBase64String(Data);
                loadedfilterdata = MyAPIGateway.Utilities.SerializeFromBinary <Filterdata>(base64);
                // DebugLog.Write($"loaded id: {loadedfilterdata.id}");
                if (loadedfilterdata.id == MyCargoContainer.EntityId)
                {
                    // DebugLog.Write($"Saved state found (id: {loadedfilterdata.id})");
                    MyInventory inventory = (MyInventory)MyCargoContainer.GetInventory();
                    if (loadedfilterdata.FilterItems != null)
                    {
                        for (int i = 0; i < loadedfilterdata.FilterItems.Count(); i++)
                        {
                            // DebugLog.Write($"{loadedfilterdata.FilterItems[i].DisplayName}");
                            FilterController.FilterList.Add(loadedfilterdata.FilterItems[i]);
                            if (loadedfilterdata.FilterItems[i].Type == FilterType.FILTER_TYPE)
                            {
                                MyObjectBuilderType type;
                                if (MyObjectBuilderType.TryParse(loadedfilterdata.FilterItems[i].ParseItem, out type) == true)
                                {
                                    inventory.Constraint.AddObjectBuilderType(type);
                                }
                            }
                            else if (loadedfilterdata.FilterItems[i].Type == FilterType.FILTER_ITEM)
                            {
                                MyDefinitionId Id;
                                if (MyDefinitionId.TryParse(loadedfilterdata.FilterItems[i].ParseItem, out Id) == true)
                                {
                                    inventory.Constraint.Add(Id);
                                }
                            }
                        }
                    }
                    inventory.Constraint.IsWhitelist = loadedfilterdata.FilterMode;
                    FilterController.FilterMode      = loadedfilterdata.FilterMode;
                    inventory.Constraint.Icon        = null;
                }
                else
                {
                    // DebugLog.Write($"Id mismatch - Entity Id: {Entity.EntityId}  MyCargoContainerId: {MyCargoContainer.EntityId}");
                }
            }
        }
        public static UpgradeCost LoadUpgradeCost(string path)
        {
            if (!File.Exists(path))
            {
                return(null);
            }
            UpgradeCost cost = new UpgradeCost();

            String[] line;
            line          = File.ReadAllLines(path);
            cost.id       = int.Parse(line[0].Split(',')[0]);
            cost.type     = line[0].Split(',')[1];
            cost.NewLevel = float.Parse(line[0].Split(',')[2]);
            for (int i = 2; i < line.Length; i++)
            {
                String[] split = line[i].Split(',');
                foreach (String s in split)
                {
                    s.Replace(" ", "");
                }
                if (split[0].ToLower().Contains("metapoints"))
                {
                    cost.MetaPointCost += int.Parse(split[1]);
                }
                if (split[0].ToLower().Contains("money"))
                {
                    cost.MoneyRequired += int.Parse(split[1]);
                }
                else
                {
                    if (MyDefinitionId.TryParse(split[0], split[1], out MyDefinitionId id))
                    {
                        if (cost.itemsRequired.ContainsKey(id))
                        {
                            cost.itemsRequired[id] += int.Parse(split[2]);
                        }
                        else
                        {
                            cost.itemsRequired.Add(id, int.Parse(split[2]));
                        }
                    }
                }
            }
            switch (cost.type.ToLower())
            {
            case "slots":
                slotUpgrades.Add(cost.id, cost);
                break;

            default:
                AlliancePlugin.Log.Error("Upgrade file has no defined type");
                break;
            }
            return(cost);
        }
Exemple #12
0
 bool tryAddAssemblerTask(IMyProductionBlock assembler, string definition, VRage.MyFixedPoint count)
 {
     try {
         MyDefinitionId objectIdToAdd = new MyDefinitionId();
         MyDefinitionId.TryParse(definition, out objectIdToAdd);
         assembler.AddQueueItem(objectIdToAdd, count);
         return(true);
     } catch (Exception e) {
         return(false);
     }
 }
        void AddBlueprintItems(String[] words, String blueprintId, params ItemFilter[] filters)
        {
            AddItems(words, filters);
            MyDefinitionId definition;

            MyDefinitionId.TryParse("MyObjectBuilder_BlueprintDefinition", blueprintId, out definition);
            foreach (String word in words)
            {
                itemNamesToBlueprints.Add(word, definition);
            }
        }
Exemple #14
0
        public bool AddBlueprint(string name, out MyItemType type)
        {
            MyDefinitionId item;
            MyDefinitionId?blueprint;

            if (MyDefinitionId.TryParse("MyObjectBuilder_" + name, out item) &&
                ((blueprint = CreateBlueprint(item.SubtypeName)) != null))
            {
                Blueprints[item] = blueprint.Value;
                InverseBlueprints[blueprint.Value] = item;
                type = item;
                return(true);
            }
            type = default(MyItemType);
            return(false);
        }
Exemple #15
0
        public Dictionary <MyDefinitionId, MyDefinitionId> GetReplacementReferencePairs()
        {
            var result = new Dictionary <MyDefinitionId, MyDefinitionId>();

            if (this.GlobalBlockReplacerReference.Length == 0)
            {
                Logger.AddMsg("Global Block Replacement References 0", true);
                return(result);
            }

            foreach (var pair in this.GlobalBlockReplacerReference)
            {
                var split = pair.Split('|');

                if (split.Length != 2)
                {
                    Logger.AddMsg("Global Replace Bad Split: " + pair, true);
                    continue;
                }

                var idA = new MyDefinitionId();
                var idB = new MyDefinitionId();

                if (MyDefinitionId.TryParse(split[0], out idA) == false)
                {
                    Logger.AddMsg("Could Not Parse: " + split[0], true);
                    continue;
                }

                if (MyDefinitionId.TryParse(split[1], out idB) == false)
                {
                    Logger.AddMsg("Could Not Parse: " + split[1], true);
                    continue;
                }

                if (result.ContainsKey(idA) == true)
                {
                    Logger.AddMsg("MyDefinitionId already present: " + split[0], true);
                    continue;
                }

                result.Add(idA, idB);
            }

            return(result);
        }
Exemple #16
0
        bool GetDefinitionId(string type, out MyDefinitionId definitionId)
        {
            //Hiding string magic here.

            //jTurp "I asked Inflex to add in a MyItemType.MakeBlueprint so hopefully in the future it'll be easier"
            //So this hardcoded lookup table should be replaced if that happens.

            //Translate subtypeID to blueprint if needed
            if (BlueprintNames.ContainsKey(type))
            {
                type = BlueprintNames[type];
            }

            if (MyDefinitionId.TryParse("MyObjectBuilder_BlueprintDefinition/" + type, out definitionId))
            {
                return(true);
            }
            return(false);
        }
Exemple #17
0
        internal void AddToFilter(Filterdata filterdata)
        {
            if (filterdata.FilterItems.Length == 0)
            {
                // DebugLog.Write("AddToFilter called with 0 items to add. ignoring...");
                return;
            }

            var inventory = (MyInventory)MyCargoContainer.GetInventory();

            for (int i = 0; i < filterdata.FilterItems.Length; i++)
            {
                if (filterdata.FilterItems[i].Type == FilterType.FILTER_TYPE)
                {
                    MyObjectBuilderType type;
                    if (MyObjectBuilderType.TryParse(filterdata.FilterItems[i].ParseItem, out type) == true)
                    {
                        if (!inventory.Constraint.ConstrainedTypes.Contains(type))
                        {
                            inventory.Constraint.AddObjectBuilderType(type);
                        }
                    }
                }
                if (filterdata.FilterItems[i].Type == FilterType.FILTER_ITEM)
                {
                    MyDefinitionId Id;
                    if (MyDefinitionId.TryParse(filterdata.FilterItems[i].ParseItem, out Id) == true)
                    {
                        if (!inventory.Constraint.ConstrainedIds.Contains(Id))
                        {
                            inventory.Constraint.Add(Id);
                        }
                    }
                }
                if (!FilterController.FilterList.Contains(filterdata.FilterItems[i]))
                {
                    FilterController.FilterList.Add(filterdata.FilterItems[i]);
                }
            }
            inventory.Constraint.Icon = null;
            SaveData();
        }
Exemple #18
0
 public override void Execute(Data.Data data, Dictionary <string, object> parameters)
 {
     SessionHandler.EnqueueAction(() =>
     {
         var player = Utils.GetPlayer();
         if (player != null && Items != null)
         {
             var character   = player.Character;
             var worldMatrix = character.WorldMatrix;
             foreach (var item in Items)
             {
                 if (MyDefinitionId.TryParse("MyObjectBuilder_" + item.Id, out var id) &&
                     MyDefinitionManager.Static.TryGetPhysicalItemDefinition(id, out var itemDefinition))
                 {
                     var amount = GetEventValue(item.Amount, 1, parameters);
                     Utils.AddOrDropItem(player, itemDefinition, ref amount, worldMatrix);
                 }
             }
         }
     });
 }
Exemple #19
0
            /// <summary>
            /// Создаёт предложение для продажи в блоке магазина
            /// </summary>
            /// <param name="itemTypeSubtype">Тип объекта</param>
            /// <param name="amount">Колличество</param>
            /// <param name="price">Цена</param>
            void InsertOffer(string itemTypeSubtype, int amount, int price)
            {
                long           orderId = 0;
                MyDefinitionId definitionId;

                if (MyDefinitionId.TryParse(itemTypeSubtype, out definitionId))
                {
                    Block.InsertOffer(new MyStoreItemDataSimple(definitionId, amount, price), out orderId); // Мы закупаем
                }
                else
                {
                    TradeInfo.AppendLine($"ОШИБКА! Объект [MyDefinitionId] НЕ создан. Вероятно указан не правильный itemType/ & Subtype");
                }
                if (orderId != 0)
                {
                    TradeInfo.AppendLine($"[Create] Продажа [{itemTypeSubtype}] {amount}шт по цене {price}кр");
                }
                else
                {
                    TradeInfo.AppendLine($"ОШИБКА! Продажа [{itemTypeSubtype}] не удалась! Проверьте имя и цену[{price}]");
                }
            }
Exemple #20
0
        public MyDefinitionId?FindBlueprint(MyItemType iType)
        {
            MyDefinitionId blueprint;

            if (MyDefinitionId.TryParse($"MyObjectBuilder_BlueprintDefinition/{iType.SubtypeId}", out blueprint))
            {
                if (leadAssembler.CanUseBlueprint(blueprint))
                {
                    return(blueprint);
                }
            }

            if (MyDefinitionId.TryParse($"MyObjectBuilder_BlueprintDefinition/{iType.SubtypeId}Component", out blueprint))
            {
                if (leadAssembler.CanUseBlueprint(blueprint))
                {
                    return(blueprint);
                }
            }

            return(null);
        }
Exemple #21
0
        public void Make_component(MyFixedPoint min_count, MyFixedPoint current_count, MyFixedPoint production_queue, string blueprint)
        {
            //Dbg_panel($"Make_component({blueprint})");

            MyDefinitionId queue_item_blueprint_id;
            MyFixedPoint   amount_diff;

            amount_diff = min_count - current_count - production_queue;
            //Dbg_panel($"amount_diff ({amount_diff}) = min_count ({min_count}) - current_count ({current_count}) - production_queue ({production_queue})");

            bool opt1 = amount_diff <= min_count;
            bool opt2 = amount_diff > 0;

            if (opt1 & opt2)
            {
                if (MyDefinitionId.TryParse(blueprint, out queue_item_blueprint_id))
                {
                    string[] blueprint_name = blueprint.Split('/');
                    Dbg_panel($"Make {amount_diff} of {blueprint_name[1]}");
                    assembler.AddQueueItem(queue_item_blueprint_id, amount_diff);
                }
            }
        }
Exemple #22
0
        private void ToolbarItemChanged(long entityId, string typeId, string subtypeId, int page, int slot)
        {
            try
            {
                if (Instance == null)
                {
                    // WTF
                    MyVisualScriptLogicProvider.ToolbarItemChanged -= ToolbarItemChanged;
                    return;
                }

                if (MyAPIGateway.Session.Player == null || !modOverrideEnabled)
                {
                    return;
                }

                MyDefinitionId handId;
                if (config.ModEnabled && IsToolbarCharacter() && MyAPIGateway.Gui.ActiveGamePlayScreen == "MyGuiScreenCubeBuilder" &&
                    typeId == "MyObjectBuilder_PhysicalGunObject" && MyDefinitionId.TryParse(typeId, subtypeId, out handId))
                {
                    EquippedToolAction newToolAction = new EquippedToolAction(handId, page, slot);
                    foreach (EquippedToolAction toolAction in equippedTools)
                    {
                        if (toolAction.Update(newToolAction))
                        {
                            return;
                        }
                    }
                    equippedTools.Add(newToolAction);
                }
            }
            catch (Exception e)
            {
                MyLog.Default.WriteLineAndConsole("ERROR in ToolbarItemChanged(): " + e);
            }
        }
        public void Main(string argument)
        {
            if (_assembler == null && !InitialiseAssembler())
            {
                WriteToTextPanel(_assemblerName + " not installed");
                return;
            }
            string arg = argument.ToLower();

            List <string> groups = new List <string>();

            for (int start = 0; (start = arg.IndexOf('(', start)) != -1; start++)
            {
                int    end    = (start >= 0) ? arg.IndexOf(')', start) : -1;
                string result = (end >= 0) ? arg.Substring(start + 1, end - start - 1) : "";
                groups.Add(result);
            }

            const string working = "Assembler is working.\n";
            const string missing = "Missing material for Queue.\n";

            if (!_assembler.IsProducing && !_assembler.IsQueueEmpty)
            {
                _asmworking.Replace(working, missing);
            }
            if (_assembler.IsProducing)
            {
                _asmworking.Clear();
                _asmworking.AppendLine(working);
            }
            if (!_assembler.IsProducing && _assembler.IsQueueEmpty)
            {
                _asmworking.Clear();
                _dynamicContent.Clear();
                _asmworking.AppendLine("Assembler is Idle.\n");
            }
            //dynamicContent.Clear();

            Echo(_runStatus[_runAdvancer]);
            _runAdvancer = (_runAdvancer + 1) % _runStatus.Length;

            foreach (var selectedGroup in groups)
            {
                List <string> args = new List <string>(selectedGroup.Split('/'));

                if (_values.ContainsKey(args[0]))
                {
                    string item  = _values[args[0]];
                    string count = args[1];

                    if (count?.Length == 0 || Convert.ToDouble(count) <= 0)
                    {
                        Echo("Item: " + item + "\nAmount: Wrong or No number input\n");
                        return;
                    }
                    MyDefinitionId objectIdToAdd = new MyDefinitionId();
                    if (MyDefinitionId.TryParse("MyObjectBuilder_BlueprintDefinition/" + item, out objectIdToAdd))
                    {
                        Echo("Item: " + item + "\nAmount: " + Convert.ToDouble(count) + "\n");
                        _assembler.AddQueueItem(objectIdToAdd, Convert.ToDouble(count));
                        _dynamicContent.Append("Item: ").Append(item).Append("\nAmount: ").Append(Convert.ToDouble(count)).AppendLine("\n");
                    }
                }
                else
                {
                    Echo("Argument Missing: Check Name \n");
                }
            }
            if (arg == "clear")
            {
                _dynamicContent.Clear();
                _assembler.ClearQueue();
                Echo("Cleared Assembler Queue.");
                _dynamicContent.AppendLine("Cleared Assembler Queue.");
            }

            WriteToTextPanel(_asmworking.ToString() + _dynamicContent.ToString());
            string asmstatus = ("\nAssembler is producing: " + _assembler.IsProducing.ToString());
            //string asmstatus = assembler.NextItemId.ToString();
            //WriteToTextPanel(asmstatus);
        }
Exemple #24
0
 private bool TryGetBlueprint(string shortName, out MyDefinitionId id) => MyDefinitionId.TryParse(_blueprintDef + _blueprintNames[shortName], out id);
        public void Main(string argument, UpdateType updateSource)
        {
            // Copy to reset the values
            var localItemDict = new Dictionary <VRage.MyTuple <string, string>, ItemDef>(itemDict);

            // Enumerate the blocks that have inventory
            foreach (var e in inventoryBlocks)
            {
                var items = new List <MyInventoryItem>();
                for (int i = 0; i < e.InventoryCount; i++)
                {
                    e.GetInventory(i).GetItems(items);
                    ItemDef thisItem;
                    foreach (var item in items)
                    {
                        var itemKey = VRage.MyTuple.Create(item.Type.TypeId, item.Type.SubtypeId);
                        if (localItemDict.TryGetValue(itemKey, out thisItem))
                        {
                            thisItem.Available    += (float)item.Amount;
                            localItemDict[itemKey] = thisItem;
                        }
                    }
                }
            }

            // Get the total queued items
            var queuedItems = new List <MyProductionItem>();

            foreach (var a in assemblerBlocks.Where(a => a.Mode == MyAssemblerMode.Assembly))
            {
                var q = new List <MyProductionItem>();
                a.GetQueue(q);
                foreach (var i in q)
                {
                    string iname = i.BlueprintId.SubtypeName;
                    if (iname.EndsWith("Component"))
                    {
                        iname = iname.Substring(0, iname.Length - "Component".Length);
                    }
                    var     itemKey = VRage.MyTuple.Create("MyObjectBuilder_Component", iname);
                    ItemDef thisItem;
                    if (localItemDict.TryGetValue(itemKey, out thisItem))
                    {
                        thisItem.Queued       += (int)i.Amount;
                        localItemDict[itemKey] = thisItem;
                    }
                }
            }

            // Find any components that need to be assembled
            StringBuilder output = new StringBuilder(256);

            foreach (var key in localItemDict.Keys)
            {
                var    item     = localItemDict[key];
                string itemName = key.Item2;
                int    toQueue  = (int)item.Min - ((int)item.Available + (int)item.Queued);
                if (toQueue > 0)
                {
                    output.Append(itemName + ": " + (int)item.Min + " min/" + (int)item.Available + " avai/" + (int)item.Queued + " q'd->" + toQueue + "to add\n");
                    if (itemName == "Computer" || itemName == "Construction" ||
                        itemName == "Detector" || itemName == "Explosives" ||
                        itemName == "Girder" || itemName == "GravityGenerator" ||
                        itemName == "Medical" || itemName == "Motor" ||
                        itemName == "RadioCommunication" || itemName == "Reactor" ||
                        itemName == "Thrust")
                    {
                        itemName += "Component";
                    }
                    MyDefinitionId bp = new MyDefinitionId();
                    if (MyDefinitionId.TryParse("MyObjectBuilder_BlueprintDefinition/" + itemName, out bp))
                    {
                        assemblerBlocks[0].AddQueueItem(bp, (decimal)toQueue);
                    }
                }
            }
            output.Append("Last runtime: " + Math.Round(this.Runtime.LastRunTimeMs, 2) + "ms");
            Me.GetSurface(0).WriteText(output);
        }
Exemple #26
0
        /// <summary>
        /// Добавление нового контракта за голову
        /// </summary>
        /// <param name="steamID">SteamID цели контракта</param>
        public void AddHeadHunterContract(ulong steamID)
        {
            try
            {
                ///парсим строку определения кастомного контракта и пишем в новую переменную
                MyDefinitionId definitionId;
                MyDefinitionId.TryParse("MyObjectBuilder_ContractTypeDefinition/CustomContract", out definitionId);

                ///Получаем интерфейс игрока на сервере
                var player = PlayerUtils.GetPlayer(steamID);
                ///Если игрока нет в сети или не существует - контракт не добавляется
                if (player == null)
                {
                    return;
                }
                ///Создаем описание контракта
                var contractDescr = new ContractDescription(player.DisplayName);
                ///в глобальные переменные пишем список контрактных блоков и загружаем ранее созданные контракты
                GetContractBlocks();
                LoadContracts();

                ///блокируем список на изменение в других потоках
                lock (ContractStorage)
                {
                    ///проверяем контракты, есть ли уже заказ на этого игрока
                    ContractBlocks.ForEach(contractBlock => {
                        if (ContractStorage.BountedPlayers.Where(x => x.SteamID == steamID).Count() > 0)
                        {
                            ContractStorage.BountedPlayers.Where(x => x.SteamID == steamID).ForEach(x => {
                                ///если заказ найден проверяем остаток на награде
                                ///если награда 0 - контракты не добавляются в контрактные блоки
                                if (x.Bounty == 0)
                                {
                                    return;
                                }

                                ///если награда не 0 - создаем новый контракт
                                var bounty     = x.Bounty;
                                var collateral = Plugin.Config.ContractCollateral;
                                var contract   = new MyContractCustom(definitionId, contractBlock.EntityId, bounty, collateral, 0, contractDescr.GetContractName(), contractDescr.GetDescription(), 10, -10, null);

                                ///добавляем новый контракт в систему контрактов
                                var contractAddResult = MyAPIGateway.ContractSystem.AddContract(contract);
                                ///если добавление прошло успешно - записываем в список заказов новый контракт
                                if (contractAddResult.Success)
                                {
                                    var _contract = new HeadHunterContract()
                                    {
                                        contract_id = contractAddResult.ContractId, contract_condition_id = contractAddResult.ContractConditionId, State = MyAPIGateway.ContractSystem.GetContractState(contractAddResult.ContractId)
                                    };
                                    x.Contracts.Add(_contract);
                                }
                                else
                                {
                                    Log.Info("failed add contract");
                                }
                            });
                        }
                    });
                }
                ///записываем контракты в файл
                SaveContracts();
            } catch (Exception e)
            {
                Log.Error(e.Message);
                Log.Error(e.StackTrace);
            }
        }
        public void Buy(string orderNumber)
        {
            if (!CheckIsPlayer(out var player))
            {
                return;
            }

            if (!Plugin.PurchaseOrders.TryGetValue(orderNumber, out var purchaseOrder))
            {
                Respond("No such purchase order");
                return;
            }

            var sellerIdentityId = purchaseOrder.SellerIdentityId;
            var isSelfOrder      = sellerIdentityId == player.IdentityId;

            if (!Config.CanRepurchaseOwnOrder && isSelfOrder)
            {
                Respond("Can't repurchase your own order");
                return;
            }

            var sellerNotExist = !MySession.Static.Players.HasIdentity(sellerIdentityId);

            if (sellerNotExist)
            {
                Log.Error($"Seller {sellerIdentityId} of order <{orderNumber}> not exists!");
            }
            else if (!Config.CanRepurchaseFactionOrder && !isSelfOrder &&
                     MySession.Static.Factions.GetPlayerFaction(sellerIdentityId)?.IsMember(player.IdentityId) == true)
            {
                Respond("Can't repurchase your faction order");
                return;
            }

            if (!player.TryGetBalanceInfo(out var balance) || balance < purchaseOrder.Price)
            {
                Respond($"No enough money, need {purchaseOrder.Price} but you only have {balance}");
                return;
            }

            if (!MyDefinitionId.TryParse(purchaseOrder.ItemType, purchaseOrder.ItemSubType, out var definitionId) ||
                !MyDefinitionManager.Static.TryGetPhysicalItemDefinition(definitionId, out _))
            {
                Respond(
                    $"The order <{orderNumber}> contains invalid DefinitionId, may cause by mod changing or data corruption, please contact GM"
                    );
                return;
            }

            var playerInventory         = GetPlayerInventory();
            var canAddToPlayerInventory = playerInventory?.ComputeAmountThatFits(definitionId) ?? MyFixedPoint.Zero;
            var cargoInventory          = GetAimedHavePermissionCargoInventory();
            var canAddToCargoInventory  = cargoInventory?.ComputeAmountThatFits(definitionId) ?? MyFixedPoint.Zero;

            //totalCanAdd may overflow
            if (canAddToCargoInventory < purchaseOrder.Amount &&
                canAddToPlayerInventory < purchaseOrder.Amount &&
                canAddToPlayerInventory + canAddToCargoInventory < purchaseOrder.Amount)
            {
                Respond("No enough inventory space");
                return;
            }

            MyFixedPoint addToPlayerInventory;
            MyFixedPoint addToCargoInventory;

            if (canAddToCargoInventory > purchaseOrder.Amount)
            {
                addToCargoInventory  = purchaseOrder.Amount;
                addToPlayerInventory = MyFixedPoint.Zero;
            }
            else
            {
                addToCargoInventory  = canAddToCargoInventory;
                addToPlayerInventory = purchaseOrder.Amount - canAddToCargoInventory;
            }

            if (!Plugin.TryFinishOrder(orderNumber, out _))
            {
                Respond("No such purchase order");
                return;
            }

            player.RequestChangeBalance(-purchaseOrder.Price);
            var objectBuilder = MyObjectBuilderSerializer.CreateNewObject(definitionId);

            playerInventory?.AddItems(addToPlayerInventory, objectBuilder);
            cargoInventory?.AddItems(addToCargoInventory, objectBuilder);
            Respond($"You bought {definitionId} ({purchaseOrder.Amount}) for ${purchaseOrder.Price}");

            var tax = (long)(Config.IllegalTaxRateDouble * purchaseOrder.Price);
            var s   = $"<{orderNumber}> purchased by '{player.DisplayName}' for ${purchaseOrder.Price}(tax ${tax})";

            if (Config.BroadcastOnBuy)
            {
                SendMessage($"The order {s}");
            }

            if (sellerNotExist)
            {
                return;
            }
            MyBankingSystem.ChangeBalance(sellerIdentityId, purchaseOrder.Price - tax);

            if (!Config.BroadcastOnBuy && Config.NotifySellerOnBuy &&
                MySession.Static.Players.TryGetPlayerId(sellerIdentityId, out var sellerPlayerId) &&
                MySession.Static.Players.IsPlayerOnline(ref sellerPlayerId))
            {
                SendMessage(
                    $"Your order {s}",
                    sellerPlayerId.SteamId
                    );
            }
        }
Exemple #28
0
        private void ItemPickedUp(string itemTypeName, string itemSubTypeName, string entityName, long playerId, int amount)
        {
            MyDefinitionId handId;

            if (modOverrideEnabled && amount == 1 && itemTypeName == "MyObjectBuilder_PhysicalGunObject" && MyDefinitionId.TryParse(itemTypeName, itemSubTypeName, out handId))
            {
                new EventPacket(EventPacket.Mode.PickUp, handId).SendTo(playerId);
            }
        }
Exemple #29
0
        public Progression()
        {
            IEnumerable <MyBlueprintDefinitionBase> blues = MyDefinitionManager.Static.GetBlueprintDefinitions(); //System.Collections.Generic.IEnumerable

            foreach (MyBlueprintDefinitionBase blue in blues)
            {
                //BlockInformation blockInfo = new BlockInformation();
                //blockInfo.BlueprintId = blue.Id;
                //MyDefinitionId blockId = new MyDefinitionId();
                //blockInfo.Results = new HashSet<SerializableDefinitionId>();
                MyDefinitionId BlockId = new MyDefinitionId();
                MyDefinitionId.TryParse("MyObjectBuilder_" + blue.Id.SubtypeId.String, out BlockId);

                if (BlockId.TypeId.IsNull)
                {
                    continue;
                }
                MyCubeBlockDefinition cb = new MyCubeBlockDefinition();
                MyDefinitionManager.Static.TryGetDefinition <MyCubeBlockDefinition>(BlockId, out cb);
                HashSet <SerializableDefinitionId> results = new HashSet <SerializableDefinitionId>();

                String group      = "Default";
                float  efficiency = 0;
                String cubeSize   = cb.CubeSize.ToString();
                String _Type      = blue.Id.SubtypeId.String.Split('/')[0];
                string PairName   = cb.BlockPairName;

                MyThrustDefinition         thrust  = new MyThrustDefinition();
                MyReactorDefinition        reactor = new MyReactorDefinition();
                MyCargoContainerDefinition cargo   = new MyCargoContainerDefinition();
                float Cost = 0;
                if (MyDefinitionManager.Static.TryGetDefinition <MyThrustDefinition>(BlockId, out thrust))
                {
                    if (thrust.FuelConverter.FuelId.IsNull())
                    {
                        group = thrust.ThrusterType.String;
                    }
                    else
                    {
                        group = thrust.FuelConverter.FuelId.SubtypeName;
                    }
                    //Cost = thrust.ForceMagnitude;
                    efficiency = thrust.ForceMagnitude;//thrust.MaxPowerConsumption;
                }
                else if (MyDefinitionManager.Static.TryGetDefinition <MyReactorDefinition>(BlockId, out reactor))
                {
                    group = reactor.FuelId.SubtypeId.String;
                }
                else if (MyDefinitionManager.Static.TryGetDefinition <MyCargoContainerDefinition>(BlockId, out cargo))
                {
                    efficiency = cargo.InventorySize.Sum;
                }

                string resultCount = blue.DisplayNameText;
                SerializableDefinitionId SerializedBlueprintId = blue.Id;

                List <MyBlueprintDefinitionBase.Item> recipe = new List <MyBlueprintDefinitionBase.Item>();
                foreach (MyBlueprintDefinitionBase.Item item in blue.Results)
                {
                    results.Add(item.Id);
                }

                SerializableDefinitionId smallLargeBlockId = new SerializableDefinitionId();
                var dg = MyDefinitionManager.Static.TryGetDefinitionGroup(cb.BlockPairName);
                if (dg != null)
                {
                    if (dg.Large != null)
                    {
                        smallLargeBlockId = dg.Large.Id;
                    }
                    if (dg.Small != null)
                    {
                        smallLargeBlockId = dg.Small.Id;
                    }
                }

                //MyLog.Default.WriteLine($"Id {(SerializableDefinitionId)blue.Results[0].Id}");
                foreach (var item in blue.Prerequisites)
                {
                    Cost += item.Amount.RawValue;
                    recipe.Add(item);
                }
                MyLog.Default.WriteLine($"Cost {Cost}");
                if (BlockId != null)
                {
                    SerializableDefinitionId SerializedBlockId = BlockId;
                    ComponentsCosts.Add(BlockId, new BlockInformation(BlockId, SerializedBlockId, results, recipe, Cost, group, cubeSize, efficiency, _Type, smallLargeBlockId, PairName));
                }
            }

            List <BlockInformation> existingKey = new List <BlockInformation>();

            foreach (BlockInformation BI in ComponentsCosts.Values)
            {
                if (typeList.TryGetValue(BI.Type, out existingKey))
                {
                    existingKey.Add(BI);
                }
                else
                {
                    // Create if not exists in dictionary
                    List <BlockInformation> temp = new List <BlockInformation>();
                    temp.Add(BI);
                    typeList.Add(BI.Type, temp);
                }
            }

            foreach (List <BlockInformation> BIList in typeList.Values)
            {
                BIList.Sort((pair1, pair2) => pair1.BlueprintCost.CompareTo(pair2.BlueprintCost));
            }

            //Set Actual Positon on Each Block, so later we may get the current position out of the techtree
            PrepareCache();
            SetTechPos();
            CalculateLuck();
        }
Exemple #30
0
        private void ChatMessage(string messageText, ref bool sendToOthers)
        {
            string[] args;
            if (messageText.StartsWith(prefix2) || messageText.StartsWith(prefix1))
            {
                args = messageText.Split(space, StringSplitOptions.RemoveEmptyEntries);
            }
            else
            {
                return;
            }

            sendToOthers = false;

            if (!IsPlayerAdmin(true))
            {
                return;
            }

            if (args.Length < 2)
            {
                ShowHelp();
                return;
            }


            MapSettings config = IPSession.Instance.MapSettings;

            switch (args[1])
            {
            case "blocktime":
            {
                if (args.Length > 3)
                {
                    Show("Usage: /ip blocktime <value>");
                    return;
                }

                if (args.Length == 2)
                {
                    Show("Block Build Time: " + config.BlockBuildTime);
                    return;
                }

                float n;
                if (!float.TryParse(args[2], out n))
                {
                    Show("Unable to parse '" + args[2] + "' into a number.");
                    return;
                }
                if (n < 0 || float.IsInfinity(n) || float.IsNaN(n))
                {
                    Show("Value must be greater than 0.");
                    return;
                }
                config.BlockBuildTime = n;
                Show("Block Build Time: " + n);
            }
            break;

            case "compcost":
            {
                if (args.Length > 3)
                {
                    Show("Usage: /ip compcost <value>");
                    return;
                }

                if (args.Length == 2)
                {
                    Show("Component Cost Modifier: " + config.ComponentCostModifier);
                    return;
                }

                float n;
                if (!float.TryParse(args[2], out n))
                {
                    Show("Unable to parse '" + args[2] + "' into a number.");
                    return;
                }
                if (n < 0 || float.IsInfinity(n) || float.IsNaN(n))
                {
                    Show("Value must be greater than 0.");
                    return;
                }
                config.ComponentCostModifier = n;
                Show("Component Cost Modifier: " + n);
            }
            break;

            case "minblocks":
            {
                if (args.Length > 3)
                {
                    Show("Usage: /ip minblocks <value>");
                    return;
                }

                if (args.Length == 2)
                {
                    Show("Min Blocks: " + config.MinBlocks);
                    return;
                }

                int n;
                if (!int.TryParse(args[2], out n))
                {
                    Show("Unable to parse '" + args[2] + "' into a number.");
                    return;
                }
                if (n < 0 || n >= config.MaxBlocks)
                {
                    Show("Value must be greater than 0 and less than" + config.MaxBlocks);
                    return;
                }
                config.MinBlocks = n;
                Show("Min Blocks: " + n);
            }
            break;

            case "maxblocks":
            {
                if (args.Length > 3)
                {
                    Show("Usage: /ip maxblocks <value>");
                    return;
                }

                if (args.Length == 2)
                {
                    Show("Max Blocks: " + config.MaxBlocks);
                    return;
                }

                int n;
                if (!int.TryParse(args[2], out n))
                {
                    Show("Unable to parse '" + args[2] + "' into a number.");
                    return;
                }
                if (n < 0 || n <= config.MinBlocks)
                {
                    Show("Value must be greater than " + config.MinBlocks);
                    return;
                }
                config.MaxBlocks = n;
                Show("Max Blocks: " + n);
            }
            break;

            case "subgrids":
            {
                if (args.Length > 3)
                {
                    Show("Usage: /ip subgrids <true|false>");
                    return;
                }

                if (args.Length == 2)
                {
                    Show("Subgrids: " + config.Subgrids);
                    return;
                }

                bool b;
                if (!bool.TryParse(args[2], out b))
                {
                    Show("Unable to parse '" + args[2] + "' into true or false.");
                    return;
                }
                config.Subgrids = b;
                Show("Subgrids: " + b);
            }
            break;

            case "power":
            {
                if (args.Length > 3)
                {
                    Show("Usage: /ip power <value>");
                    return;
                }

                if (args.Length == 2)
                {
                    Show("Power Modifier: " + config.PowerModifier);
                    return;
                }

                float n;
                if (!float.TryParse(args[2], out n))
                {
                    Show("Unable to parse '" + args[2] + "' into a number.");
                    return;
                }
                if (n < 0 || float.IsInfinity(n) || float.IsNaN(n))
                {
                    Show("Value must be greater than 0.");
                    return;
                }
                config.PowerModifier = n;
                Show("Power Modifier: " + n);
            }
            break;

            case "extracomp":
            {
                if (args.Length > 4)
                {
                    Show("Usage: /ip extracomp [<typeid> <subtypeid>|none]");
                    return;
                }

                if (args.Length == 2)
                {
                    Show("Extra Component: " + config.GetExtraCompName());
                    return;
                }


                string typeId = args[2];
                string subtypeId;

                if (args.Length == 3)
                {
                    if (typeId.Equals("null", StringComparison.OrdinalIgnoreCase) || typeId.Equals("none", StringComparison.OrdinalIgnoreCase))
                    {
                        config.ExtraComponent = null;
                        Show("Extra Component: None");
                        return;
                    }

                    if (typeId.Contains("/"))
                    {
                        string[] typeArgs = typeId.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                        if (typeArgs.Length != 2)
                        {
                            Show("Usage: /ip extracomp [<typeid> <subtypeid>|none]");
                            return;
                        }
                        typeId    = typeArgs[0];
                        subtypeId = typeArgs[1];
                    }
                    else
                    {
                        Show("Usage: /ip extracomp [<typeid> <subtypeid>|none]");
                        return;
                    }
                }
                else
                {
                    subtypeId = args[3];
                }

                string obTypeId;
                if (!typeId.StartsWith("MyObjectBuilder_"))
                {
                    obTypeId = "MyObjectBuilder_" + typeId;
                }
                else
                {
                    obTypeId = typeId;
                    typeId   = typeId.Replace("MyObjectBuilder_", "");
                }

                MyDefinitionId id;
                if (!MyDefinitionId.TryParse(obTypeId, subtypeId, out id))
                {
                    Show($"Unable to parse {typeId}/{subtypeId} into an id.");
                    return;
                }

                MyPhysicalItemDefinition comp;
                if (!MyDefinitionManager.Static.TryGetPhysicalItemDefinition(id, out comp))
                {
                    Show($"Unable to find an item with id {typeId}/{subtypeId} in the game.");
                    return;
                }
                config.ExtraComponent = id;
                Show("Extra Component: " + config.GetExtraCompName());
            }
            break;

            case "extracompcost":
            {
                if (args.Length > 3)
                {
                    Show("Usage: /ip extracompcost <value>");
                    return;
                }

                if (args.Length == 2)
                {
                    Show("Extra Component Cost: " + config.ExtraCompCost);
                    return;
                }

                float n;
                if (!float.TryParse(args[2], out n))
                {
                    Show("Unable to parse '" + args[2] + "' into a number.");
                    return;
                }
                if (n < 0 || float.IsInfinity(n) || float.IsNaN(n))
                {
                    Show("Value must be greater than 0.");
                    return;
                }
                config.ExtraCompCost = n;
                Show("Extra Component Cost: " + n);
            }
            break;

            default:
                ShowHelp();
                break;
            }
        }