Beispiel #1
0
        public override void UpdateBeforeSimulation100()
        {
            base.UpdateBeforeSimulation100();

            if (m_generator.IsWorking)
            {
                Frame = frameShift++;
                if (Frame % 30 != 0)
                {
                    return;
                }

                //IMyInventory inventory = ((Sandbox.ModAPI.IMyTerminalBlock)Entity).GetInventory(0) as IMyInventory;

                //if (!inventory.ContainItems(10000, new MyObjectBuilder_Ingot { SubtypeName = "Coin" }))
                //{
                //    inventory.AddItems(5, new MyObjectBuilder_Ingot { SubtypeName = "Coin" });
                //    terminalBlock.RefreshCustomInfo();
                //}
                //IMyInventory inventory1 = ((Sandbox.ModAPI.IMyTerminalBlock)Entity).GetInventory(1) as IMyInventory;
                //if (!inventory1.ContainItems(10, new MyObjectBuilder_AmmoMagazine { SubtypeName = "NATO_25x184mm" }))
                //{
                //    inventory1.AddItems(1, new MyObjectBuilder_AmmoMagazine { SubtypeName = "NATO_25x184mm" });
                //    terminalBlock.RefreshCustomInfo();
                //}


                List <IMyPlayer> players = new List <IMyPlayer>();
                MyAPIGateway.Players.GetPlayers(players, x => x.Controller != null && x.Controller.ControlledEntity != null);
                foreach (IMyPlayer player in players)
                {
                    if (player.IsBot)
                    {
                        continue;
                    }
                    if (player.Controller.ControlledEntity is IMyCharacter)
                    {
                        MyEntity entity = player.Controller.ControlledEntity.Entity as MyEntity;
                        if (entity.HasInventory)
                        {
                            IMyInventory inventory = entity.GetInventoryBase() as MyInventory;
                            if (!inventory.ContainItems(10000, new MyObjectBuilder_Ingot {
                                SubtypeName = "Coin"
                            }))
                            {
                                inventory.AddItems(60, new MyObjectBuilder_Ingot {
                                    SubtypeName = "Coin"
                                });
                                terminalBlock.RefreshCustomInfo();
                            }
                        }
                    }
                }
            }
        }
Beispiel #2
0
        public static IMyInventory GetInventory(this IMyTerminalBlock block, int index)
        {
            MyEntity entity = block as MyEntity;

            if (entity == null)
            {
                return(null);
            }
            if (!entity.HasInventory)
            {
                return(null);
            }
            return(entity.GetInventoryBase(index) as IMyInventory);
        }
Beispiel #3
0
        public static Ammo GetLoadedAmmo(IMyCubeBlock weapon)
        {
            MyEntity entity = (MyEntity)weapon;

            if (!entity.HasInventory)
            {
                throw new InvalidOperationException("Has no inventory: " + weapon.getBestName());
            }

            MyInventoryBase inv = entity.GetInventoryBase(0);

            if (inv.GetItemsCount() == 0)
            {
                return(null);
            }

            MyDefinitionId magazineId;

            try { magazineId = inv.GetItems()[0].Content.GetId(); }
            catch (IndexOutOfRangeException)             // because of race condition
            { return(null); }

            return(GetAmmo(magazineId));
        }
Beispiel #4
0
        public bool SpawnInventoryContainer(bool spawnAboveEntity = true)
        {
            //TODO: this should not be here but we have to know if session is being closed if so then no new entity will be created.
            // Entity closing method and event should have parameter with sessionIsClosing.
            if (Sandbox.Game.World.MySession.Static == null || !Sandbox.Game.World.MySession.Static.Ready)
            {
                return(false);
            }

            var ownerEntity = Entity as MyEntity;

            for (int i = 0; i < ownerEntity.InventoryCount; ++i)
            {
                var inventory = ownerEntity.GetInventory(i);
                if (inventory != null && inventory.GetItemsCount() > 0)
                {
                    MyEntity inventoryOwner = Entity as MyEntity;
                    var      worldMatrix    = inventoryOwner.WorldMatrix;
                    if (spawnAboveEntity)
                    {
                        Vector3 upDir = -Sandbox.Game.GameSystems.MyGravityProviderSystem.CalculateNaturalGravityInPoint(inventoryOwner.PositionComp.GetPosition());
                        if (upDir == Vector3.Zero)
                        {
                            upDir = Vector3.Up;
                        }
                        upDir.Normalize();

                        Vector3 forwardDir = Vector3.CalculatePerpendicularVector(upDir);

                        var ownerPosition = worldMatrix.Translation;
                        var ownerAabb     = inventoryOwner.PositionComp.WorldAABB;
                        for (int moveIter = 0; moveIter < 20; ++moveIter)
                        {
                            var newPosition = ownerPosition + 0.1f * moveIter * upDir + 0.1f * moveIter * forwardDir;
                            var aabb        = new BoundingBoxD(newPosition - 0.25 * Vector3D.One, newPosition + 0.25 * Vector3D.One);
                            if (!aabb.Intersects(ref ownerAabb))
                            {
                                // Move newPosition a little to avoid collision with fractured pieces.
                                worldMatrix.Translation = newPosition + 0.25f * upDir;
                                break;
                            }
                        }

                        if (worldMatrix.Translation == ownerPosition)
                        {
                            worldMatrix.Translation += upDir + forwardDir;
                        }
                    }
                    else
                    {
                        var model = (inventoryOwner.Render.ModelStorage as MyModel);
                        if (model != null)
                        {
                            Vector3 modelCenter         = model.BoundingBox.Center;
                            Vector3 translationToCenter = Vector3.Transform(modelCenter, worldMatrix);
                            worldMatrix.Translation = translationToCenter;
                        }
                    }

                    MyContainerDefinition entityDefinition;
                    if (!MyComponentContainerExtension.TryGetContainerDefinition(m_containerDefinition.TypeId, m_containerDefinition.SubtypeId, out entityDefinition))
                    {
                        System.Diagnostics.Debug.Fail("Container Definition: " + m_containerDefinition.ToString() + " was not found!");
                        return(false);
                    }

                    MyEntity entity = MyEntities.CreateFromComponentContainerDefinitionAndAdd(entityDefinition.Id);
                    System.Diagnostics.Debug.Assert(entity != null);
                    if (entity == null)
                    {
                        return(false);
                    }

                    entity.PositionComp.SetWorldMatrix(worldMatrix);

                    System.Diagnostics.Debug.Assert(inventoryOwner != null, "Owner is not set!");

                    if (inventoryOwner.InventoryCount == 1)
                    {
                        inventoryOwner.Components.Remove <MyInventoryBase>();
                    }
                    else
                    {
                        var aggregate = inventoryOwner.GetInventoryBase() as MyInventoryAggregate;
                        if (aggregate != null)
                        {
                            aggregate.RemoveComponent(inventory);
                        }
                        else
                        {
                            System.Diagnostics.Debug.Fail("Inventory owners indicates that it owns more inventories, but doesn't have aggregate?");
                            return(false);
                        }
                    }

                    // Replaces bag default inventory with existing one.
                    entity.Components.Add <MyInventoryBase>(inventory);
                    inventory.RemoveEntityOnEmpty = true;

                    entity.Physics.LinearVelocity  = Vector3.Zero;
                    entity.Physics.AngularVelocity = Vector3.Zero;

                    if (ownerEntity.Physics != null)
                    {
                        entity.Physics.LinearVelocity  = ownerEntity.Physics.LinearVelocity;
                        entity.Physics.AngularVelocity = ownerEntity.Physics.AngularVelocity;
                    }
                    else if (ownerEntity is MyCubeBlock)
                    {
                        var grid = (ownerEntity as MyCubeBlock).CubeGrid;
                        if (grid.Physics != null)
                        {
                            entity.Physics.LinearVelocity  = grid.Physics.LinearVelocity;
                            entity.Physics.AngularVelocity = grid.Physics.AngularVelocity;
                        }
                    }

                    return(true);
                }
            }
            return(false);
        }
        internal void TakeRequiredComponents(MyEntity inventoryOwner)
        {
            if (MyAPIGateway.Session.CreativeMode)
            {
                return;
            }

            if (!inventoryOwner.HasInventory)
            {
                return;
            }

            // Ignore reactors
            if (inventoryOwner is Sandbox.ModAPI.Ingame.IMyReactor)
            {
                return;
            }

            if (inventoryOwner is IMyCubeBlock && ((IMyCubeBlock)inventoryOwner).BlockDefinition.SubtypeName.Contains("Nanite"))
            {
                return;
            }

            int inventoryIndex = inventoryOwner.InventoryCount - 1;
            //if (inventoryOwner is Sandbox.ModAPI.Ingame.IMyAssembler)
            //    inventoryIndex = 1;

            IMyInventory constructionInventory = GetConstructionInventory();
            IMyInventory inventory             = (IMyInventory)inventoryOwner.GetInventoryBase(inventoryIndex);

            if (constructionInventory == null || inventory == null)
            {
                return;
            }

            if (((Sandbox.Game.MyInventory)inventory).GetItemsCount() < 1)
            {
                return;
            }

            //if (!constructionInventory.IsConnectedTo(inventory))
            //    return;

            IMyTerminalBlock terminalOwner            = inventoryOwner as IMyTerminalBlock;
            MyRelationsBetweenPlayerAndBlock relation = ((IMyTerminalBlock)m_constructionBlock).GetUserRelationToOwner(terminalOwner.OwnerId);

            if (relation == MyRelationsBetweenPlayerAndBlock.Enemies)
            {
                return;
            }

            foreach (var inventoryItem in inventory.GetItems().ToList())
            {
                foreach (var componentNeeded in ComponentsRequired.ToList())
                {
                    if (inventoryItem.Content.TypeId != typeof(MyObjectBuilder_Component))
                    {
                        continue;
                    }

                    if (componentNeeded.Value <= 0)
                    {
                        continue;
                    }

                    if ((int)inventoryItem.Amount <= 0f)
                    {
                        continue;
                    }

                    if (inventoryItem.Content.SubtypeName == componentNeeded.Key)
                    {
                        if (inventoryItem.Amount >= componentNeeded.Value)
                        {
                            var validAmount = GetMaxComponentAmount(componentNeeded.Key, (float)constructionInventory.MaxVolume - (float)constructionInventory.CurrentVolume);
                            var amount      = Math.Min(componentNeeded.Value, validAmount);
                            if (!constructionInventory.CanItemsBeAdded((int)amount, new SerializableDefinitionId(typeof(MyObjectBuilder_Component), componentNeeded.Key)))
                            {
                                continue;
                            }

                            inventory.RemoveItemsOfType((int)amount, (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(typeof(MyObjectBuilder_Component), componentNeeded.Key));
                            constructionInventory.AddItems((int)amount, (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(typeof(MyObjectBuilder_Component), componentNeeded.Key));
                            ComponentsRequired[componentNeeded.Key] -= (int)amount;
                        }
                        else
                        {
                            var validAmount = GetMaxComponentAmount(componentNeeded.Key, (float)constructionInventory.MaxVolume - (float)constructionInventory.CurrentVolume);
                            var amount      = Math.Min((float)inventoryItem.Amount, validAmount);

                            if (!constructionInventory.CanItemsBeAdded((int)amount, new SerializableDefinitionId(typeof(MyObjectBuilder_Component), componentNeeded.Key)))
                            {
                                continue;
                            }

                            inventory.RemoveItemsOfType((int)amount, (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(typeof(MyObjectBuilder_Component), componentNeeded.Key));
                            constructionInventory.AddItems((int)amount, (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(typeof(MyObjectBuilder_Component), componentNeeded.Key));
                            ComponentsRequired[componentNeeded.Key] -= (int)amount;
                        }

                        continue;
                    }
                }
            }
        }
 private IMyInventory GetConstructionInventory()
 {
     return((IMyInventory)m_constructionBlock.GetInventoryBase(0));
 }
Beispiel #7
0
        public static void OnSyncRequest(byte[] bytes)
        {
            try
            {
                Logger.Log.Debug("BeaconSecurity.OnSyncRequest() - starts");

                SyncPacket pckIn = new SyncPacket();
                string     data  = System.Text.Encoding.Unicode.GetString(bytes);
                //Logger.Log.Debug(@"*******************************\n{0}\n*******************************\n", data);
                pckIn = MyAPIGateway.Utilities.SerializeFromXML <SyncPacket>(data);
                Logger.Log.Info("OnSyncRequest COMMAND:{0}, id:{1}, entity:'{2}', steamid: {3}, isserver: {4}", Enum.GetName(typeof(Command), pckIn.command), pckIn.ownerId, pckIn.entityId, pckIn.steamId, Core.IsServer);

                if (pckIn.proto != SyncPacket.Version)
                {
                    Logger.Log.Error("Wrong version of sync protocol client [{0}] <> [{1}] server", SyncPacket.Version, pckIn.proto);
                    MyAPIGateway.Utilities.ShowNotification("同步协议版本不匹配!尝试重新启动游戏或服务器!", 5000, MyFontEnum.Red);
                    return;
                }

                switch ((Command)pckIn.command)
                {
                case Command.Redeem:
                {
                    //收到命令,给这个玩家加点东西?
                    if (Core.IsServer)
                    {
                        Logger.Log.Info("Some one with steamid={0} trying to redeem", pckIn.steamId);
                        //IMyPlayer player = Core.GetPlayer(pckIn.steamId) as IMyPlayer;
                        string msg = "返回信息";
                        MyAPIGateway.Utilities.ShowMessage(Core.MODSAY, String.Format(msg));
                        if (Core.Codes.RedeemedCodes.Contains(pckIn.message))
                        {
                            MyAPIGateway.Utilities.ShowNotification("已经兑换过了!", 2000, MyFontEnum.Green);
                            SyncPacket newpacket = new SyncPacket();
                            newpacket.proto   = SyncPacket.Version;
                            newpacket.command = (ushort)Command.MessageToChat;
                            newpacket.message = "已经兑换过了!";
                            Core.SendMessage(newpacket);         // send to others
                            return;
                            //MyAPIGateway.Utilities.ShowMessage(Core.MODSAY, String.Format("已经被兑换!"));
                            //msg = "已经被兑换!";
                        }
                        else
                        {
                            string t     = pckIn.message.Replace("-", "");
                            byte[] data2 = Base24Encoding.Default.GetBytes(t);
                            if (data2 == null)
                            {
                                return;
                            }
                            String str = System.Text.Encoding.ASCII.GetString(data2);
                            str = str.TrimStart('\0');
                            string[] sep  = { ":" };
                            string[] msgs = str.Split(sep, 4, StringSplitOptions.RemoveEmptyEntries);
                            if (msgs.Length != 4)
                            {
                                return;
                            }



                            string type = msgs[0];
                            if (type.Equals("Coin", StringComparison.OrdinalIgnoreCase))
                            {
                                var num = 0;
                                try { num = Int32.Parse(msgs[1]); } catch { }

                                if (num == 0)
                                {
                                    return;
                                }
                                var sum = 0;
                                try { sum = Int32.Parse(msgs[3]); } catch { }

                                string content = msgs[0] + ":" + msgs[1] + ":" + msgs[2];

                                var sum2 = 0;
                                foreach (char c in content)
                                {
                                    sum2 += (int)c;
                                }
                                sum2 = sum2 % 100;
                                if (sum2 != sum)
                                {
                                    //MyAPIGateway.Utilities.ShowMessage(Core.MODSAY, String.Format("兑换码错误!"));
                                    MyAPIGateway.Utilities.ShowNotification("兑换码错误!", 2000, MyFontEnum.Green);
                                    SyncPacket newpacket = new SyncPacket();
                                    newpacket.proto   = SyncPacket.Version;
                                    newpacket.command = (ushort)Command.MessageToChat;
                                    newpacket.message = "兑换码错误!";
                                    Core.SendMessage(newpacket);         // send to others
                                    return;
                                }

                                //IMyPlayer player = MyAPIGateway.Session.Player as IMyPlayer;
                                IMyPlayer player = Core.GetPlayer(pckIn.steamId) as IMyPlayer;

                                if (player == null)
                                {
                                    Logger.Log.Info("redeem player null");
                                    return;
                                }

                                MyEntity entity = player.Character.Entity as MyEntity;
                                if (entity != null && entity.HasInventory)
                                {
                                    MyInventory inventory = entity.GetInventoryBase() as MyInventory;

                                    inventory.AddItems(num, new MyObjectBuilder_Ingot {
                                            SubtypeName = "Coin"
                                        });

                                    Core.Codes.RedeemedCodes.Add(pckIn.message);

                                    Core.setCodes(Core.Codes);
                                    // Core.SendSettingsToServer(Core.Settings, pckIn.steamId);

                                    //MyAPIGateway.Utilities.ShowMessage(Core.MODSAY, String.Format("兑换成功!"));
                                    MyAPIGateway.Utilities.ShowNotification("兑换成功!", 2000, MyFontEnum.Green);
                                    SyncPacket newpacket = new SyncPacket();
                                    newpacket.proto   = SyncPacket.Version;
                                    newpacket.command = (ushort)Command.MessageToChat;
                                    newpacket.message = "兑换成功!";
                                    Core.SendMessage(newpacket);         // send to others
                                    //Core.setSettings(pckIn.settings);

                                    //// resend for all clients a new settings
                                    //SyncPacket newpacket = new SyncPacket();
                                    //newpacket.proto = SyncPacket.Version;
                                    //newpacket.request = false;
                                    //newpacket.command = (ushort)Command.SettingsSync;
                                    //newpacket.steamId = 0; // for all
                                    //newpacket.settings = Core.Settings;
                                    //Core.SendMessage(newpacket);
                                }
                            }
                        }



                        //IMyPlayer player = MyAPIGateway.Session.Player as IMyPlayer;
                        //if (player != null)
                        //{
                        //    MyEntity entity = player.Character.Entity as MyEntity;
                        //    if (entity.HasInventory)
                        //    {
                        //        IMyInventory inventory = entity.GetInventoryBase() as MyInventory;
                        //        if (!inventory.ContainItems(1000, new MyObjectBuilder_Ingot { SubtypeName = "Iron" }))
                        //        {
                        //            inventory.AddItems(1, new MyObjectBuilder_Ingot { SubtypeName = "Iron" });
                        //            Logger.Log.Info("Some one with steamid={0} trying to redeemed", pckIn.steamId);
                        //            //terminalBlock.RefreshCustomInfo();
                        //        }
                        //    }

                        //    // resend for all clients a new settings
                        //    SyncPacket newpacket = new SyncPacket();
                        //    newpacket.proto = SyncPacket.Version;
                        //    newpacket.request = false;
                        //    newpacket.command = (ushort)Command.Redeem;
                        //    newpacket.steamId = 0; // for all
                        //    newpacket.message = "兑换成功";
                        //    Core.SendMessage(newpacket);
                        //}
                        //else
                        //{
                        //    Logger.Log.Info("Some one with steamid={0} trying to redeem, no player", pckIn.steamId);
                        //}
                    }

                    break;
                }

                case Command.MessageToChat:
                {
                    MyAPIGateway.Utilities.ShowMessage(Core.MODSAY, pckIn.message);
                    break;
                }

                case Command.SettingsSync:
                {
                    if (pckIn.request)         // Settings sync request
                    {
                        if (Core.IsServer && Core.Settings != null)
                        {         // server send settings to client
                            Logger.Log.Info("Send sync packet with settings to user steamId {0}", pckIn.steamId);
                            SyncPacket pckOut = new SyncPacket();
                            pckOut.proto    = SyncPacket.Version;
                            pckOut.request  = false;
                            pckOut.command  = (ushort)Command.SettingsSync;
                            pckOut.steamId  = pckIn.steamId;
                            pckOut.settings = Core.Settings;
                            Core.SendMessage(pckOut, pckIn.steamId);
                        }
                    }
                    else
                    {
                        if (!Core.IsServer)
                        {         // setting sync only for clients
                            Logger.Log.Info("User config synced...");
                            // if settings changes or syncs...
                            Core.setSettings(pckIn.settings);
                            if (pckIn.steamId == 0)         // if steamid is zero, so we updating for all clients and notify this message
                            {
                                MyAPIGateway.Utilities.ShowNotification("设置已更新!", 2000, MyFontEnum.Green);
                            }
                        }
                    }
                    break;
                }

                case Command.SettingsChange:
                {
                    if (Core.IsServer)         // Only server can acccept this message
                    {
                        Logger.Log.Info("Some one with steamid={0} trying to change server settings", pckIn.steamId);
                        if (Core.IsAdmin(pckIn.steamId) || pckIn.steamId == MyAPIGateway.Session.Player.SteamUserId)
                        {
                            Logger.Log.Info("Server config changed by steamId {0}", pckIn.steamId);
                            Core.setSettings(pckIn.settings);

                            // resend for all clients a new settings
                            SyncPacket newpacket = new SyncPacket();
                            newpacket.proto    = SyncPacket.Version;
                            newpacket.request  = false;
                            newpacket.command  = (ushort)Command.SettingsSync;
                            newpacket.steamId  = 0;        // for all
                            newpacket.settings = Core.Settings;
                            Core.SendMessage(newpacket);
                        }
                    }
                    break;
                }

                case Command.SyncOff:
                {
                    break;
                }

                case Command.SyncOn:
                {
                    break;
                }

                default:
                {
                    break;
                }
                }
            }
            catch (Exception ex)
            {
                Logger.Log.Error("Exception at BeaconSecurity.OnSyncRequest(): {0}", ex.Message);
                return;
            }
        }
Beispiel #8
0
        public static IMyInventory GetInventory(this IMyTerminalBlock block, int index)
        {
            MyEntity entity = block as MyEntity;

            return(entity?.HasInventory ? (entity.GetInventoryBase(index) as IMyInventory) : null);
        }
Beispiel #9
0
        //
        // == SessionComponent Hooks
        //
        public override void UpdateBeforeSimulation()
        {
            try
            {
                if (MyAPIGateway.Session == null || MyAPIGateway.Utilities == null || MyAPIGateway.Multiplayer == null) // exit if api is not ready
                {
                    return;
                }

                if (!Inited) // init and set handlers
                {
                    Init();
                }

                if (Settings == null) // request or load setting
                {
                    GetSettings();    // if server, settings will be set a this call, so it safe
                }
                if (!IsServer)        // if client exit at this point. Cleaning works only on server side.
                {
                    return;
                }

                if (Codes == null)
                {
                    GetCodes();
                }

                Frame = frameShift++;
                if (Frame % 3600 != 0)
                {
                    return;
                }

                List <IMyPlayer> players = new List <IMyPlayer>();

                //MyAPIGateway.Players.GetPlayers(players, x => x.Controller != null && x.Controller.ControlledEntity != null);
                MyAPIGateway.Players.GetPlayers(players, x => x.Character != null && !x.IsBot);
                foreach (IMyPlayer player in players)
                {
                    if (player.Character is IMyCharacter)
                    {
                        MyEntity entity = player.Character.Entity as MyEntity;
                        if (entity.HasInventory)
                        {
                            IMyInventory inventory = entity.GetInventoryBase() as MyInventory;
                            if (!inventory.ContainItems(Settings.SalaryMax, new MyObjectBuilder_Ingot {
                                SubtypeName = "Coin"
                            }))
                            {
                                inventory.AddItems(Settings.SalaryPerMinute, new MyObjectBuilder_Ingot {
                                    SubtypeName = "Coin"
                                });
                                //terminalBlock.RefreshCustomInfo();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log.Error("EXCEPTION at BeaconSecurity.UpdateBeforeSimulation(): {0} {1}", ex.Message, ex.StackTrace);
            }
        }