Exemple #1
0
        public override void Execute(Data.Data data)
        {
            SessionHandler.EnqueueAction(() =>
            {
                var player = Utils.GetPlayer();
                if (player != null)
                {
                    var character = player.Character;
                    var inventory = character.GetInventory();
                    foreach (var planItem in character.BuildPlanner)
                    {
                        foreach (var component in planItem.Components)
                        {
                            var newObject = MyObjectBuilderSerializer.CreateNewObject(component.ComponentDefinition.Id);
                            if (inventory.AddItems(component.Count, newObject))
                            {
                                component.Count = 0;
                            }
                            else
                            {
                                var matrix = player.Character.WorldMatrix;
                                MyFloatingObjects.Spawn(component.ComponentDefinition, matrix.Translation, matrix.Forward, matrix.Up, component.Count);
                                component.Count = 0;
                            }
                        }

                        planItem.Components.RemoveAll(component => component.Count <= 0);
                    }
                    character.CleanFinishedBuildPlanner();
                }
            });
        }
Exemple #2
0
        public static void AddOrDropItem(MyPlayer player, MyPhysicalItemDefinition item, ref double amount, MatrixD position)
        {
            var inventory = player.Character.GetInventory();
            var newObject = MyObjectBuilderSerializer.CreateNewObject(item.Id);

            amount = TryAddToInventory(inventory, amount, newObject, item.Id);
            if (amount > 0)
            {
                var controlledEntity = player.Controller.ControlledEntity;
                if (controlledEntity is MyShipController controller)
                {
                    foreach (var gridInventory in controller.CubeGrid.Inventories)
                    {
                        amount = TryAddToInventory(gridInventory.GetInventory(), amount, newObject, item.Id);
                        if (amount <= Double.Epsilon)
                        {
                            break;
                        }
                    }
                }

                if (amount > 0)
                {
                    MyFloatingObjects.Spawn(item, position.Translation, position.Forward, position.Up, (int)Math.Ceiling(amount));
                    amount = 0;
                }
            }
        }
Exemple #3
0
        private static void FixTransferAmount(MyInventory src, MyInventory dst, MyPhysicalInventoryItem?srcItem, bool spawn, ref MyFixedPoint remove, ref MyFixedPoint add)
        {
            Debug.Assert(Sync.IsServer);
            if (srcItem.Value.Amount < remove)
            {
                remove = srcItem.Value.Amount;
                add    = remove;
            }

            if (!MySession.Static.CreativeMode && !src.Equals(dst))
            {
                MyFixedPoint space = dst.ComputeAmountThatFits(srcItem.Value.Content.GetId());
                if (space < remove)
                {
                    if (spawn)
                    {
                        MyEntity e = (dst.Owner as MyEntity);
                        Matrix   m = e.WorldMatrix;
                        MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(remove - space, srcItem.Value.Content), e.PositionComp.GetPosition() + m.Forward + m.Up, m.Forward, m.Up, e.Physics);
                    }
                    else
                    {
                        remove = space;
                    }
                    add = space;
                }
            }
        }
        public override void ProcessObjects(ListReader <MyDefinitionId> objects)
        {
            var allEntities = MyEntities.GetEntities();

            m_tmpSubtypes.Clear();
            foreach (var obj in objects)
            {
                m_tmpSubtypes.Add(obj.SubtypeId);
            }


            // Find floating objects in all objects
            foreach (var entity in allEntities)
            {
                MyFloatingObject floatingObject = entity as MyFloatingObject;
                if (floatingObject == null)
                {
                    continue;
                }

                // Check if not manipulated (in hand)
                if (MyManipulationTool.IsEntityManipulated(entity))
                {
                    continue;
                }

                MyDefinitionId defId = floatingObject.Item.Content.GetObjectId();

                // Check if they are marked as removable in Decay.sbc script file.
                if (m_tmpSubtypes.Contains(defId.SubtypeId))
                {
                    MyFloatingObjects.RemoveFloatingObject(floatingObject, true);
                }
            }
        }
Exemple #5
0
        private void SpawnEjection()
        {
            var eInfo    = Ejector.Info;
            var ejectDef = ActiveAmmoDef.AmmoDef.Ejection;

            if (ejectDef.Type == WeaponDefinition.AmmoDef.AmmoEjectionDef.SpawnType.Item && System.Session.IsServer)
            {
                var delay = (uint)ejectDef.CompDef.Delay;
                if (delay <= 0)
                {
                    MyFloatingObjects.Spawn(ActiveAmmoDef.AmmoDef.Const.EjectItem, eInfo.Position, eInfo.Direction, MyPivotUp, null, EjectionSpawnCallback);
                }
                else
                {
                    System.Session.FutureEvents.Schedule(EjectionDelayed, null, delay);
                }
            }
            else if (System.Session.HandlesInput)
            {
                var particle = ActiveAmmoDef.AmmoDef.AmmoGraphics.Particles.Eject;
                MyParticleEffect ejectEffect;
                var matrix = MatrixD.CreateTranslation(eInfo.Position);

                if (MyParticlesManager.TryCreateParticleEffect(particle.Name, ref matrix, ref eInfo.Position, uint.MaxValue, out ejectEffect))
                {
                    //ejectEffect.UserColorMultiplier = particle.Color;
                    var scaler = 1;
                    ejectEffect.UserRadiusMultiplier = particle.Extras.Scale * scaler;
                    //var scale = particle.ShrinkByDistance ? MathHelper.Clamp(MathHelper.Lerp(1, 0, Vector3D.Distance(System.Session.CameraPos, eInfo.Position) / particle.Extras.MaxDistance), 0.05f, 1) : 1;
                    //ejectEffect.UserScale = (float)scale * scaler;
                    ejectEffect.Velocity = eInfo.Direction * ActiveAmmoDef.AmmoDef.Ejection.Speed;
                }
            }
        }
        public MyEntity Spawn(MyFixedPoint amount, MatrixD worldMatrix, MyEntity owner = null)
        {
            if (Content is MyObjectBuilder_BlockItem)
            {
                Debug.Assert(MyFixedPoint.IsIntegral(amount), "Spawning fractional number of grids!");

                var blockItem = Content as MyObjectBuilder_BlockItem;
                var builder   = MyObjectBuilderSerializer.CreateNewObject(typeof(MyObjectBuilder_CubeGrid)) as MyObjectBuilder_CubeGrid;
                builder.GridSizeEnum           = MyCubeSize.Small;
                builder.IsStatic               = false;
                builder.PersistentFlags       |= MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.Enabled;
                builder.PositionAndOrientation = new MyPositionAndOrientation(worldMatrix);

                var block = MyObjectBuilderSerializer.CreateNewObject(blockItem.BlockDefId) as MyObjectBuilder_CubeBlock;
                builder.CubeBlocks.Add(block);

                MyCubeGrid firstGrid = null;
                for (int i = 0; i < amount; ++i)
                {
                    builder.EntityId = MyEntityIdentifier.AllocateId();
                    block.EntityId   = MyEntityIdentifier.AllocateId();
                    MyCubeGrid newGrid = MyEntities.CreateFromObjectBuilder(builder) as MyCubeGrid;
                    firstGrid = firstGrid ?? newGrid;
                    MyEntities.Add(newGrid);
                    Sandbox.Game.Multiplayer.MySyncCreate.SendEntityCreated(builder);
                }
                return(firstGrid);
            }
            else
            {
                return(MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(amount, Content), worldMatrix, owner != null ? owner.Physics : null));
            }
        }
Exemple #7
0
 private void EjectionDelayed(object o)
 {
     if (Comp.IsWorking && ActiveAmmoDef?.AmmoDef != null && ActiveAmmoDef.AmmoDef.Ejection.Type == WeaponDefinition.AmmoDef.AmmoEjectionDef.SpawnType.Item && !Ejector.NullEntity)
     {
         MyFloatingObjects.Spawn(ActiveAmmoDef.AmmoDef.Const.EjectItem, Ejector.Info.Position, Ejector.Info.Direction, MyPivotUp, null, EjectionSpawnCallback);
     }
 }
Exemple #8
0
        private void SpawnOrePieces(MyFixedPoint amountItems, MyFixedPoint maxAmountPerDrop, Vector3 hitPosition, MyObjectBuilder_PhysicalObject oreObjBuilder, MyVoxelMaterialDefinition voxelMaterial)
        {
            if (Sync.IsServer == false)
            {
                return;
            }

            ProfilerShort.Begin("SpawnOrePieces");
            var forward = Vector3.Normalize(m_sensor.FrontPoint - m_sensor.Center);
            //var pos = m_sensor.CutOutSphere.Center + forward * m_floatingObjectSpawnOffset;
            var            pos     = hitPosition - forward * m_floatingObjectSpawnRadius;
            BoundingSphere bsphere = new BoundingSphere(pos, m_floatingObjectSpawnRadius);

            while (amountItems > 0)
            {
                //new: MyFixedPoint dropAmount = amountItems;
                //original: MyFixedPoint dropAmount = MyFixedPoint.Min(amountItems, maxAmountPerDrop);
                MyFixedPoint dropAmount = MyFixedPoint.Min(amountItems, maxAmountPerDrop);
                amountItems -= dropAmount;
                var inventoryItem = new MyPhysicalInventoryItem(dropAmount, oreObjBuilder);
                var item          = MyFloatingObjects.Spawn(inventoryItem, bsphere, null, voxelMaterial);
                item.Physics.LinearVelocity  = MyUtils.GetRandomVector3HemisphereNormalized(forward) * MyUtils.GetRandomFloat(1.5f, 4);//original speed 5-8
                item.Physics.AngularVelocity = MyUtils.GetRandomVector3Normalized() * MyUtils.GetRandomFloat(4, 8);
            }
            ProfilerShort.End();
        }
Exemple #9
0
 internal void AmmoChange(object o)
 {
     try
     {
         var ammoChange = (AmmoLoad)o;
         if (ammoChange.Change == AmmoLoad.ChangeType.Add)
         {
             var oldType = System.AmmoTypes[ammoChange.OldId];
             if (Comp.BlockInventory.CanItemsBeAdded(ammoChange.Amount, oldType.AmmoDefinitionId))
             {
                 Comp.BlockInventory.AddItems(ammoChange.Amount, ammoChange.Item.Content);
             }
             else
             {
                 if (!Comp.Session.MpActive)
                 {
                     MyAPIGateway.Utilities.ShowNotification($"Weapon inventory full, ejecting {ammoChange.Item.Content.SubtypeName} magazine", 3000, "Red");
                 }
                 else if (Comp.Data.Repo.Base.State.PlayerId > 0)
                 {
                     var message = $"Weapon inventory full, ejecting {ammoChange.Item.Content.SubtypeName} magazine";
                     Comp.Session.SendClientNotify(Comp.Data.Repo.Base.State.PlayerId, message, true, "Red", 3000);
                 }
                 MyFloatingObjects.Spawn(ammoChange.Item, Dummies[0].Info.Position, MyPivotDir, MyPivotUp);
             }
         }
     }
     catch (Exception ex) { Log.Line($"Exception in AmmoChange: {ex} - {((AmmoLoad)o).Amount} - {((AmmoLoad)o).Item.Content.SubtypeName}"); }
 }
Exemple #10
0
        private bool ThrowFloatingObjectsFunc()
        {
            var view = MySession.Static.CameraController.GetViewMatrix();
            var inv  = Matrix.Invert(view);

            //MyPhysicalInventoryItem item = new MyPhysicalInventoryItem(100,
            var oreBuilder   = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>("Stone");
            var scrapBuilder = MyFloatingObject.ScrapBuilder;

            for (int i = 1; i <= 25; i++)
            {
                var item = new MyPhysicalInventoryItem((MyRandom.Instance.Next() % 200) + 1, oreBuilder);
                var obj  = MyFloatingObjects.Spawn(item, inv.Translation + inv.Forward * i * 1.0f, inv.Forward, inv.Up);
                obj.Physics.LinearVelocity = inv.Forward * 50;
            }

            Vector3D scrapPos = inv.Translation;

            scrapPos.X += 10;
            for (int i = 1; i <= 25; i++)
            {
                var item = new MyPhysicalInventoryItem((MyRandom.Instance.Next() % 200) + 1, scrapBuilder);
                var obj  = MyFloatingObjects.Spawn(item, scrapPos + inv.Forward * i * 1.0f, inv.Forward, inv.Up);
                obj.Physics.LinearVelocity = inv.Forward * 50;
            }

            return(true);
        }
        public void TakeFloatingObject(MyFloatingObject obj)
        {
            MyFixedPoint amount = obj.Item.Amount;

            if (MyPerGameSettings.ConstrainInventory())
            {
                amount = MyFixedPoint.Min(ComputeAmountThatFits(obj.Item.Content.GetObjectId()), amount);
            }
            if (amount > 0)
            {
                if (Sync.IsServer)
                {
                    if (obj.MarkedForClose)
                    {
                        return;
                    }
                    MyFloatingObjects.RemoveFloatingObject(obj, amount);
                    AddItemsInternal(amount, obj.Item.Content);
                    SyncObject.SendAddItemsAnnounce(this, amount, obj.Item.Content);
                }
                else
                {
                    SyncObject.TakeFloatingObjectRequest(this, obj);
                }
            }
        }
 private void EjectionDelayed(object o)
 {
     if (ActiveAmmoDef?.ConsumableDef != null && !Ejector.NullEntity)
     {
         MyFloatingObjects.Spawn(ActiveAmmoDef.ConsumableDef.Const.EjectItem, Ejector.Info.Position, Ejector.Info.Direction, MyPivotUp, null, EjectionSpawnCallback);
     }
 }
        static void RemoveFloatingObjectSuccess(ref RemoveFloatingObjectMsg msg, MyNetworkClient sender)
        {
            MyFloatingObject floatingObject;

            if (MyEntities.TryGetEntityById <MyFloatingObject>(msg.EntityId, out floatingObject))
            {
                MyFloatingObjects.RemoveFloatingObject(floatingObject, msg.Amount);
            }
        }
Exemple #14
0
        static void RemoveFloatingObjectRequest(ref RemoveFloatingObjectMsg msg, MyNetworkClient sender)
        {
            Debug.Assert(Sync.IsServer);
            MyFloatingObject floatingObject;

            if (MyEntities.TryGetEntityById <MyFloatingObject>(msg.EntityId, out floatingObject))
            {
                MyFloatingObjects.RemoveFloatingObject(floatingObject, msg.Amount);
            }
        }
Exemple #15
0
        private void TransferRemainingComponents()
        {
            int pos = 0;

            try
            {
                MyCubeBlockDefinition blockDefinition = (MyCubeBlockDefinition)m_targetBlock.BlockDefinition;
                Dictionary <string, MyTuple <int, MyPhysicalItemDefinition> > components = new Dictionary <string, MyTuple <int, MyPhysicalItemDefinition> >();
                foreach (var item in blockDefinition.Components)
                {
                    var inventoryItem = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(item.DeconstructItem.Id);
                    if (!components.ContainsKey(item.DeconstructItem.Id.SubtypeName))
                    {
                        components.Add(item.DeconstructItem.Id.SubtypeName, new MyTuple <int, MyPhysicalItemDefinition>(item.Count, item.DeconstructItem));
                    }
                    else
                    {
                        components[item.DeconstructItem.Id.SubtypeName] = new MyTuple <int, MyPhysicalItemDefinition>(components[item.DeconstructItem.Id.SubtypeName].Item1 + item.Count, item.DeconstructItem);
                    }
                }
                pos = 1;

                foreach (var item in m_missingComponents)
                {
                    if (components.ContainsKey(item.Key))
                    {
                        components[item.Key] = new MyTuple <int, MyPhysicalItemDefinition>(components[item.Key].Item1 - item.Value, components[item.Key].Item2);
                    }

                    if (components[item.Key].Item1 <= 0)
                    {
                        components.Remove(item.Key);
                    }
                }
                pos = 2;
                foreach (var item in components)
                {
                    TransferFromItem((MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(item.Value.Item2.Id), item.Value.Item1);
                }
                pos = 3;
                foreach (var item in m_inventory)
                {
                    MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(item.Value.Item1, item.Value.Item2), Vector3D.Transform(m_targetBlock.Position * m_targetBlock.CubeGrid.GridSize, m_targetBlock.CubeGrid.WorldMatrix), m_targetBlock.CubeGrid.WorldMatrix.Forward, m_targetBlock.CubeGrid.WorldMatrix.Up);
                }
            }
            catch (Exception ex)
            {
                Logging.Instance.WriteLine(string.Format("Error {0}: {1}", pos, ex.ToString()));
            }
        }
Exemple #16
0
        private void TransferFromItem(MyObjectBuilder_PhysicalObject item, int count)
        {
            MyInventory targetInventory = ((MyCubeBlock)m_constructionBlock.ConstructionBlock).GetInventory();

            if (targetInventory.CanItemsBeAdded(count, item.GetId()))
            {
                targetInventory.AddItems(count, item);
                return;
            }

            var inventoryItem = new MyPhysicalInventoryItem(count, item);

            MyFloatingObjects.Spawn(inventoryItem, Vector3D.Transform(m_targetBlock.Position * m_targetBlock.CubeGrid.GridSize,
                                                                      m_targetBlock.CubeGrid.WorldMatrix), m_targetBlock.CubeGrid.WorldMatrix.Forward, m_targetBlock.CubeGrid.WorldMatrix.Up);
        }
 private void AffectAddBySurvival(ref MyFixedPoint amount, MyObjectBuilder_PhysicalObject objectBuilder)
 {
     Debug.Assert(Sync.IsServer);
     MyFixedPoint space = ComputeAmountThatFits(objectBuilder.GetObjectId());
     if (space < amount)
     {
         if (Owner != null && Owner.InventoryOwnerType == MyInventoryOwnerTypeEnum.Character)
         {
             MyCharacter c = (Owner as MyCharacter);
             Matrix m = c.GetHeadMatrix(true);
             MyEntity entity = MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(amount - space, objectBuilder), m.Translation, m.Forward, m.Up, c.Physics);
             entity.Physics.ApplyImpulse(m.Forward.Cross(m.Up), c.PositionComp.GetPosition());
         }
         amount = space;
     }
 }
Exemple #18
0
        public override void Execute(Data.Data data, Dictionary <string, object> parameters)
        {
            SessionHandler.EnqueueAction(() =>
            {
                var player = Utils.GetPlayer();
                if (player != null)
                {
                    var character = player.Character;

                    var inventory = player.Character.GetInventory();
                    foreach (var physicalInventoryItem in inventory.GetItems())
                    {
                        MyFloatingObjects.EnqueueInventoryItemSpawn(physicalInventoryItem, character.PositionComp.WorldAABB, character.Physics.GetVelocityAtPoint(player.GetPosition()));
                    }
                    inventory.Clear();
                }
            });
        }
Exemple #19
0
        static void HavokWorld_EntityLeftWorld(HkEntity hkEntity)
        {
            var entities = hkEntity.GetAllEntities();

            foreach (var entity in entities)
            {
                if (Sandbox.Game.Multiplayer.Sync.IsServer && entity != null)
                {
                    // HACK: due to not working Close or MarkForClose correctly
                    if (entity is Sandbox.Game.Entities.Character.MyCharacter)
                    {
                        ((Sandbox.Game.Entities.Character.MyCharacter)entity).DoDamage(1000, MyDamageType.Suicide, true);
                    }
                    else if (entity is MyVoxelMap || entity is MyCubeBlock)
                    {
                    }
                    else if (entity is MyCubeGrid)
                    {
                        var grid = ((MyCubeGrid)entity);
                        if (entity.SyncObject != null)
                        {
                            grid.SyncObject.SendCloseRequest();
                        }
                        else
                        {
                            grid.Close();
                        }
                    }
                    else if (entity is MyFloatingObject)
                    {
                        MyFloatingObjects.RemoveFloatingObject((MyFloatingObject)entity);
                    }
                    else if (entity is MyFracturedPiece)
                    {
                        Sandbox.Game.GameSystems.MyFracturedPiecesManager.Static.RemoveFracturePiece((MyFracturedPiece)entity, 0);
                    }
                    else if (entity.SyncObject != null)
                    {
                        entity.SyncObject.SendCloseRequest();
                    }
                }
            }
            entities.Clear();
        }
Exemple #20
0
 public static void Spawn(this MyPhysicalInventoryItem thisItem, MyFixedPoint amount, MatrixD worldMatrix, MyEntity owner, Action <MyEntity> completionCallback)
 {
     if ((amount >= 0) && (thisItem.Content != null))
     {
         if (thisItem.Content is MyObjectBuilder_BlockItem)
         {
             if (typeof(MyObjectBuilder_CubeBlock).IsAssignableFrom((System.Type)thisItem.Content.GetObjectId().TypeId))
             {
                 MyCubeBlockDefinition     definition;
                 MyObjectBuilder_BlockItem content = thisItem.Content as MyObjectBuilder_BlockItem;
                 MyDefinitionManager.Static.TryGetCubeBlockDefinition(content.BlockDefId, out definition);
                 if (definition != null)
                 {
                     MyObjectBuilder_CubeGrid objectBuilder = MyObjectBuilderSerializer.CreateNewObject(typeof(MyObjectBuilder_CubeGrid)) as MyObjectBuilder_CubeGrid;
                     objectBuilder.GridSizeEnum           = definition.CubeSize;
                     objectBuilder.IsStatic               = false;
                     objectBuilder.PersistentFlags       |= MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.Enabled;
                     objectBuilder.PositionAndOrientation = new MyPositionAndOrientation(worldMatrix);
                     MyObjectBuilder_CubeBlock item = MyObjectBuilderSerializer.CreateNewObject(content.BlockDefId) as MyObjectBuilder_CubeBlock;
                     if (item != null)
                     {
                         item.Min = (SerializableVector3I)(((definition.Size / 2) - definition.Size) + Vector3I.One);
                         objectBuilder.CubeBlocks.Add(item);
                         for (int i = 0; i < amount; i++)
                         {
                             objectBuilder.EntityId = MyEntityIdentifier.AllocateId(MyEntityIdentifier.ID_OBJECT_TYPE.ENTITY, MyEntityIdentifier.ID_ALLOCATION_METHOD.RANDOM);
                             item.EntityId          = MyEntityIdentifier.AllocateId(MyEntityIdentifier.ID_OBJECT_TYPE.ENTITY, MyEntityIdentifier.ID_ALLOCATION_METHOD.RANDOM);
                             Vector3D?relativeOffset = null;
                             MyEntities.CreateFromObjectBuilderParallel(objectBuilder, true, completionCallback, null, null, relativeOffset, false, false);
                         }
                     }
                 }
             }
         }
         else
         {
             MyPhysicalItemDefinition definition = null;
             if (MyDefinitionManager.Static.TryGetPhysicalItemDefinition(thisItem.Content.GetObjectId(), out definition))
             {
                 MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(amount, thisItem.Content, 1f), worldMatrix, owner?.Physics, completionCallback);
             }
         }
     }
 }
Exemple #21
0
        private void OpenBag(IMyEntity bagEntity)
        {
            try
            {
                MyInventoryBagEntity bag = bagEntity as MyInventoryBagEntity;
                if (bag == null)
                {
                    return;
                }

                foreach (var item in bag.GetInventory().GetItems().ToList())
                {
                    MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(item.Amount, item.Content), bagEntity.WorldMatrix.Translation, bagEntity.WorldMatrix.Forward, bagEntity.WorldMatrix.Up);
                }

                bagEntity.Close();
            }
            catch (Exception ex)
            { Logging.Instance.WriteLine(string.Format("OpenBag Error(): {0}", ex.ToString())); }
        }
Exemple #22
0
        private void CutTree(int itemInstanceId, Vector3D hitWorldPosition, Vector3 hitNormal, float forceMultiplier = 1.0f)
        {
            HkStaticCompoundShape shape = (HkStaticCompoundShape)Physics.RigidBody.GetShape();
            int physicsInstanceId;

            if (m_localIdToPhysicsShapeInstanceId.TryGetValue(itemInstanceId, out physicsInstanceId))
            {
                //Remove static tree
                MyEnvironmentItemData itemData = m_itemsData[itemInstanceId];

                RemoveItem(itemInstanceId, physicsInstanceId, sync: true, immediateUpdate: true);

                //Create fractured tree
                MyDefinitionId id             = new MyDefinitionId(Definition.ItemDefinitionType, itemData.SubtypeId);
                var            itemDefinition = MyDefinitionManager.Static.GetEnvironmentItemDefinition(id);
                if (MyModels.GetModelOnlyData(itemDefinition.Model).HavokBreakableShapes != null)
                {
                    CreateBreakableShape(itemDefinition, ref itemData, ref hitWorldPosition, hitNormal, forceMultiplier);
                }
                else
                {
                    ProfilerShort.Begin("Spawning tree");
                    // This is for SE when you hit a tree, it will create a floating object with the same model. In case it affects ME, it may be changed. Contact DusanA for it.
                    Debug.Assert(MyPerGameSettings.Game == GameEnum.SE_GAME);
                    MyPhysicalInventoryItem Item = new MyPhysicalInventoryItem()
                    {
                        Amount = 1, Content = new MyObjectBuilder_TreeObject()
                        {
                            SubtypeName = itemData.SubtypeId.ToString()
                        }
                    };
                    Vector3D pos     = itemData.Transform.Position;
                    Vector3D gravity = -MyGravityProviderSystem.CalculateNaturalGravityInPoint(pos);
                    gravity.Normalize();

                    MyFloatingObjects.Spawn(Item, pos + gravity, MyUtils.GetRandomPerpendicularVector(ref gravity), gravity);
                    ProfilerShort.End();
                }
            }
        }
        public MyEntity Spawn(MyFixedPoint amount, MatrixD worldMatrix, MyEntity owner = null)
        {
            if (Content is MyObjectBuilder_BlockItem)
            {
                var blockItem = Content as MyObjectBuilder_BlockItem;
                var builder   = Sandbox.Common.ObjectBuilders.Serializer.MyObjectBuilderSerializer.CreateNewObject(typeof(MyObjectBuilder_CubeGrid)) as MyObjectBuilder_CubeGrid;
                builder.EntityId               = MyEntityIdentifier.AllocateId();
                builder.GridSizeEnum           = MyCubeSize.Small;
                builder.IsStatic               = false;
                builder.PersistentFlags       |= MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.Enabled;
                builder.PositionAndOrientation = new MyPositionAndOrientation(worldMatrix);

                var block = Sandbox.Common.ObjectBuilders.Serializer.MyObjectBuilderSerializer.CreateNewObject(blockItem.BlockDefId) as MyObjectBuilder_CubeBlock;
                builder.CubeBlocks.Add(block);
                var newGrid = MyEntities.CreateFromObjectBuilder(builder) as MyCubeGrid;
                MyEntities.Add(newGrid);
                Sandbox.Game.Multiplayer.MySyncCreate.SendEntityCreated(builder);
                return(newGrid);
            }
            else
            {
                return(MyFloatingObjects.Spawn(new MyInventoryItem(amount, Content), worldMatrix, owner != null ? owner.Physics : null));
            }
        }
        private void AddItemsToInventory(int variant)
        {
            bool overrideCheck   = variant != 0;
            bool spawnNonfitting = variant != 0;
            bool componentsOnly  = variant == 2;

            IMyInventoryOwner invObject = MySession.ControlledEntity as IMyInventoryOwner;

            if (invObject != null)
            {
                MyInventory inventory = invObject.GetInventory(0);
                //inventory.Clear();

                if (!componentsOnly)
                {
                    MyObjectBuilder_AmmoMagazine ammoMag = new MyObjectBuilder_AmmoMagazine();
                    ammoMag.SubtypeName      = "NATO_5p56x45mm";
                    ammoMag.ProjectilesCount = 50;
                    AddItems(inventory, ammoMag, false, 5);

                    MyObjectBuilder_AmmoMagazine ammoMag2 = new MyObjectBuilder_AmmoMagazine();
                    ammoMag2.SubtypeName      = "NATO_25x184mm";
                    ammoMag2.ProjectilesCount = 50;
                    AddItems(inventory, ammoMag2, false);

                    MyObjectBuilder_AmmoMagazine ammoMag3 = new MyObjectBuilder_AmmoMagazine();
                    ammoMag3.SubtypeName      = "Missile200mm";
                    ammoMag3.ProjectilesCount = 50;
                    AddItems(inventory, ammoMag3, false);


                    AddItems(inventory, CreateGunContent("AutomaticRifleItem"), false);
                    AddItems(inventory, CreateGunContent("WelderItem"), false);
                    AddItems(inventory, CreateGunContent("AngleGrinderItem"), false);
                    AddItems(inventory, CreateGunContent("HandDrillItem"), false);
                }

                // Add all components
                foreach (var definition in MyDefinitionManager.Static.GetAllDefinitions())
                {
                    if (definition.Id.TypeId != typeof(MyObjectBuilder_Component) &&
                        definition.Id.TypeId != typeof(MyObjectBuilder_Ingot))
                    {
                        continue;
                    }

                    if (componentsOnly && definition.Id.TypeId != typeof(MyObjectBuilder_Component))
                    {
                        continue;
                    }

                    if (componentsOnly && ((MyComponentDefinition)definition).Volume > 0.05f)
                    {
                        continue;
                    }

                    var component = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(definition.Id.TypeId);
                    component.SubtypeName = definition.Id.SubtypeName;
                    if (!AddItems(inventory, component, overrideCheck, 1) && spawnNonfitting)
                    {
                        Matrix headMatrix = MySession.ControlledEntity.GetHeadMatrix(true);
                        MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(1, component), headMatrix.Translation + headMatrix.Forward * 0.2f, headMatrix.Forward, headMatrix.Up, MySession.ControlledEntity.Entity.Physics);
                    }
                }

                if (!componentsOnly)
                {
                    string[] ores;
                    MyDefinitionManager.Static.GetOreTypeNames(out ores);
                    foreach (var ore in ores)
                    {
                        var oreBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>(ore);
                        if (!AddItems(inventory, oreBuilder, overrideCheck, 1) && spawnNonfitting)
                        {
                            Matrix headMatrix = MySession.ControlledEntity.GetHeadMatrix(true);
                            MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(1, oreBuilder), headMatrix.Translation + headMatrix.Forward * 0.2f, headMatrix.Forward, headMatrix.Up, MySession.ControlledEntity.Entity.Physics);
                        }
                    }
                }
            }
        }
        public override bool HandleInput()
        {
            bool handled = false;

            if (m_gridDebugInfo)
            {
                LineD      line = new LineD(MySector.MainCamera.Position, MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 1000);
                MyCubeGrid grid;
                Vector3I   cubePos;
                double     distance;
                if (MyCubeGrid.GetLineIntersection(ref line, out grid, out cubePos, out distance))
                {
                    var gridMatrix = grid.WorldMatrix;
                    var boxMatrix  = Matrix.CreateTranslation(cubePos * grid.GridSize) * gridMatrix;
                    var block      = grid.GetCubeBlock(cubePos);

                    MyRenderProxy.DebugDrawText2D(new Vector2(), cubePos.ToString(), Color.White, 0.7f);
                    MyRenderProxy.DebugDrawOBB(Matrix.CreateScale(new Vector3(grid.GridSize) + new Vector3(0.15f)) * boxMatrix, Color.Red.ToVector3(), 0.2f, true, true);

                    //int[, ,] bones = grid.Skeleton.AddCubeBones(cubePos);

                    //Vector3 closestBone = Vector3.Zero;
                    //Vector3I closestPoint = Vector3I.Zero;
                    //float closestPointDist = float.MaxValue;
                    //int closestBoneIndex = 0;

                    //for (int x = -1; x <= 1; x += 1)
                    //{
                    //    for (int y = -1; y <= 1; y += 1)
                    //    {
                    //        for (int z = -1; z <= 1; z += 1)
                    //        {
                    //            int boneIndex = bones[x + 1, y + 1, z + 1];
                    //            Vector3 bone = grid.Skeleton[boneIndex];

                    //            var pos = boxMatrix.Translation + new Vector3(grid.GridSize / 2) * new Vector3(x, y, z);
                    //            //MyRenderProxy.DebugDrawSphere(pos, 0.2f, Color.Blue.ToVector3(), 1.0f, false);
                    //            MyRenderProxy.DebugDrawText3D(pos, String.Format("{0:G2}, {1:G2}, {2:G2}", bone.X, bone.Y, bone.Z), Color.White, 0.5f, false);

                    //            var dist = MyUtils.GetPointLineDistance(ref line, ref pos);
                    //            if (dist < closestPointDist)
                    //            {
                    //                closestPointDist = dist;
                    //                closestPoint = new Vector3I(x, y, z);
                    //                closestBoneIndex = boneIndex;
                    //                closestBone = bone;

                    //            }
                    //        }
                    //    }
                    //}

                    //MyRenderProxy.DebugDrawText3D(boxMatrix.Translation + new Vector3(grid.GridSize / 2) * closestPoint * 1.0f, String.Format("{0:G2}, {1:G2}, {2:G2}", closestBone.X, closestBone.Y, closestBone.Z), Color.Red, 0.5f, false);
                    //var bonePos = grid.Skeleton[bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1]];
                    //MyRenderProxy.DebugDrawSphere(boxMatrix.Translation + new Vector3(grid.GridSize / 2) * closestPoint * 1.0f + bonePos, 0.5f, Color.Red.ToVector3(), 0.4f, true, true);

                    //if (input.IsNewKeyPressed(Keys.P) && block != null)
                    //{
                    //    if (input.IsAnyShiftKeyPressed())
                    //    {
                    //        grid.ResetBlockSkeleton(block);
                    //    }
                    //    else
                    //    {
                    //        grid.Skeleton[bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1]] = Vector3.Zero;
                    //        grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One);
                    //        //grid.SetBlockDirty(block);
                    //    }
                    //    handled = true;
                    //}

                    //// Move bones to center by 0.1f
                    //if (input.IsNewKeyPressed(Keys.OemOpenBrackets))
                    //{
                    //    int index = bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1];
                    //    grid.Skeleton[index] -= Vector3.Sign(grid.Skeleton[index]) * 0.1f;
                    //    grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One);
                    //    //grid.SetBlockDirty(block);
                    //    handled = true;
                    //}

                    //// Reduce max offset by 0.1f
                    //if (input.IsNewKeyPressed(Keys.OemCloseBrackets))
                    //{
                    //    int index = bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1];
                    //    var old = Vector3.Abs(grid.Skeleton[index]);
                    //    var max = new Vector3(Math.Max(Math.Max(old.X, old.Y), old.Z));
                    //    if (max.X > 0.1f)
                    //    {
                    //        grid.Skeleton[index] = Vector3.Clamp(grid.Skeleton[index], -max + 0.1f, max - 0.1f);
                    //    }
                    //    else
                    //    {
                    //        grid.Skeleton[index] = Vector3.Zero;
                    //    }
                    //    grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One);
                    //    //grid.SetBlockDirty(block);
                    //    handled = true;
                    //}
                }
            }

            if (MyInput.Static.IsAnyAltKeyPressed())
            {
                return(handled);
            }

            bool shift = MyInput.Static.IsAnyShiftKeyPressed();
            bool ctrl  = MyInput.Static.IsAnyCtrlKeyPressed();

            //if (input.IsNewKeyPressed(Keys.I))
            //{
            //    foreach (var grid in MyEntities.GetEntities().OfType<MyCubeGrid>())
            //    {
            //        foreach (var block in grid.GetBlocks().ToArray())
            //        {
            //            grid.DetectMerge(block.Min, block.Max);
            //        }
            //    }
            //    handled = true;
            //}

            // Disabled since it is common to have normal control bound to O key.
            // If you ever need this again, bind it to something more complicated, like key combination.
            //if (input.IsNewKeyPressed(Keys.O))
            //{
            //    m_gridDebugInfo = !m_gridDebugInfo;
            //    handled = true;
            //}

            //for (int i = 0; i <= 9; i++)
            //{
            //    if (MyInput.Static.IsNewKeyPressed((Keys)(((int)Keys.D0) + i)))
            //    {
            //        string name = "Slot" + i.ToString();
            //        if (ctrl)
            //        {
            //            MySession.Static.Name = name;
            //            MySession.Static.WorldID = MySession.Static.GetNewWorldId();
            //            MySession.Static.Save(name);
            //        }
            //        else if (shift)
            //        {
            //            var path = MyLocalCache.GetSessionSavesPath(name, false, false);
            //            if (System.IO.Directory.Exists(path))
            //            {
            //                MySession.Static.Unload();
            //                MySession.Static.Load(path);
            //            }
            //        }
            //        handled = true;
            //    }
            //}

            //if (MyInput.Static.IsNewKeyPressed(Keys.End))
            //{
            //    MyMeteorShower.MeteorWave(null);
            //}

            // Disabled for god sake!
            //if (MyInput.Static.IsNewKeyPressed(Keys.PageUp) && MyInput.Static.IsAnyCtrlKeyPressed())
            //{
            //    MyReloadTestComponent.Enabled = true;
            //}
            //if (MyInput.Static.IsNewKeyPressed(Keys.PageDown) && MyInput.Static.IsAnyCtrlKeyPressed())
            //{
            //    MyReloadTestComponent.Enabled = false;
            //}

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad6))
            {
                var view = MySession.Static.CameraController.GetViewMatrix();
                var inv  = Matrix.Invert(view);

                //MyPhysicalInventoryItem item = new MyPhysicalInventoryItem(100,
                var oreBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>("Stone");
                var item       = new MyPhysicalInventoryItem(1, oreBuilder);
                var obj        = MyFloatingObjects.Spawn(item, inv.Translation + inv.Forward * 1.0f, inv.Forward, inv.Up);
                obj.Physics.LinearVelocity = inv.Forward * 50;
            }

            if (false && MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9))
            {
                List <HkShape>       trShapes = new List <HkShape>();
                List <HkConvexShape> shapes   = new List <HkConvexShape>();
                List <Matrix>        matrices = new List <Matrix>();

                var         grid = new HkGridShape(2.5f, HkReferencePolicy.None);
                const short size = 50;
                for (short x = 0; x < size; x++)
                {
                    for (short y = 0; y < size; y++)
                    {
                        for (short z = 0; z < size; z++)
                        {
                            var box = new HkBoxShape(Vector3.One);
                            grid.AddShapes(new System.Collections.Generic.List <HkShape>()
                            {
                                box
                            }, new Vector3S(x, y, z), new Vector3S(x, y, z));
                            trShapes.Add(new HkConvexTranslateShape(box, new Vector3(x, y, z), HkReferencePolicy.None));
                            shapes.Add(box);
                            matrices.Add(Matrix.CreateTranslation(new Vector3(x, y, z)));
                        }
                    }
                }

                var emptyGeom = new HkGeometry(new List <Vector3>(), new List <int>());

                var list         = new HkListShape(trShapes.ToArray(), trShapes.Count, HkReferencePolicy.None);
                var compressedBv = new HkBvCompressedMeshShape(emptyGeom, shapes, matrices, HkWeldingType.None);
                var mopp         = new HkMoppBvTreeShape(list, HkReferencePolicy.None);

                HkShapeBuffer buf = new HkShapeBuffer();

                //HkShapeContainerIterator i = compressedBv.GetIterator(buf);
                //int count = 0; // will be 125000
                //while (i.IsValid)
                //{
                //    count++;
                //    i.Next();
                //}

                buf.Dispose();
                var info = new HkRigidBodyCinfo();
                info.Mass = 10;
                info.CalculateBoxInertiaTensor(Vector3.One, 10);
                info.MotionType  = HkMotionType.Dynamic;
                info.QualityType = HkCollidableQualityType.Moving;
                info.Shape       = compressedBv;
                var body = new HkRigidBody(info);

                //MyPhysics.HavokWorld.AddRigidBody(body);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad7))
            {
                foreach (var g in MyEntities.GetEntities().OfType <MyCubeGrid>())
                {
                    foreach (var s in g.CubeBlocks.Select(s => s.FatBlock).Where(s => s != null).OfType <MyMotorStator>())
                    {
                        if (s.Rotor != null)
                        {
                            var q = Quaternion.CreateFromAxisAngle(s.Rotor.WorldMatrix.Up, MathHelper.ToRadians(45));
                            s.Rotor.CubeGrid.WorldMatrix = MatrixD.CreateFromQuaternion(q) * s.Rotor.CubeGrid.WorldMatrix;
                        }
                    }
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad8))
            {
                var view = MySession.Static.CameraController.GetViewMatrix();
                var inv  = Matrix.Invert(view);

                var oreBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>("Stone");
                var obj        = new MyObjectBuilder_FloatingObject()
                {
                    Item = new MyObjectBuilder_InventoryItem()
                    {
                        PhysicalContent = oreBuilder, Amount = 1000
                    }
                };
                obj.PositionAndOrientation = new MyPositionAndOrientation(inv.Translation + 2.0f * inv.Forward, inv.Forward, inv.Up);
                obj.PersistentFlags        = MyPersistentEntityFlags2.InScene;
                var e = MyEntities.CreateFromObjectBuilderAndAdd(obj);
                e.Physics.LinearVelocity = Vector3.Normalize(inv.Forward) * 50.0f;
            }


            if (MyInput.Static.IsNewKeyPressed(MyKeys.Divide))
            {
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.Multiply))
            {
                MyDebugDrawSettings.ENABLE_DEBUG_DRAW = !MyDebugDrawSettings.ENABLE_DEBUG_DRAW;
                MyDebugDrawSettings.DEBUG_DRAW_STRUCTURAL_INTEGRITY = true;

                var grids = MyEntities.GetEntities().OfType <MyCubeGrid>();
                foreach (var g in grids)
                {
                    if (!g.IsStatic)// || g.GetBlocks().Count < 800) //to compute only castle
                    {
                        continue;
                    }

                    g.CreateStructuralIntegrity();
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad1))
            {
                var e = MyEntities.GetEntities().OfType <MyCubeGrid>().FirstOrDefault();
                if (e != null)
                {
                    e.Physics.RigidBody.MaxLinearVelocity = 1000;
                    if (e.Physics.RigidBody2 != null)
                    {
                        e.Physics.RigidBody2.MaxLinearVelocity = 1000;
                    }

                    e.Physics.LinearVelocity = new Vector3(1000, 0, 0);
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.Decimal))
            {
                MyPrefabManager.Static.SpawnPrefab("respawnship", MySector.MainCamera.Position, MySector.MainCamera.ForwardVector, MySector.MainCamera.UpVector);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.Multiply) && MyInput.Static.IsAnyShiftKeyPressed())
            {
                GC.Collect(2);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad5))
            {
                Thread.Sleep(250);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9))
            {
                var obj = MySession.Static.ControlledEntity != null ? MySession.Static.ControlledEntity.Entity : null;
                if (obj != null)
                {
                    const float dist = 5.0f;
                    obj.PositionComp.SetPosition(obj.PositionComp.GetPosition() + obj.WorldMatrix.Forward * dist);
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad4))
            {
                MyEntity invObject = MySession.Static.ControlledEntity as MyEntity;
                if (invObject != null && invObject.HasInventory)
                {
                    MyFixedPoint amount = 20000;

                    var         oreBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>("Stone");
                    MyInventory inventory  = invObject.GetInventory(0) as MyInventory;
                    System.Diagnostics.Debug.Assert(inventory != null, "Null or unexpected type returned!");
                    inventory.AddItems(amount, oreBuilder);
                }

                handled = true;
            }

            //if (MyInput.Static.IsNewKeyPressed(Keys.NumPad8))
            //{
            //    var pos = MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 2;
            //    var grid = (MyObjectBuilder_CubeGrid)MyObjectBuilderSerializer.CreateNewObject(MyObjectBuilderTypeEnum.CubeGrid);
            //    grid.PositionAndOrientation = new MyPositionAndOrientation(pos, Vector3.Forward, Vector3.Up);
            //    grid.CubeBlocks = new List<MyObjectBuilder_CubeBlock>();
            //    grid.GridSizeEnum = MyCubeSize.Large;

            //    var block = new MyObjectBuilder_CubeBlock();
            //    block.BlockOrientation = MyBlockOrientation.Identity;
            //    block.Min = Vector3I.Zero;
            //    //var blockDefinition = Sandbox.Game.Managers.MyDefinitionManager.Static.GetCubeBlockDefinition(new CommonLib.ObjectBuilders.Definitions.MyDefinitionId(typeof(MyObjectBuilder_CubeBlock), "LargeBlockArmorBlock"));
            //    block.SubtypeName = "LargeBlockArmorBlock";
            //    grid.CubeBlocks.Add(block);
            //    grid.LinearVelocity = MySector.MainCamera.ForwardVector * 20;
            //    grid.PersistentFlags = MyPersistentEntityFlags2.Enabled | MyPersistentEntityFlags2.InScene;

            //    var x = MyEntities.CreateFromObjectBuilderAndAdd(grid);
            //}

            //if (MyInput.Static.IsNewKeyPressed(Keys.NumPad9))
            //{
            //    var pos = MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 2;
            //    var grid =  (MyObjectBuilder_CubeGrid)MyObjectBuilderSerializer.CreateNewObject(MyObjectBuilderTypeEnum.CubeGrid);
            //    grid.PositionAndOrientation = new MyPositionAndOrientation(pos, Vector3.Forward, Vector3.Up);
            //    grid.CubeBlocks = new List<MyObjectBuilder_CubeBlock>();
            //    grid.GridSizeEnum = MyCubeSize.Large;

            //    var block = new MyObjectBuilder_CubeBlock();
            //    block.BlockOrientation = MyBlockOrientation.Identity;
            //    block.Min = Vector3I.Zero;
            //    //var blockDefinition = Sandbox.Game.Managers.MyDefinitionManager.Static.GetCubeBlockDefinition(new CommonLib.ObjectBuilders.Definitions.MyDefinitionId(typeof(MyObjectBuilder_CubeBlock), "LargeBlockArmorBlock"));
            //    block.SubtypeName = "LargeBlockGyro";
            //    grid.CubeBlocks.Add(block);
            //    grid.LinearVelocity = MySector.MainCamera.ForwardVector * 20;
            //    grid.PersistentFlags = MyPersistentEntityFlags2.Enabled | MyPersistentEntityFlags2.InScene;

            //    var x = MyEntities.CreateFromObjectBuilderAndAdd(grid);
            //}

            if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.Delete))
            {
                int count = MyEntities.GetEntities().OfType <MyFloatingObject>().Count();
                foreach (var obj in MyEntities.GetEntities().OfType <MyFloatingObject>())
                {
                    if (obj == MySession.Static.ControlledEntity)
                    {
                        MySession.Static.SetCameraController(MyCameraControllerEnum.Spectator);
                    }
                    obj.Close();
                }
                handled = true;
            }

            if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.Decimal))
            {
                foreach (var obj in MyEntities.GetEntities())
                {
                    if (obj != MySession.Static.ControlledEntity && (MySession.Static.ControlledEntity == null || obj != MySession.Static.ControlledEntity.Entity.Parent) && obj != MyCubeBuilder.Static.FindClosestGrid())
                    {
                        obj.Close();
                    }
                }
                handled = true;
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9) || MyInput.Static.IsNewKeyPressed(MyKeys.NumPad5))
            {
                //MyCubeGrid.UserCollisions = input.IsNewKeyPressed(Keys.NumPad9);

                var body = MySession.Static.ControlledEntity.Entity.GetTopMostParent().Physics;
                if (body.RigidBody != null)
                {
                    //body.AddForce(Engine.Physics.MyPhysicsForceType.ADD_BODY_FORCE_AND_BODY_TORQUE, new Vector3(0, 0, 10 * body.Mass), null, null);
                    body.RigidBody.ApplyLinearImpulse(body.Entity.WorldMatrix.Forward * body.Mass * 2);
                }
                handled = true;
            }

            //if (input.IsNewKeyPressed(Keys.J) && input.IsAnyCtrlKeyPressed())
            //{
            //    MyGlobalInputComponent.CopyCurrentGridToClipboard();

            //    MyEntity addedEntity = MyGlobalInputComponent.PasteEntityFromClipboard();

            //    if (addedEntity != null)
            //    {
            //        Vector3 pos = addedEntity.GetPosition();
            //        pos.Z += addedEntity.WorldVolume.Radius * 1.5f;
            //        addedEntity.SetPosition(pos);
            //    }
            //    handled = true;
            //}

            if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.OemComma))
            {
                foreach (var e in MyEntities.GetEntities().OfType <MyFloatingObject>().ToArray())
                {
                    e.Close();
                }
            }

            return(handled);
        }
Exemple #26
0
 public MySyncFloatingObjects(MyFloatingObjects floatingObjects)
 {
     m_floatingObjects = floatingObjects;
 }
Exemple #27
0
        public static MyEntity SpawnInWorldOrLootBag(this MyPhysicalInventoryItem thisItem, MyEntity owner, ref MyEntity lootBagEntity)
        {
            Debug.Assert(Sandbox.Game.Multiplayer.Sync.IsServer);

            MyDefinitionBase itemDefinition = thisItem.GetItemDefinition();

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

            MyEntity spawnedItem = null;

            Vector3 upDir = -MyGravityProviderSystem.CalculateNaturalGravityInPoint(owner.PositionComp.WorldMatrix.Translation);

            if (upDir == Vector3.Zero)
            {
                upDir = Vector3.Up;
            }
            else
            {
                upDir.Normalize();
            }

            if (itemDefinition is MyCubeBlockDefinition)
            {
                MyCubeBlockDefinition blockDef = itemDefinition as MyCubeBlockDefinition;

                if (MyDefinitionManager.Static.GetLootBagDefinition() != null)
                {
                    // New code which tries to spawn item with "MyEntities.FindFreePlace" and if there is no such position then loot bag is spawn and item is moved into it.
                    MyModel     blockModel = MyModels.GetModelOnlyData(blockDef.Model);
                    BoundingBox box        = blockModel.BoundingBox;
                    box.Inflate(0.15f); // Inflate with value that is higher than half size of small grid so it will eliminate problems with block center offsets.
                    float radius            = box.HalfExtents.Max();
                    var   baseSpawnPosition = owner.PositionComp.WorldMatrix.Translation;
                    if (owner is MyCharacter)
                    {
                        baseSpawnPosition += owner.PositionComp.WorldMatrix.Up + owner.PositionComp.WorldMatrix.Forward;
                    }
                    else
                    {
                        baseSpawnPosition += upDir;
                    }

                    for (int gridIndex = 0; gridIndex < thisItem.Amount; ++gridIndex)
                    {
                        Vector3D?spawnPos = null;
                        if (lootBagEntity == null && (spawnPos = MyEntities.FindFreePlace(baseSpawnPosition, radius, maxTestCount: 50, testsPerDistance: 5, stepSize: 0.25f)) != null)
                        {
                            MatrixD transform = owner.PositionComp.WorldMatrix;
                            transform.Translation = spawnPos.Value;

                            var blockBuilder = MyObjectBuilderSerializer.CreateNewObject(blockDef.Id) as MyObjectBuilder_CubeBlock;
                            blockBuilder.Min      = blockDef.Size / 2 - blockDef.Size + Vector3I.One;
                            blockBuilder.EntityId = MyEntityIdentifier.AllocateId();

                            var newGrid = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_CubeGrid>();
                            newGrid.PositionAndOrientation = new MyPositionAndOrientation(transform);
                            newGrid.GridSizeEnum           = blockDef.CubeSize;
                            newGrid.PersistentFlags       |= MyPersistentEntityFlags2.InScene;
                            newGrid.EntityId = MyEntityIdentifier.AllocateId();
                            newGrid.CubeBlocks.Add(blockBuilder);

                            var entity = MyEntities.CreateFromObjectBuilderAndAdd(newGrid);
                            spawnedItem = spawnedItem ?? entity;
                        }
                        else
                        {
                            AddItemToLootBag(owner, new MyPhysicalInventoryItem(1, thisItem.Content), ref lootBagEntity);
                        }
                    }
                }
                else
                {
                    // Old code used in SE (when no loot bag definition is defined).
                    float    spawnRadius = MyUtils.GetRandomFloat(Math.Max(0.25f, ITEM_SPAWN_RADIUS), ITEM_SPAWN_RADIUS);
                    Vector3D randomizer  = MyUtils.GetRandomVector3CircleNormalized() * spawnRadius + Vector3D.Up * 0.25f;

                    int         yOffset = 0;
                    MyModel     m       = MyModels.GetModelOnlyData(blockDef.Model);
                    float       sizeY   = m.BoundingBoxSize.Y + 0.05f;
                    BoundingBox box     = m.BoundingBox;

                    for (int gridIndex = 0; gridIndex < thisItem.Amount; ++gridIndex)
                    {
                        var newGrid = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_CubeGrid>();

                        MatrixD transform = owner.PositionComp.WorldMatrix * MatrixD.CreateTranslation(randomizer + new Vector3D(0, yOffset * sizeY, 0));
                        if (!GetNonPenetratingTransformPosition(ref box, ref transform))
                        {
                            randomizer = MyUtils.GetRandomVector3CircleNormalized() * 0.25f + Vector3D.Up * 0.25f;
                            transform  = owner.PositionComp.WorldMatrix * MatrixD.CreateTranslation(randomizer + new Vector3D(0, yOffset * sizeY, 0));
                        }

                        newGrid.PositionAndOrientation = new MyPositionAndOrientation(transform);
                        newGrid.GridSizeEnum           = blockDef.CubeSize;
                        newGrid.PersistentFlags       |= MyPersistentEntityFlags2.InScene;
                        newGrid.EntityId = MyEntityIdentifier.AllocateId();

                        var newBlock = MyObjectBuilderSerializer.CreateNewObject(blockDef.Id) as MyObjectBuilder_CubeBlock;
                        newBlock.EntityId = MyEntityIdentifier.AllocateId();
                        newGrid.CubeBlocks.Add(newBlock);

                        var entity = MyEntities.CreateFromObjectBuilderAndAdd(newGrid);
                        spawnedItem = spawnedItem ?? entity;

                        if ((gridIndex + 1) % 10 == 0)
                        {
                            spawnRadius = MyUtils.GetRandomFloat(Math.Max(0.25f, ITEM_SPAWN_RADIUS), ITEM_SPAWN_RADIUS);
                            randomizer  = MyUtils.GetRandomVector3CircleNormalized() * spawnRadius + Vector3D.Up * 0.25f;
                            yOffset     = 0;
                        }
                        else
                        {
                            yOffset++;
                        }
                    }
                }
            }
            else if (itemDefinition is MyPhysicalItemDefinition)
            {
                MyPhysicalItemDefinition floatingObjectDefinition = itemDefinition as MyPhysicalItemDefinition;

                MyFixedPoint          amount         = thisItem.Amount;
                bool                  canStack       = thisItem.Content.CanStack(thisItem.Content);
                MyFixedPoint          stackSize      = canStack ? amount : 1;
                MyFixedPoint          maxStackAmount = MyFixedPoint.MaxValue;
                MyComponentDefinition compDef        = null;
                if (MyDefinitionManager.Static.TryGetComponentDefinition(thisItem.Content.GetId(), out compDef))
                {
                    maxStackAmount = compDef.MaxStackAmount;
                    stackSize      = MyFixedPoint.Min(stackSize, maxStackAmount);
                }

                if (MyDefinitionManager.Static.GetLootBagDefinition() != null)
                {
                    // New code which tries to spawn item with "MyEntities.FindFreePlace" and if there is no such position then loot bag is spawn and item is moved into it.
                    MyModel     model             = MyModels.GetModelOnlyData(floatingObjectDefinition.Model);
                    BoundingBox box               = model.BoundingBox;
                    float       radius            = box.HalfExtents.Max();
                    var         baseSpawnPosition = owner.PositionComp.WorldMatrix.Translation;
                    if (owner is MyCharacter)
                    {
                        baseSpawnPosition += owner.PositionComp.WorldMatrix.Up + owner.PositionComp.WorldMatrix.Forward;
                    }
                    else
                    {
                        baseSpawnPosition += upDir;
                    }

                    while (amount > 0)
                    {
                        MyFixedPoint spawnAmount = stackSize;
                        amount -= stackSize;
                        if (amount < 0)
                        {
                            spawnAmount = amount + stackSize;
                        }

                        Vector3D?spawnPos = null;
                        if (lootBagEntity == null && (spawnPos = MyEntities.FindFreePlace(baseSpawnPosition, radius, maxTestCount: 50, testsPerDistance: 5, stepSize: 0.25f)) != null)
                        {
                            MatrixD worldMat = owner.PositionComp.WorldMatrix;
                            worldMat.Translation = spawnPos.Value;
                            var entity = MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(spawnAmount, thisItem.Content), worldMat);
                            spawnedItem = spawnedItem ?? entity;
                        }
                        else
                        {
                            AddItemToLootBag(owner, new MyPhysicalInventoryItem(spawnAmount, thisItem.Content), ref lootBagEntity);
                        }
                    }
                }
                else
                {
                    // Old code used in SE (when no loot bag definition is defined).
                    while (amount > 0)
                    {
                        MyFixedPoint spawnAmount = stackSize;
                        amount -= stackSize;
                        if (amount < 0)
                        {
                            spawnAmount = amount + stackSize;
                        }

                        float    spawnRadius = MyUtils.GetRandomFloat(Math.Max(0.25f, ITEM_SPAWN_RADIUS), ITEM_SPAWN_RADIUS);
                        Vector3D randomizer  = MyUtils.GetRandomVector3CircleNormalized() * spawnRadius + Vector3D.Up * 0.25f;
                        var      worldMat    = owner.PositionComp.WorldMatrix * MatrixD.CreateTranslation(randomizer);

                        var entity = MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(spawnAmount, thisItem.Content), worldMat);
                        spawnedItem = spawnedItem ?? entity;
                    }
                }
            }

            return(spawnedItem);
        }
Exemple #28
0
        private void TransferRemainingComponents()
        {
            MyObjectBuilder_CubeBlock block;

            try
            {
                if (m_targetBlock.FatBlock == null)
                {
                    block = m_targetBlock.GetObjectBuilder();
                }
                else
                {
                    block = m_targetBlock.FatBlock.GetObjectBuilderCubeBlock();
                }
            }
            catch (Exception ex)
            {
                Logging.Instance.WriteLine(string.Format("ERROR getting cubeblock object builder (1): {0} {1} - {2}", m_targetBlock.IsDestroyed, m_targetBlock.FatBlock != null ? m_targetBlock.FatBlock.GetType().Name : m_targetBlock.GetType().Name, ex.ToString()));
                return;
            }

            MyCubeBlockDefinition blockDefinition;

            if (MyDefinitionManager.Static.TryGetCubeBlockDefinition(block.GetId(), out blockDefinition))
            {
                Dictionary <string, MyTuple <int, MyPhysicalItemDefinition> > components = new Dictionary <string, MyTuple <int, MyPhysicalItemDefinition> >();
                foreach (var item in blockDefinition.Components)
                {
                    var inventoryItem = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(item.DeconstructItem.Id);
                    if (!components.ContainsKey(item.DeconstructItem.Id.SubtypeName))
                    {
                        components.Add(item.DeconstructItem.Id.SubtypeName, new MyTuple <int, MyPhysicalItemDefinition>(item.Count, item.DeconstructItem));
                    }
                    else
                    {
                        components[item.DeconstructItem.Id.SubtypeName] = new MyTuple <int, MyPhysicalItemDefinition>(components[item.DeconstructItem.Id.SubtypeName].Item1 + item.Count, item.DeconstructItem);
                    }
                }

                foreach (var item in m_missingComponents)
                {
                    if (components.ContainsKey(item.Key))
                    {
                        components[item.Key] = new MyTuple <int, MyPhysicalItemDefinition>(components[item.Key].Item1 - item.Value, components[item.Key].Item2);
                    }

                    if (components[item.Key].Item1 <= 0)
                    {
                        components.Remove(item.Key);
                    }
                }

                foreach (var item in components)
                {
                    TransferFromItem((MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(item.Value.Item2.Id), item.Value.Item1);
                }
            }

            foreach (var item in m_inventory)
            {
                MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(item.Value.Item1, item.Value.Item2), Vector3D.Transform(m_targetBlock.Position * m_targetBlock.CubeGrid.GridSize, m_targetBlock.CubeGrid.WorldMatrix), m_targetBlock.CubeGrid.WorldMatrix.Forward, m_targetBlock.CubeGrid.WorldMatrix.Up);
            }
        }
Exemple #29
0
        public static MyEntity Spawn(this MyPhysicalInventoryItem thisItem, MyFixedPoint amount, MatrixD worldMatrix, MyEntity owner = null)
        {
            if (amount < 0)
            {
                return(null);
            }
            if (thisItem.Content == null)
            {
                Debug.Fail("Can not spawn item with null content!");
                return(null);
            }

            if (thisItem.Content is MyObjectBuilder_BlockItem)
            {
                Debug.Assert(MyFixedPoint.IsIntegral(amount), "Spawning fractional number of grids!");
                bool isBlock = typeof(MyObjectBuilder_CubeBlock).IsAssignableFrom(thisItem.Content.GetObjectId().TypeId);
                Debug.Assert(isBlock, "Block item does not contain block!?!?@&*#%!");
                if (!isBlock)
                {
                    return(null);
                }

                var blockItem = thisItem.Content as MyObjectBuilder_BlockItem;
                MyCubeBlockDefinition blockDefinition;
                MyDefinitionManager.Static.TryGetCubeBlockDefinition(blockItem.BlockDefId, out blockDefinition);
                Debug.Assert(blockDefinition != null, "Block definition not found");
                if (blockDefinition == null)
                {
                    return(null);
                }

                var builder = MyObjectBuilderSerializer.CreateNewObject(typeof(MyObjectBuilder_CubeGrid)) as MyObjectBuilder_CubeGrid;
                builder.GridSizeEnum           = blockDefinition.CubeSize;
                builder.IsStatic               = false;
                builder.PersistentFlags       |= MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.Enabled;
                builder.PositionAndOrientation = new MyPositionAndOrientation(worldMatrix);

                var block = MyObjectBuilderSerializer.CreateNewObject(blockItem.BlockDefId) as MyObjectBuilder_CubeBlock;
                System.Diagnostics.Debug.Assert(block != null, "Block couldn't been created, maybe wrong definition id? DefID: " + blockItem.BlockDefId);

                if (block != null)
                {
                    block.Min = blockDefinition.Size / 2 - blockDefinition.Size + Vector3I.One;
                    builder.CubeBlocks.Add(block);

                    MyCubeGrid firstGrid = null;
                    for (int i = 0; i < amount; ++i)
                    {
                        builder.EntityId = MyEntityIdentifier.AllocateId();
                        block.EntityId   = MyEntityIdentifier.AllocateId();
                        MyCubeGrid newGrid = MyEntities.CreateFromObjectBuilder(builder) as MyCubeGrid;
                        firstGrid = firstGrid ?? newGrid;
                        MyEntities.Add(newGrid);
                    }
                    return(firstGrid);
                }
                return(null);
            }
            else
            {
                MyPhysicalItemDefinition itemDefinition = null;
                if (MyDefinitionManager.Static.TryGetPhysicalItemDefinition(thisItem.Content.GetObjectId(), out itemDefinition))
                {
                    return(MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(amount, thisItem.Content), worldMatrix, owner != null ? owner.Physics : null));
                }
                return(null);
            }
        }