private void Character_OnClosing(MyEntity obj)
        {
            System.Diagnostics.Debug.Assert(obj is MyCharacter, "Entity is not character!");
            System.Diagnostics.Debug.Assert(obj == Character, "Called from another entity!");
            System.Diagnostics.Debug.Assert(Character.IsDead, "Called but character is not dead!");
            System.Diagnostics.Debug.Assert(m_spawnInventory != null, "Inventory was not set!");

            Character.OnClosing -= Character_OnClosing;

            if (m_spawnInventory != null && m_spawnInventory.GetItemsCount() > 0)
            {
                MyContainerDefinition containerDefinition;
                if (!MyComponentContainerExtension.TryGetContainerDefinition(Character.Definition.InventorySpawnContainerId.Value.TypeId, Character.Definition.InventorySpawnContainerId.Value.SubtypeId, out containerDefinition))
                {
                    // Backward compatibility - old definition id is with MyObjectBuilder_EntityBase
                    MyDefinitionId compatIventorySpawnContainerId = new MyDefinitionId(typeof(MyObjectBuilder_InventoryBagEntity), Character.Definition.InventorySpawnContainerId.Value.SubtypeId);
                    MyComponentContainerExtension.TryGetContainerDefinition(compatIventorySpawnContainerId.TypeId, compatIventorySpawnContainerId.SubtypeId, out containerDefinition);
                }

                if (containerDefinition != null)
                {
                    Character.Components.Remove <MyInventoryBase>();
                    if (Sync.IsServer)
                    {
                        var bagEntityId = SpawnInventoryContainer(Character.Definition.InventorySpawnContainerId.Value, m_spawnInventory, false);
                    }
                }
                else
                {
                    System.Diagnostics.Debug.Fail("The provided definiton of the container was not found!");
                }
            }
        }
예제 #2
0
        private static double GetInventoryVolumeInternal(MyDefinitionId id)
        {
            MyContainerDefinition container;

            if (MyComponentContainerExtension.TryGetContainerDefinition(id.TypeId, id.SubtypeId, out container) && container.DefaultComponents != null)
            {
                foreach (var component in container.DefaultComponents)
                {
                    MyComponentDefinitionBase componentDefinition = null;
                    if (!MyComponentContainerExtension.TryGetComponentDefinition(component.BuilderType,
                                                                                 component.SubtypeId ?? id.SubtypeId, out componentDefinition))
                    {
                        continue;
                    }
                    var invDef = componentDefinition as MyInventoryComponentDefinition;
                    if (invDef != null)
                    {
                        return(invDef.Volume * 1000);
                    }
                }
            }

            var def = MyDefinitionManager.Static.GetCubeBlockDefinition(id);

            if (def is MyCargoContainerDefinition)
            {
                return((def as MyCargoContainerDefinition).InventorySize.Volume * 1000);
            }
            return(0.0);
        }
예제 #3
0
        private void SpawnBackpack(MyEntity obj)
        {
            MyInventory inventory = new MyInventory();

            inventory.Init(this.m_spawnInventory.GetObjectBuilder());
            this.m_spawnInventory = inventory;
            if (this.m_spawnInventory != null)
            {
                MyContainerDefinition definition;
                if (!MyComponentContainerExtension.TryGetContainerDefinition(base.Character.Definition.InventorySpawnContainerId.Value.TypeId, base.Character.Definition.InventorySpawnContainerId.Value.SubtypeId, out definition))
                {
                    MyDefinitionId id = new MyDefinitionId(typeof(MyObjectBuilder_InventoryBagEntity), base.Character.Definition.InventorySpawnContainerId.Value.SubtypeId);
                    MyComponentContainerExtension.TryGetContainerDefinition(id.TypeId, id.SubtypeId, out definition);
                }
                if (((definition != null) && Sync.IsServer) && !MyFakes.USE_GPS_AS_FRIENDLY_SPAWN_LOCATIONS)
                {
                    MyGps gps1 = new MyGps();
                    gps1.ShowOnHud      = true;
                    gps1.Name           = new StringBuilder().AppendStringBuilder(MyTexts.Get(MySpaceTexts.GPS_Body_Location_Name)).Append(" - ").AppendFormatedDateTime(DateTime.Now).ToString();
                    gps1.DisplayName    = MyTexts.GetString(MySpaceTexts.GPS_Body_Location_Name);
                    gps1.DiscardAt      = null;
                    gps1.Coords         = base.Character.PositionComp.GetPosition();
                    gps1.Description    = "";
                    gps1.AlwaysVisible  = true;
                    gps1.GPSColor       = new Color(0x75, 0xc9, 0xf1);
                    gps1.IsContainerGPS = true;
                    MyGps gps = gps1;
                    MySession.Static.Gpss.SendAddGps(base.Character.DeadPlayerIdentityId, ref gps, this.SpawnInventoryContainer(base.Character.Definition.InventorySpawnContainerId.Value, this.m_spawnInventory, false, base.Character.DeadPlayerIdentityId), false);
                }
            }
        }
예제 #4
0
        private static void AddItemToLootBag(MyEntity itemOwner, MyPhysicalInventoryItem item, ref MyEntity lootBagEntity)
        {
            MyLootBagDefinition lootBagDefinition = MyDefinitionManager.Static.GetLootBagDefinition();

            if (lootBagDefinition != null)
            {
                MyDefinitionBase itemDefinition = item.GetItemDefinition();
                if (itemDefinition != null)
                {
                    if ((lootBagEntity == null) && (lootBagDefinition.SearchRadius > 0f))
                    {
                        Vector3D        position         = itemOwner.PositionComp.GetPosition();
                        BoundingSphereD boundingSphere   = new BoundingSphereD(position, (double)lootBagDefinition.SearchRadius);
                        List <MyEntity> entitiesInSphere = MyEntities.GetEntitiesInSphere(ref boundingSphere);
                        double          maxValue         = double.MaxValue;
                        foreach (MyEntity entity in entitiesInSphere)
                        {
                            if (entity.MarkedForClose)
                            {
                                continue;
                            }
                            if ((entity.GetType() == typeof(MyEntity)) && ((entity.DefinitionId != null) && (entity.DefinitionId.Value == lootBagDefinition.ContainerDefinition)))
                            {
                                double num2 = (entity.PositionComp.GetPosition() - position).LengthSquared();
                                if (num2 < maxValue)
                                {
                                    lootBagEntity = entity;
                                    maxValue      = num2;
                                }
                            }
                        }
                        entitiesInSphere.Clear();
                    }
                    if ((lootBagEntity == null) || (lootBagEntity.Components.Has <MyInventoryBase>() && !(lootBagEntity.Components.Get <MyInventoryBase>() as MyInventory).CanItemsBeAdded(item.Amount, itemDefinition.Id)))
                    {
                        MyContainerDefinition definition2;
                        lootBagEntity = null;
                        if (MyComponentContainerExtension.TryGetContainerDefinition(lootBagDefinition.ContainerDefinition.TypeId, lootBagDefinition.ContainerDefinition.SubtypeId, out definition2))
                        {
                            lootBagEntity = SpawnBagAround(itemOwner, definition2, 3, 2, 5, 1f);
                        }
                    }
                    if (lootBagEntity != null)
                    {
                        MyInventory inventory = lootBagEntity.Components.Get <MyInventoryBase>() as MyInventory;
                        if (inventory != null)
                        {
                            if (itemDefinition is MyCubeBlockDefinition)
                            {
                                inventory.AddBlocks(itemDefinition as MyCubeBlockDefinition, item.Amount);
                            }
                            else
                            {
                                inventory.AddItems(item.Amount, item.Content);
                            }
                        }
                    }
                }
            }
        }
예제 #5
0
        private long SpawnInventoryContainer(MyDefinitionId bagDefinition, MyInventory inventory, bool spawnAboveCharacter = 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(0);
            }

            MyEntity builder     = Character;
            var      worldMatrix = Character.WorldMatrix;

            if (spawnAboveCharacter)
            {
                worldMatrix.Translation += worldMatrix.Up + worldMatrix.Forward;
            }
            else
            {
                Vector3 modelCenter         = Character.Render.GetModel().BoundingBox.Center;
                Vector3 translationToCenter = Vector3.Transform(modelCenter, worldMatrix);
                worldMatrix.Translation = translationToCenter;
            }

            MyContainerDefinition containerDefinition;

            if (!MyComponentContainerExtension.TryGetContainerDefinition(bagDefinition.TypeId, bagDefinition.SubtypeId, out containerDefinition))
            {
                System.Diagnostics.Debug.Fail("Entity container definition: " + bagDefinition.ToString() + " was not found!");
                return(0);
            }

            MyEntity entity = MyEntities.CreateFromComponentContainerDefinitionAndAdd(containerDefinition.Id);

            System.Diagnostics.Debug.Assert(entity != null);
            if (entity == null)
            {
                return(0);
            }

            entity.PositionComp.SetWorldMatrix(worldMatrix);

            entity.Physics.LinearVelocity  = builder.Physics.LinearVelocity;
            entity.Physics.AngularVelocity = builder.Physics.AngularVelocity;

            //GR: Change color of spawned backpack to much character color
            entity.Render.EnableColorMaskHsv = true;
            entity.Render.ColorMaskHsv       = Character.Render.ColorMaskHsv;

            inventory.RemoveEntityOnEmpty = true;
            entity.Components.Add <MyInventoryBase>(inventory);

            return(entity.EntityId);
        }
예제 #6
0
        private unsafe long SpawnInventoryContainer(MyDefinitionId bagDefinition, MyInventory inventory, bool spawnAboveCharacter = true, long ownerIdentityId = 0L)
        {
            MyContainerDefinition definition;

            if ((MySession.Static == null) || !MySession.Static.Ready)
            {
                return(0L);
            }
            MyEntity character   = base.Character;
            MatrixD  worldMatrix = base.Character.WorldMatrix;

            if (spawnAboveCharacter)
            {
                MatrixD *xdPtr1 = (MatrixD *)ref worldMatrix;
                xdPtr1.Translation += worldMatrix.Up + worldMatrix.Forward;
            }
            else
            {
                MatrixD *xdPtr2 = (MatrixD *)ref worldMatrix;
                xdPtr2.Translation = base.Character.PositionComp.WorldAABB.Center + (worldMatrix.Backward * 0.40000000596046448);
            }
            if (!MyComponentContainerExtension.TryGetContainerDefinition(bagDefinition.TypeId, bagDefinition.SubtypeId, out definition))
            {
                return(0L);
            }
            MyEntity entity2 = MyEntities.CreateFromComponentContainerDefinitionAndAdd(definition.Id, false, true);

            if (entity2 == null)
            {
                return(0L);
            }
            MyInventoryBagEntity entity3 = entity2 as MyInventoryBagEntity;

            if (entity3 != null)
            {
                entity3.OwnerIdentityId = ownerIdentityId;
            }
            entity2.PositionComp.SetWorldMatrix(worldMatrix, null, false, true, true, false, false, false);
            entity2.Physics.LinearVelocity    = character.Physics.LinearVelocity;
            entity2.Physics.AngularVelocity   = character.Physics.AngularVelocity;
            entity2.Render.EnableColorMaskHsv = true;
            entity2.Render.ColorMaskHsv       = base.Character.Render.ColorMaskHsv;
            inventory.RemoveEntityOnEmpty     = true;
            entity2.Components.Add <MyInventoryBase>(inventory);
            return(entity2.EntityId);
        }
예제 #7
0
        void confirmButton_OnButtonClick(MyGuiControlButton sender)
        {
            foreach (var selection in m_removeComponentsListBox.SelectedItems)
            {
                MyComponentContainerExtension.TryRemoveComponent(m_entityId, (selection.UserData as Type));
            }

            foreach (var addComp in m_addComponentsListBox.SelectedItems)
            {
                if (addComp.UserData is MyDefinitionId)
                {
                    MyComponentContainerExtension.TryAddComponent(m_entityId, (MyDefinitionId)addComp.UserData);
                }
            }

            CloseScreen();
        }
예제 #8
0
        private static MyEntity SpawnBagAround(MyEntity itemOwner, MyContainerDefinition bagDefinition, int sideCheckCount = 3, int frontCheckCount = 2, int upCheckCount = 5, float stepSize = 1f)
        {
            MatrixD  xd;
            Vector3D?nullable      = null;
            MyModel  modelOnlyData = null;

            foreach (MyContainerDefinition.DefaultComponent component in bagDefinition.DefaultComponents)
            {
                if (typeof(MyObjectBuilder_ModelComponent).IsAssignableFrom((System.Type)component.BuilderType))
                {
                    MyComponentDefinitionBase componentDefinition = null;
                    MyStringHash subtypeId = bagDefinition.Id.SubtypeId;
                    if (component.SubtypeId != null)
                    {
                        subtypeId = component.SubtypeId.Value;
                    }
                    if (MyComponentContainerExtension.TryGetComponentDefinition(component.BuilderType, subtypeId, out componentDefinition))
                    {
                        MyModelComponentDefinition definition = componentDefinition as MyModelComponentDefinition;
                        if (definition != null)
                        {
                            modelOnlyData = MyModels.GetModelOnlyData(definition.Model);
                        }
                    }
                    break;
                }
            }
            if (modelOnlyData == null)
            {
                return(null);
            }
            float   radius = modelOnlyData.BoundingBox.HalfExtents.Max();
            HkShape shape  = (HkShape) new HkSphereShape(radius);

            try
            {
                Vector3  vector3;
                Vector3  vector5;
                Vector3  vector6;
                int      num4;
                Vector3D vectord3;
                int      num5;
                Vector3D translation = itemOwner.PositionComp.WorldMatrix.Translation;
                float    num2        = radius * stepSize;
                Vector3  up          = -MyGravityProviderSystem.CalculateNaturalGravityInPoint(itemOwner.PositionComp.WorldMatrix.Translation);
                if (up == Vector3.Zero)
                {
                    up = Vector3.Up;
                }
                else
                {
                    up.Normalize();
                }
                up.CalculatePerpendicularVector(out vector3);
                Vector3 vector4 = Vector3.Cross(vector3, up);
                vector4.Normalize();
                Quaternion identity     = Quaternion.Identity;
                Vector3[]  vectorArray  = new Vector3[] { vector3, vector4, -vector3, -vector4 };
                Vector3[]  vectorArray2 = new Vector3[] { vector4, -vector3, -vector4, vector3 };
                int        index        = 0;
                goto TR_0026;
TR_000D:
                if (nullable == null)
                {
                    MyOrientedBoundingBoxD xd3     = new MyOrientedBoundingBoxD(itemOwner.PositionComp.LocalAABB, itemOwner.PositionComp.WorldMatrix);
                    Vector3D[]             corners = new Vector3D[8];
                    xd3.GetCorners(corners, 0);
                    float      minValue      = float.MinValue;
                    Vector3D[] vectordArray2 = corners;
                    int        num8          = 0;
                    while (true)
                    {
                        if (num8 >= vectordArray2.Length)
                        {
                            nullable = new Vector3D?(itemOwner.PositionComp.WorldMatrix.Translation);
                            if (minValue > 0f)
                            {
                                nullable = new Vector3D?(xd3.Center + (minValue * up));
                            }
                            break;
                        }
                        float num9 = Vector3.Dot((Vector3)(vectordArray2[num8] - xd3.Center), up);
                        minValue = Math.Max(minValue, num9);
                        num8++;
                    }
                }
                goto TR_0003;
TR_000E:
                index++;
                goto TR_0026;
TR_000F:
                num4++;
                goto TR_0022;
TR_0010:
                num5++;
TR_001E:
                while (true)
                {
                    if (num5 >= sideCheckCount)
                    {
                        goto TR_000F;
                    }
                    else if (nullable == null)
                    {
                        for (int i = 0; (i < upCheckCount) && (nullable == null); i++)
                        {
                            Vector3D pos = (vectord3 + ((num5 * num2) * vector6)) + ((i * num2) * up);
                            if (MyEntities.IsInsideWorld(pos) && !MyEntities.IsShapePenetrating(shape, ref pos, ref identity, 15))
                            {
                                BoundingSphereD sphere = new BoundingSphereD(pos, (double)radius);
                                if (MySession.Static.VoxelMaps.GetOverlappingWithSphere(ref sphere) == null)
                                {
                                    nullable = new Vector3D?(pos);
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        goto TR_000F;
                    }
                    break;
                }
                goto TR_0010;
TR_0022:
                while (true)
                {
                    if (num4 >= frontCheckCount)
                    {
                        goto TR_000E;
                    }
                    else if (nullable == null)
                    {
                        vectord3 = (((translation + (0.25f * vector5)) + (radius * vector5)) + ((num4 * num2) * vector5)) - (((0.5f * (sideCheckCount - 1)) * num2) * vector6);
                        num5     = 0;
                    }
                    else
                    {
                        goto TR_000E;
                    }
                    break;
                }
                goto TR_001E;
TR_0026:
                while (true)
                {
                    if (index >= vectorArray.Length)
                    {
                        goto TR_000D;
                    }
                    else if (nullable == null)
                    {
                        vector5 = vectorArray[index];
                        vector6 = vectorArray2[index];
                        num4    = 0;
                    }
                    else
                    {
                        goto TR_000D;
                    }
                    break;
                }
                goto TR_0022;
            }
            finally
            {
                shape.RemoveReference();
            }
TR_0003:
            xd             = itemOwner.PositionComp.WorldMatrix;
            xd.Translation = nullable.Value;
            MyEntity entity = MyEntities.CreateFromComponentContainerDefinitionAndAdd(bagDefinition.Id, false, true);

            if (entity == null)
            {
                return(null);
            }
            entity.PositionComp.SetWorldMatrix(xd, null, false, true, true, false, false, false);
            entity.Physics.LinearVelocity  = Vector3.Zero;
            entity.Physics.AngularVelocity = Vector3.Zero;
            return(entity);
        }
예제 #9
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);
        }
예제 #10
0
        public override void RecreateControls(bool contructor)
        {
            base.RecreateControls(contructor);

            // LABEL
            this.Controls.Add(new MyGuiControlLabel(new Vector2(0.0f, -0.46f), text: "Select components to remove and components to add", originAlign: MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER));

            // ENTITY SELECTION
            if (m_entitiesSelection == null)
            {
                m_entitiesSelection = new MyGuiControlCombobox();
                m_entitiesSelection.ItemSelected += EntitySelected;
            }

            m_entitiesSelection.Position    = new Vector2(0f, -0.42f);
            m_entitiesSelection.OriginAlign = MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER;

            m_entitiesSelection.ClearItems();
            foreach (var ent in m_entities)
            {
                m_entitiesSelection.AddItem(ent.EntityId, ent.ToString());
            }
            m_entitiesSelection.SelectItemByKey(m_entityId, false);

            this.Controls.Add(m_entitiesSelection);

            // ENTITY ID LABEL
            this.Controls.Add(new MyGuiControlLabel(new Vector2(0.0f, -0.39f), text: String.Format("EntityID = {0}", m_entityId), font: MyFontEnum.White, originAlign: MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER));

            // ENTITY NAME LABEL AND COMPONENTS
            MyEntity entity;

            if (MyEntities.TryGetEntityById(m_entityId, out entity))
            {
                this.Controls.Add(new MyGuiControlLabel(new Vector2(0.0f, -0.36f), text: String.Format("Name: {1}, Type: {0}", entity.GetType().Name, entity.DisplayNameText), font: MyFontEnum.White, originAlign: MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER));
            }

            // REMOVE COMPONENTS LABEL
            this.Controls.Add(new MyGuiControlLabel(new Vector2(-0.21f, -0.32f), text: "Select components to remove", originAlign: MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER));

            // COMPONENTS REMOVE SELECTION BOX
            if (m_removeComponentsListBox == null)
            {
                m_removeComponentsListBox = new MyGuiControlListbox();
            }
            m_removeComponentsListBox.ClearItems();
            m_removeComponentsListBox.MultiSelect = true;
            m_removeComponentsListBox.Name        = "RemoveComponents";
            List <Type> components;

            if (MyComponentContainerExtension.TryGetEntityComponentTypes(m_entityId, out components))
            {
                foreach (var component in components)
                {
                    MyGuiControlListbox.Item item = new MyGuiControlListbox.Item(text: new StringBuilder(component.Name), userData: component);
                    m_removeComponentsListBox.Add(item);
                }
                m_removeComponentsListBox.VisibleRowsCount = components.Count + 1;
            }
            m_removeComponentsListBox.Position    = new Vector2(-0.21f, 0f);
            m_removeComponentsListBox.OriginAlign = MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER;
            m_removeComponentsListBox.ItemSize    = new Vector2(0.38f, 0.036f);
            m_removeComponentsListBox.Size        = new Vector2(0.4f, 0.6f);
            this.Controls.Add(m_removeComponentsListBox);

            // ADD COMPONENTS LABEL
            this.Controls.Add(new MyGuiControlLabel(new Vector2(0.21f, -0.32f), text: "Select components to add", originAlign: MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER));

            // COMPONENTS ADD SELECTION BOX
            if (m_addComponentsListBox == null)
            {
                m_addComponentsListBox = new MyGuiControlListbox();
            }
            m_addComponentsListBox.ClearItems();
            m_addComponentsListBox.MultiSelect = true;
            m_addComponentsListBox.Name        = "AddComponents";
            components.Clear();

            List <MyDefinitionId> definitions = new List <MyDefinitionId>();

            MyDefinitionManager.Static.GetDefinedEntityComponents(ref definitions);

            foreach (var id in definitions)
            {
                var text = id.ToString();
                if (text.StartsWith("MyObjectBuilder_"))
                {
                    text = text.Remove(0, "MyObectBuilder_".Length + 1);
                }
                MyGuiControlListbox.Item item = new MyGuiControlListbox.Item(text: new StringBuilder(text), userData: id);
                m_addComponentsListBox.Add(item);
            }
            m_addComponentsListBox.VisibleRowsCount = definitions.Count + 1;
            m_addComponentsListBox.Position         = new Vector2(0.21f, 0f);
            m_addComponentsListBox.OriginAlign      = MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER;
            m_addComponentsListBox.ItemSize         = new Vector2(0.36f, 0.036f);
            m_addComponentsListBox.Size             = new Vector2(0.4f, 0.6f);
            this.Controls.Add(m_addComponentsListBox);

            m_confirmButton = new MyGuiControlButton(new Vector2(0.21f, 0.35f), MyGuiControlButtonStyleEnum.Default, new Vector2(0.2f, 0.05f), null, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, null, new System.Text.StringBuilder("Confirm"));
            m_cancelButton  = new MyGuiControlButton(new Vector2(-0.21f, 0.35f), MyGuiControlButtonStyleEnum.Default, new Vector2(0.2f, 0.05f), null, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, null, new System.Text.StringBuilder("Cancel"));

            this.Controls.Add(m_confirmButton);
            this.Controls.Add(m_cancelButton);

            m_confirmButton.ButtonClicked += confirmButton_OnButtonClick;
            m_cancelButton.ButtonClicked  += cancelButton_OnButtonClick;
        }
예제 #11
0
        /// <summary>
        /// Spawns bag around position given by "baseTransform", checks all 4 directions around - forwards (forward, right, backward, left) and on each such direction moves test sphere
        /// in 3 directions forward (frontChecks), sides (perpendicular to forward direction - rights) and up. If spawn position is not found then position above "worldAabbTopPosition"
        /// is selected.
        /// </summary>
        private static MyEntity SpawnBagAround(MyEntity itemOwner, MyContainerDefinition bagDefinition,
                                               int sideCheckCount = 3, int frontCheckCount = 2, int upCheckCount = 5, float stepSize = 1f)
        {
            Debug.Assert(Sandbox.Game.Multiplayer.Sync.IsServer);

            Vector3D?finalPos = null;

            // Model sphere
            MyModel bagModel = null;

            foreach (var componentDef in bagDefinition.DefaultComponents)
            {
                if (typeof(MyObjectBuilder_ModelComponent).IsAssignableFrom(componentDef.BuilderType))
                {
                    MyComponentDefinitionBase componentDefinition = null;
                    var componentSubtype = bagDefinition.Id.SubtypeId;
                    if (componentDef.SubtypeId.HasValue)
                    {
                        componentSubtype = componentDef.SubtypeId.Value;
                    }

                    if (MyComponentContainerExtension.TryGetComponentDefinition(componentDef.BuilderType, componentSubtype, out componentDefinition))
                    {
                        var modelComponentDef = componentDefinition as MyModelComponentDefinition;
                        Debug.Assert(modelComponentDef != null);
                        if (modelComponentDef != null)
                        {
                            bagModel = MyModels.GetModelOnlyData(modelComponentDef.Model);
                        }
                    }

                    break;
                }
            }

            Debug.Assert(bagModel != null);
            if (bagModel == null)
            {
                return(null);
            }

            float   bagBoxRadius = bagModel.BoundingBox.HalfExtents.Max();
            HkShape sphere       = new HkSphereShape(bagBoxRadius);

            try
            {
                Vector3D basePos = itemOwner.PositionComp.WorldMatrix.Translation;
                float    step    = bagBoxRadius * stepSize;

                // Calculate right, up and forward vectors from gravity
                Vector3 upDir = -MyGravityProviderSystem.CalculateNaturalGravityInPoint(itemOwner.PositionComp.WorldMatrix.Translation);
                if (upDir == Vector3.Zero)
                {
                    upDir = Vector3.Up;
                }
                else
                {
                    upDir.Normalize();
                }

                Vector3 forwardDir;
                upDir.CalculatePerpendicularVector(out forwardDir);

                Vector3 rightDir = Vector3.Cross(forwardDir, upDir);
                rightDir.Normalize();

                Vector3D   currentPos;
                Quaternion rot = Quaternion.Identity;

                Vector3[] forwards = new Vector3[]
                {
                    forwardDir,
                    rightDir,
                    -forwardDir,
                    -rightDir
                };

                Vector3[] rights = new Vector3[]
                {
                    rightDir,
                    -forwardDir,
                    -rightDir,
                    forwardDir
                };

                // All sides
                for (int i = 0; i < forwards.Length && finalPos == null; ++i)
                {
                    var forward = forwards[i];
                    var right   = rights[i];

                    // Move forward
                    for (int frontMove = 0; frontMove < frontCheckCount && finalPos == null; ++frontMove)
                    {
                        Vector3D sidePosBase = basePos + 0.25f * forward + bagBoxRadius * forward + frontMove * step * forward - 0.5f * (sideCheckCount - 1) * step * right;

                        // Move perp to forward
                        for (int sideMove = 0; sideMove < sideCheckCount && finalPos == null; ++sideMove)
                        {
                            // Move up
                            for (int upMove = 0; upMove < upCheckCount && finalPos == null; ++upMove)
                            {
                                currentPos = sidePosBase + sideMove * step * right + upMove * step * upDir;

                                if (MyEntities.IsInsideWorld(currentPos) && !MyEntities.IsShapePenetrating(sphere, ref currentPos, ref rot))
                                {
                                    BoundingSphereD boundingSphere     = new BoundingSphereD(currentPos, bagBoxRadius);
                                    MyVoxelBase     overlappedVoxelmap = MySession.Static.VoxelMaps.GetOverlappingWithSphere(ref boundingSphere);

                                    if (overlappedVoxelmap == null)
                                    {
                                        finalPos = currentPos;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }

                // If not found position then select position above aabb's top.
                if (finalPos == null)
                {
                    MyOrientedBoundingBoxD obb     = new MyOrientedBoundingBoxD((BoundingBoxD)itemOwner.PositionComp.LocalAABB, itemOwner.PositionComp.WorldMatrix);
                    Vector3D[]             corners = new Vector3D[8];
                    obb.GetCorners(corners, 0);
                    float dotUp = float.MinValue;
                    foreach (var corner in corners)
                    {
                        var localDot = Vector3.Dot(corner - obb.Center, upDir);
                        dotUp = Math.Max(dotUp, localDot);
                    }

                    finalPos = itemOwner.PositionComp.WorldMatrix.Translation;
                    Debug.Assert(dotUp > 0);
                    if (dotUp > 0)
                    {
                        finalPos = obb.Center + dotUp * upDir;
                    }
                }
            }
            finally
            {
                sphere.RemoveReference();
            }

            Debug.Assert(finalPos != null);

            MatrixD transform = itemOwner.PositionComp.WorldMatrix;

            transform.Translation = finalPos.Value;

            MyEntity bagEntity = MyEntities.CreateFromComponentContainerDefinitionAndAdd(bagDefinition.Id);

            if (bagEntity == null)
            {
                return(null);
            }

            bagEntity.PositionComp.SetWorldMatrix(transform);

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

            return(bagEntity);
        }
예제 #12
0
        /// <summary>
        /// Add the given inventory item to loot bag. If loot bag does not exist then it will be created.
        /// </summary>
        private static void AddItemToLootBag(MyEntity itemOwner, MyPhysicalInventoryItem item, ref MyEntity lootBagEntity)
        {
            Debug.Assert(Sandbox.Game.Multiplayer.Sync.IsServer);

            var lootBagDefinition = MyDefinitionManager.Static.GetLootBagDefinition();

            Debug.Assert(lootBagDefinition != null, "Loot bag not definined");
            if (lootBagDefinition == null)
            {
                return;
            }

            // Block
            MyDefinitionBase itemDefinition = item.GetItemDefinition();

            Debug.Assert(itemDefinition != null, "Unknown inventory item");
            if (itemDefinition == null)
            {
                return;
            }

            // Find lootbag nearby.
            if (lootBagEntity == null && lootBagDefinition.SearchRadius > 0)
            {
                Vector3D        itemOwnerPosition = itemOwner.PositionComp.GetPosition();
                BoundingSphereD sphere            = new BoundingSphereD(itemOwnerPosition, lootBagDefinition.SearchRadius);
                var             entitiesInSphere  = MyEntities.GetEntitiesInSphere(ref sphere);
                double          minDistanceSq     = double.MaxValue;
                foreach (var entity in entitiesInSphere)
                {
                    if (!entity.MarkedForClose && (entity.GetType() == typeof(MyEntity)))
                    {
                        if (entity.DefinitionId != null && entity.DefinitionId.Value == lootBagDefinition.ContainerDefinition)
                        {
                            var distanceSq = (entity.PositionComp.GetPosition() - itemOwnerPosition).LengthSquared();
                            if (distanceSq < minDistanceSq)
                            {
                                lootBagEntity = entity;
                                minDistanceSq = distanceSq;
                            }
                        }
                    }
                }
                entitiesInSphere.Clear();
            }

            // Create lootbag
            if (lootBagEntity == null ||
                (lootBagEntity.Components.Has <MyInventoryBase>() && !(lootBagEntity.Components.Get <MyInventoryBase>() as MyInventory).CanItemsBeAdded(item.Amount, itemDefinition.Id)))
            {
                lootBagEntity = null;
                MyContainerDefinition lootBagDef;
                if (MyComponentContainerExtension.TryGetContainerDefinition(lootBagDefinition.ContainerDefinition.TypeId, lootBagDefinition.ContainerDefinition.SubtypeId, out lootBagDef))
                {
                    lootBagEntity = SpawnBagAround(itemOwner, lootBagDef);
                }
            }

            Debug.Assert(lootBagEntity != null, "Loot bag not created");

            // Fill lootbag inventory
            if (lootBagEntity != null)
            {
                MyInventory inventory = lootBagEntity.Components.Get <MyInventoryBase>() as MyInventory;
                Debug.Assert(inventory != null);
                if (inventory != null)
                {
                    if (itemDefinition is MyCubeBlockDefinition)
                    {
                        inventory.AddBlocks(itemDefinition as MyCubeBlockDefinition, item.Amount);
                    }
                    else
                    {
                        inventory.AddItems(item.Amount, item.Content);
                    }
                }
            }
        }