Ejemplo n.º 1
0
        static bool TryFindCryoChamberCharacter(MyPlayer player)
        {
            if (player == null)
            {
                return(false);
            }

            var entities = MyEntities.GetEntities();

            foreach (var entity in entities)
            {
                var cubeGrid = entity as MyCubeGrid;
                if (cubeGrid != null)
                {
                    var blocks = cubeGrid.GetFatBlocks <Sandbox.Game.Entities.Blocks.MyCryoChamber>();
                    foreach (var cryoChamber in blocks)
                    {
                        if (cryoChamber.TryToControlPilot(player))
                        {
                            MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(cryoChamber.CubeGrid), new EndpointId(player.Id.SteamId));
                            MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(cryoChamber.Pilot), new EndpointId(player.Id.SteamId));
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
Ejemplo n.º 2
0
        static void CycleRequest_Implementation(MyEntityCyclingOrder order, bool reset, bool findLarger, float metricValue, long currentEntityId, CyclingOptions options)
        {
            if (reset)
            {
                metricValue     = float.MinValue;
                currentEntityId = 0;
                findLarger      = false;
            }

            MyEntityCycling.FindNext(order, ref metricValue, ref currentEntityId, findLarger, options);

            var      e   = MyEntities.GetEntityByIdOrDefault(currentEntityId);
            Vector3D pos = e != null ? e.WorldMatrix.Translation : Vector3D.Zero;

            if (MyEventContext.Current.IsLocallyInvoked)
            {
                Cycle_Implementation(metricValue, currentEntityId, pos);
            }
            else
            {
                var proxy = e as IMyEventProxy;
                if (proxy != null)
                {
                    if (proxy is MyCubeGrid && (proxy as MyCubeGrid).Physics == null)
                    {
                        //don't send grids without physics
                    }
                    else
                    {
                        MyMultiplayer.ReplicateImmediatelly(proxy, MyEventContext.Current.Sender);
                    }
                }
                MyMultiplayer.RaiseStaticEvent(x => Cycle_Implementation, metricValue, currentEntityId, pos, MyEventContext.Current.Sender);
            }
        }
        private void CreateTopPart(out MyAttachableTopBlockBase topBlock, long builtBy, MyCubeBlockDefinitionGroup topGroup, bool smallToLarge)
        {
            Debug.Assert(Sync.IsServer, "Server only method.");
            if (topGroup == null)
            {
                topBlock = null;
                return;
            }

            var gridSize = CubeGrid.GridSizeEnum;

            if (smallToLarge && gridSize == MyCubeSize.Large)   //If we have pressed the Attach Small Rotor Head button on large grid take the small grid definition from pair
            {
                gridSize = MyCubeSize.Small;
            }
            var matrix = GetTopGridMatrix();

            var definition = topGroup[gridSize];

            Debug.Assert(definition != null);

            var block = MyCubeGrid.CreateBlockObjectBuilder(definition, Vector3I.Zero, MyBlockOrientation.Identity, MyEntityIdentifier.AllocateId(), OwnerId, fullyBuilt: MySession.Static.CreativeMode);

            matrix.Translation = Vector3D.Transform(-definition.Center * CubeGrid.GridSize, matrix);

            var gridBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_CubeGrid>();

            gridBuilder.GridSizeEnum           = gridSize;
            gridBuilder.IsStatic               = false;
            gridBuilder.PositionAndOrientation = new MyPositionAndOrientation(matrix);
            gridBuilder.CubeBlocks.Add(block);

            var grid = MyEntityFactory.CreateEntity <MyCubeGrid>(gridBuilder);

            grid.Init(gridBuilder);

            topBlock = (MyAttachableTopBlockBase)grid.GetCubeBlock(Vector3I.Zero).FatBlock;

            if (!CanPlaceTop(topBlock, builtBy))
            {
                topBlock = null;
                grid.Close();
                return;
            }
            grid.PositionComp.SetPosition(grid.WorldMatrix.Translation - (Vector3D.Transform(topBlock.DummyPosLoc, grid.WorldMatrix) - grid.WorldMatrix.Translation));

            MyEntities.Add(grid);
            if (MyFakes.ENABLE_SENT_GROUP_AT_ONCE)
            {
                MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(grid), MyExternalReplicable.FindByObject(CubeGrid));
            }

            MatrixD masterToSlave = topBlock.CubeGrid.WorldMatrix * MatrixD.Invert(WorldMatrix);

            m_connectionState.Value = new State()
            {
                TopBlockId = topBlock.EntityId, MasterToSlave = masterToSlave
            };
        }
Ejemplo n.º 4
0
        protected void CreateRotorGrid(out MyCubeGrid rotorGrid, out MyAttachableTopBlockBase rotorBlock, long builtBy, MyCubeBlockDefinitionGroup rotorGroup)
        {
            Debug.Assert(Sync.IsServer, "Rotor grid can be created only on server");
            if (rotorGroup == null)
            {
                rotorGrid  = null;
                rotorBlock = null;
                return;
            }

            var gridSize = CubeGrid.GridSizeEnum;

            float size       = MyDefinitionManager.Static.GetCubeSize(gridSize);
            var   matrix     = MatrixD.CreateWorld(Vector3D.Transform(DummyPosition, CubeGrid.WorldMatrix), WorldMatrix.Forward, WorldMatrix.Up);
            var   definition = rotorGroup[gridSize];

            Debug.Assert(definition != null);

            var block = MyCubeGrid.CreateBlockObjectBuilder(definition, Vector3I.Zero, MyBlockOrientation.Identity, MyEntityIdentifier.AllocateId(), OwnerId, fullyBuilt: MySession.Static.CreativeMode);

            var gridBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_CubeGrid>();

            gridBuilder.GridSizeEnum           = gridSize;
            gridBuilder.IsStatic               = false;
            gridBuilder.PositionAndOrientation = new MyPositionAndOrientation(matrix);
            gridBuilder.CubeBlocks.Add(block);

            var grid = MyEntityFactory.CreateEntity <MyCubeGrid>(gridBuilder);

            grid.Init(gridBuilder);

            rotorGrid = grid;
            MyMotorRotor rotor = (MyMotorRotor)rotorGrid.GetCubeBlock(Vector3I.Zero).FatBlock;

            rotorBlock = rotor;
            rotorGrid.PositionComp.SetPosition(rotorGrid.WorldMatrix.Translation - (Vector3D.Transform(rotor.DummyPosLoc, rotorGrid.WorldMatrix) - rotorGrid.WorldMatrix.Translation));

            if (!CanPlaceRotor(rotorBlock, builtBy))
            {
                rotorGrid  = null;
                rotorBlock = null;
                grid.Close();
                return;
            }

            MyEntities.Add(grid);

            if (MyFakes.ENABLE_SENT_GROUP_AT_ONCE)
            {
                MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(grid), MyExternalReplicable.FindByObject(CubeGrid));
            }

            MatrixD masterToSlave = rotorBlock.CubeGrid.WorldMatrix * MatrixD.Invert(WorldMatrix);

            m_connectionState.Value = new State()
            {
                TopBlockId = rotorBlock.EntityId, MasterToSlave = masterToSlave
            };
        }
Ejemplo n.º 5
0
        private void CreateTopGrid(out MyCubeGrid topGrid, out MyAttachableTopBlockBase topBlock, long builtBy, MyCubeBlockDefinitionGroup topGroup)
        {
            if (topGroup == null)
            {
                topGrid  = null;
                topBlock = null;
                return;
            }

            var gridSize = CubeGrid.GridSizeEnum;

            float size   = MyDefinitionManager.Static.GetCubeSize(gridSize);
            var   matrix = GetTopGridMatrix();

            var definition = topGroup[gridSize];

            Debug.Assert(definition != null);

            var block = MyCubeGrid.CreateBlockObjectBuilder(definition, Vector3I.Zero, MyBlockOrientation.Identity, MyEntityIdentifier.AllocateId(), OwnerId, fullyBuilt: MySession.Static.CreativeMode);

            var gridBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_CubeGrid>();

            gridBuilder.GridSizeEnum           = gridSize;
            gridBuilder.IsStatic               = false;
            gridBuilder.PositionAndOrientation = new MyPositionAndOrientation(matrix);
            gridBuilder.CubeBlocks.Add(block);

            var grid = MyEntityFactory.CreateEntity <MyCubeGrid>(gridBuilder);

            grid.Init(gridBuilder);

            topGrid  = grid;
            topBlock = (MyAttachableTopBlockBase)topGrid.GetCubeBlock(Vector3I.Zero).FatBlock;

            if (!CanPlaceTop(topBlock, builtBy))
            {
                topGrid  = null;
                topBlock = null;
                grid.Close();
                return;
            }
            //topGrid.SetPosition(topGrid.WorldMatrix.Translation - (topBlock.WorldMatrix.Translation/*Vector3.Transform(topBlock.DummyPosLoc, topGrid.WorldMatrix) - topGrid.WorldMatrix.Translation*/));

            MyEntities.Add(grid);
            if (MyFakes.ENABLE_SENT_GROUP_AT_ONCE)
            {
                MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(grid), MyExternalReplicable.FindByObject(CubeGrid));
            }

            MatrixD masterToSlave = topBlock.CubeGrid.WorldMatrix * MatrixD.Invert(WorldMatrix);

            m_connectionState.Value = new State()
            {
                TopBlockId = topBlock.EntityId, MasterToSlave = masterToSlave
            };
        }
        private void SpawnInRespawn(MyPlayer player, MyRespawnComponent respawn, MyBotDefinition botDefinition)
        {
            if (MySession.Static.Settings.EnableOxygen)
            {
                player.Identity.ChangeToOxygenSafeSuit();
            }

            if (respawn.Entity == null)
            {
                Debug.Assert(false, "Respawn does not have entity!");
                SpawnInSuit(player, null, botDefinition);
                return;
            }
            var parent = respawn.Entity.GetTopMostParent();

            if (parent.Physics == null)
            {
                Debug.Assert(false, "Respawn entity parent does not have physics!");
                SpawnInSuit(player, (MyEntity)parent, botDefinition);
                return;
            }

            MatrixD pos;

            var medRoom = respawn.Entity as MyMedicalRoom;

            if (medRoom != null)
            {
                pos = medRoom.GetSpawnPosition();
            }
            else
            {
                pos = respawn.GetSpawnPosition(respawn.Entity.WorldMatrix);
            }

            Vector3 velocity = parent.Physics.GetVelocityAtPoint(pos.Translation);

            MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(parent), new EndpointId(player.Id.SteamId));

            player.SpawnAt(pos, velocity, (MyEntity)parent, botDefinition, true);

            if (medRoom != null)
            {
                medRoom.TryTakeSpawneeOwnership(player);
                medRoom.TrySetFaction(player);

                if (medRoom.ForceSuitChangeOnRespawn)
                {
                    player.Character.ChangeModelAndColor(medRoom.RespawnSuitName, player.Character.ColorMask);
                }
            }
        }
Ejemplo n.º 7
0
        public override void OnBuildSuccess(long builtBy)
        {
            Debug.Assert(m_constraint == null);

            if (Sync.IsServer)
            {
                MyMultiplayer.ReplicateImmediatelly(this, this.CubeGrid);
                CreateRotorGrid(out m_rotorGrid, out m_rotorBlock, builtBy);
                if (m_rotorBlock != null) // No place for top part
                {
                    MatrixD masterToSlave = m_rotorBlock.CubeGrid.WorldMatrix * MatrixD.Invert(WorldMatrix);
                    m_rotorBlockId.Value = new State()
                    {
                        OtherEntityId = m_rotorBlock.EntityId, MasterToSlave = masterToSlave
                    };
                    Attach(m_rotorBlock);
                }
            }

            NeedsUpdate &= ~MyEntityUpdateEnum.BEFORE_NEXT_FRAME;
            base.OnBuildSuccess(builtBy);
        }
Ejemplo n.º 8
0
        public static bool Move(string userName, Vector3D position)
        {
            //CharacterEntity charEntity = SectorObjectManager.Instance.GetTypedInternalData<CharacterEntity>().FirstOrDefault(x => x.DisplayName.ToLower() == userName.ToLower() && x.Health > 0);
            MyObjectBuilder_Character charEntity = FindCharacter(userName);

            if (charEntity == null)
            {
                Essentials.Log.Info(string.Format("Unable to find CharacterEntity of '{0}'", userName));
                return(false);
            }

            CubeGridEntity gridEntity = new CubeGridEntity(new FileInfo(Essentials.PluginPath + "MovePlayer.sbc"));

            gridEntity.EntityId = BaseEntity.GenerateEntityId();
            foreach (MyObjectBuilder_CubeBlock block in gridEntity.BaseCubeBlocks)
            {
                // set ownership
                MyObjectBuilder_Cockpit cockpit = block as MyObjectBuilder_Cockpit;
                if (cockpit != null)
                {
                    cockpit.Pilot = charEntity;
                }
            }

            gridEntity.PositionAndOrientation = new MyPositionAndOrientation(position, Vector3.Forward, Vector3.Up);

            Wrapper.GameAction(() =>
            {
                MyObjectBuilder_EntityBase baseEntity = gridEntity.Export();
                MyAPIGateway.Entities.RemapObjectBuilder(baseEntity);
                IMyEntity entity = MyAPIGateway.Entities.CreateFromObjectBuilderAndAdd(baseEntity);
                Type someManager = SandboxGameAssemblyWrapper.Instance.GetAssemblyType(SectorObjectManager.EntityBaseNetManagerNamespace, SectorObjectManager.EntityBaseNetManagerClass);
                Wrapper.InvokeStaticMethod(someManager, SectorObjectManager.EntityBaseNetManagerSendEntity, new object[] { entity.GetObjectBuilder() });
                gridEntity = new CubeGridEntity((MyObjectBuilder_CubeGrid)entity.GetObjectBuilder(), entity);

                MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(entity));
            });


            DateTime _loadTime = DateTime.Now;

            while (gridEntity.IsLoading)
            {
                if (DateTime.Now - _loadTime > TimeSpan.FromSeconds(20))
                {
                    break;
                }
            }

            if (gridEntity.IsLoading)
            {
                Essentials.Log.Info("Failed to load cockpit entity: {0}", gridEntity.EntityId);
                return(false);
            }

            foreach (CubeBlockEntity block in gridEntity.CubeBlocks)
            {
                if (block is CockpitEntity)
                {
                    block.IntegrityPercent = 0.1f;
                }
            }

            gridEntity.Dispose();
            MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(gridEntity));
            return(true);
        }
Ejemplo n.º 9
0
        public void SpawnAtShip(MyPlayer player, string respawnShipId, MyBotDefinition botDefinition)
        {
            Debug.Assert(Sync.IsServer, "Spawning can only be called on the server!");
            if (!Sync.IsServer)
            {
                return;
            }

            ResetRespawnCooldown(player.Id);
            if (Sync.MultiplayerActive)
            {
                SyncCooldownToPlayer(player.Id.SteamId, player.Id.SteamId == Sync.MyId);
            }

            MyCharacter       character    = null;
            MyCockpit         cockpit      = null;
            List <MyCubeGrid> respawnGrids = new List <MyCubeGrid>();

            var respawnShipDef           = MyDefinitionManager.Static.GetRespawnShipDefinition(respawnShipId);
            MyPrefabDefinition prefabDef = respawnShipDef.Prefab;

            // Deploy ship
            Vector3D position = Vector3D.Zero;
            float    planetSpawnHeightRatio = 0.3f;
            float    spawnRangeMin          = 500f;
            float    spawnRangeMax          = 650f;

            if (prefabDef.CubeGrids != null && prefabDef.CubeGrids.Length > 0)
            {
                MyObjectBuilder_CubeGrid firstGrid = prefabDef.CubeGrids[0];
                if (firstGrid.UsePositionForSpawn)
                {
                    position = new Vector3D(
                        firstGrid.PositionAndOrientation.Value.Position.x,
                        firstGrid.PositionAndOrientation.Value.Position.y,
                        firstGrid.PositionAndOrientation.Value.Position.z);
                }

                planetSpawnHeightRatio = MyMath.Clamp(firstGrid.PlanetSpawnHeightRatio, 0.05f, 0.95f); // Clamped to prevent crazy data
                spawnRangeMin          = firstGrid.SpawnRangeMin;
                spawnRangeMax          = firstGrid.SpawnRangeMax;
            }
            Vector3D forward = Vector3.Forward;
            Vector3D up      = Vector3D.Up;

            GetSpawnPosition(prefabDef.BoundingSphere.Radius, ref position, out forward, out up, planetSpawnHeightRatio, spawnRangeMin, spawnRangeMax);

            MyPrefabManager.Static.SpawnPrefab(
                respawnGrids,
                prefabDef.Id.SubtypeName,
                position,
                forward,
                up,
                spawningOptions: VRage.Game.ModAPI.SpawningOptions.RotateFirstCockpitTowardsDirection,
                updateSync: true);

            // Find cockpits
            List <MyCockpit> shipCockpits = new List <MyCockpit>();

            foreach (MyCubeGrid grid in respawnGrids)
            {
                foreach (MyCockpit gridCockpit in grid.GetFatBlocks <MyCockpit>())
                {
                    // Ignore non-functional cockpits
                    if (!gridCockpit.IsFunctional)
                    {
                        continue;
                    }
                    shipCockpits.Add(gridCockpit);
                }
            }

            // First sort cockpits by order: Ship controlling cockpits set to main, then ship controlling cockpits not set to main, lastly whatever remains, e.g. CryoChambers and Passenger Seats
            if (shipCockpits.Count > 1)
            {
                shipCockpits.Sort(delegate(MyCockpit cockpitA, MyCockpit cockpitB)
                {
                    int controlCompare = cockpitB.EnableShipControl.CompareTo(cockpitA.EnableShipControl);
                    if (controlCompare != 0)
                    {
                        return(controlCompare);
                    }

                    int mainCompare = cockpitB.IsMainCockpit.CompareTo(cockpitA.IsMainCockpit);
                    if (mainCompare != 0)
                    {
                        return(mainCompare);
                    }

                    return(0);
                });
            }

            // Finally, select the most important cockpit
            if (shipCockpits.Count > 0)
            {
                cockpit = shipCockpits[0];
            }

            System.Diagnostics.Debug.Assert(cockpit != null, "character is spawning in ship without cockpit !");

            // Create character
            MatrixD matrix = MatrixD.Identity;

            if (cockpit != null)
            {
                matrix             = cockpit.WorldMatrix;
                matrix.Translation = cockpit.WorldMatrix.Translation - Vector3.Up - Vector3.Forward;
            }
            else if (respawnGrids.Count > 0)
            {
                matrix.Translation = respawnGrids[0].PositionComp.WorldAABB.Center + respawnGrids[0].PositionComp.WorldAABB.HalfExtents;
            }

            character = MyCharacter.CreateCharacter(matrix, Vector3.Zero, player.Identity.DisplayName, player.Identity.Model, null, botDefinition, cockpit: cockpit, playerSteamId: player.Id.SteamId);

            CloseRespawnShip(player);
            foreach (var respawnGrid in respawnGrids)
            {
                respawnGrid.ChangeGridOwnership(player.Identity.IdentityId, MyOwnershipShareModeEnum.None);
                respawnGrid.IsRespawnGrid = true;
                player.RespawnShip.Add(respawnGrid.EntityId);
            }

            if (cockpit != null)
            {
                cockpit.AttachPilot(character, false);
                MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(cockpit.CubeGrid), new EndpointId(player.Id.SteamId));
            }

            if (cockpit == null)
            {
                Sync.Players.SetPlayerCharacter(player, character, null);
            }
            else
            {
                character.SetPlayer(player);
                Sync.Players.SetPlayerToCockpit(player, cockpit);
            }
            Sync.Players.RevivePlayer(player);
        }
Ejemplo n.º 10
0
        protected void InternalAddEntity( )
        {
            try
            {
                if (AddEntityQueue.Count == 0)
                {
                    return;
                }

                BaseEntity entityToAdd = AddEntityQueue.Dequeue( );

                if (ExtenderOptions.IsDebugging)
                {
                    ApplicationLog.BaseLog.Debug(String.Format("{0} '{1}': Adding to scene...", entityToAdd.GetType().Name, entityToAdd.DisplayName));
                }

                //Create the backing object
                Type entityType   = entityToAdd.GetType( );
                Type internalType = (Type)BaseEntity.InvokeStaticMethod(entityType, "get_InternalType");
                if (internalType == null)
                {
                    throw new Exception("Could not get internal type of entity");
                }
                entityToAdd.BackingObject = Activator.CreateInstance(internalType);

                //Add the backing object to the main game object manager
                //I don't think this is actually used anywhere?
                MyEntity backingObject = (MyEntity)entityToAdd.BackingObject;

                MyEntity newEntity = MyEntities.CreateFromObjectBuilderAndAdd(entityToAdd.ObjectBuilder);


                if (entityToAdd is FloatingObject)
                {
                    try
                    {
                        //Broadcast the new entity to the clients
                        MyObjectBuilder_EntityBase baseEntity = backingObject.GetObjectBuilder( );
                        //TODO - Do stuff

                        entityToAdd.ObjectBuilder = baseEntity;
                    }
                    catch (Exception ex)
                    {
                        ApplicationLog.BaseLog.Error("Failed to broadcast new floating object");
                        ApplicationLog.BaseLog.Error(ex);
                    }
                }
                else
                {
                    try
                    {
                        //Broadcast the new entity to the clients
                        ApplicationLog.BaseLog.Info("Broadcasted entity to clients.");
                        MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(newEntity));
                        //the misspelling in this function name is driving me  i n s a n e
                    }
                    catch (Exception ex)
                    {
                        ApplicationLog.BaseLog.Error("Failed to broadcast new entity");
                        ApplicationLog.BaseLog.Error(ex);
                    }
                }

                if (ExtenderOptions.IsDebugging)
                {
                    Type type = entityToAdd.GetType( );
                    ApplicationLog.BaseLog.Debug(String.Format("{0} '{1}': Finished adding to scene", entityToAdd.GetType().Name, entityToAdd.DisplayName));
                }
            }
            catch (Exception ex)
            {
                ApplicationLog.BaseLog.Error(ex);
            }
        }
        public override bool HandleCommand(ulong userId, string[] words)
        {
            lock (Docking.Instance)
            {
                foreach (DockingItem dockingItem in Docking.Instance.DockingItems)
                {
                    string dockedShipFileName = Essentials.PluginPath + String.Format("\\Docking\\docked_{0}_{1}_{2}.sbc", dockingItem.PlayerId, dockingItem.TargetEntityId, dockingItem.DockedEntityId);

                    DockingItem dockedShip = dockingItem;
                    IMyEntity   entity     = MyAPIGateway.Entities.GetEntity(x => x.EntityId == dockedShip.TargetEntityId && x is IMyCubeGrid);
                    if (entity == null)
                    {
                        //Communication.SendPrivateInformation(userId, string.Format("Unable to undock ship due to error."));
                        Log.Info(string.Format("Unable to find parent '{0}' for '{1}' - '{2}'", dockingItem.TargetEntityId, dockingItem.DockedEntityId, dockingItem.DockedName));
                        //continue;
                    }

                    if (!File.Exists(dockedShipFileName))
                    {
                        Log.Info(string.Format("Unable to find ship file: {0}", dockedShipFileName));
                        continue;
                    }

//					FileInfo fileInfo = new FileInfo(dockedShipFileName);
                    MyObjectBuilder_CubeGrid cubeGrid;
                    MyObjectBuilderSerializer.DeserializeXML(dockedShipFileName, out cubeGrid);

                    if (entity != null)
                    {
                        // Rotate our ship relative to our saved rotation and the new carrier rotation
                        cubeGrid.PositionAndOrientation = new MyPositionAndOrientation(Matrix.CreateFromQuaternion(Quaternion.CreateFromRotationMatrix(entity.Physics.GetWorldMatrix().GetOrientation()) * dockingItem.SaveQuat).GetOrientation());
                        // Move our ship relative to the new carrier position and orientation
                        Quaternion newQuat    = Quaternion.CreateFromRotationMatrix(entity.Physics.GetWorldMatrix().GetOrientation());
                        Vector3D   rotatedPos = Vector3D.Transform(dockingItem.SavePos, newQuat);
                        //cubeGrid.Position = rotatedPos + parent.GetPosition();
                        cubeGrid.PositionAndOrientation = new MyPositionAndOrientation(MathUtility.RandomPositionFromPoint(entity.GetPosition(), 250f), cubeGrid.PositionAndOrientation.Value.Forward, cubeGrid.PositionAndOrientation.Value.Up);
                    }
                    else
                    {
                        cubeGrid.PositionAndOrientation = new MyPositionAndOrientation(MathUtility.RandomPositionFromPoint(cubeGrid.PositionAndOrientation.Value.Position, 500f), cubeGrid.PositionAndOrientation.Value.Forward, cubeGrid.PositionAndOrientation.Value.Up);
                    }

                    // Add object to world
                    cubeGrid.EntityId        = BaseEntity.GenerateEntityId();
                    cubeGrid.LinearVelocity  = Vector3.Zero;
                    cubeGrid.AngularVelocity = Vector3.Zero;

                    bool undock = false;
                    Wrapper.GameAction(() =>
                    {
                        try
                        {
                            IMyEntity newEntity = MyAPIGateway.Entities.CreateFromObjectBuilderAndAdd(cubeGrid);
                            MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(newEntity));
                            undock = true;
                        }
                        catch (Exception ex)
                        {
                            Log.Info(string.Format("Error undocking ship: {0}", ex.ToString()));
                            Communication.SendPrivateInformation(userId, string.Format("Unable to undock ship due to error."));
                        }
                    });

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

                    File.Delete(dockedShipFileName);
                    Communication.SendPrivateInformation(userId, string.Format("The ship '{0}' has been undocked from docking zone", dockingItem.DockedName));
                }

                Docking.Instance.DockingItems.Clear();
                Docking.Instance.Save();
            }

            return(true);
        }
Ejemplo n.º 12
0
        private void PutPlayerInRespawnGrid(MyPlayer player, List <MyCubeGrid> respawnGrids, MyBotDefinition botDefinition)
        {
            MyCharacter character = null;
            MyCockpit   cockpit   = null;

            // Find cockpits
            List <MyCockpit> shipCockpits = new List <MyCockpit>();

            foreach (MyCubeGrid grid in respawnGrids)
            {
                foreach (MyCockpit gridCockpit in grid.GetFatBlocks <MyCockpit>())
                {
                    // Ignore non-functional cockpits
                    if (!gridCockpit.IsFunctional)
                    {
                        continue;
                    }
                    shipCockpits.Add(gridCockpit);
                }
            }

            // First sort cockpits by order: Ship controlling cockpits set to main, then ship controlling cockpits not set to main, lastly whatever remains, e.g. CryoChambers and Passenger Seats
            if (shipCockpits.Count > 1)
            {
                shipCockpits.Sort(delegate(MyCockpit cockpitA, MyCockpit cockpitB)
                {
                    int controlCompare = cockpitB.EnableShipControl.CompareTo(cockpitA.EnableShipControl);
                    if (controlCompare != 0)
                    {
                        return(controlCompare);
                    }

                    int mainCompare = cockpitB.IsMainCockpit.CompareTo(cockpitA.IsMainCockpit);
                    if (mainCompare != 0)
                    {
                        return(mainCompare);
                    }

                    return(0);
                });
            }

            // Finally, select the most important cockpit
            if (shipCockpits.Count > 0)
            {
                cockpit = shipCockpits[0];
            }

            System.Diagnostics.Debug.Assert(cockpit != null, "character is spawning in ship without cockpit !");

            // Create character
            MatrixD matrix = MatrixD.Identity;

            if (cockpit != null)
            {
                matrix             = cockpit.WorldMatrix;
                matrix.Translation = cockpit.WorldMatrix.Translation - Vector3.Up - Vector3.Forward;
            }
            else if (respawnGrids.Count > 0)
            {
                matrix.Translation = respawnGrids[0].PositionComp.WorldAABB.Center + respawnGrids[0].PositionComp.WorldAABB.HalfExtents;
            }

            character = MyCharacter.CreateCharacter(matrix, Vector3.Zero, player.Identity.DisplayName, player.Identity.Model, null, botDefinition, cockpit: cockpit, playerSteamId: player.Id.SteamId);

            CloseRespawnShip(player);
            foreach (var respawnGrid in respawnGrids)
            {
                respawnGrid.ChangeGridOwnership(player.Identity.IdentityId, MyOwnershipShareModeEnum.None);
                respawnGrid.IsRespawnGrid = true;
                respawnGrid.m_playedTime  = 0;
                player.RespawnShip.Add(respawnGrid.EntityId);
            }
            //SaveRespawnShip(player);

            if (cockpit != null)
            {
                cockpit.AttachPilot(character, false);
                MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(cockpit.CubeGrid), new EndpointId(player.Id.SteamId));
            }

            if (cockpit == null)
            {
                Sync.Players.SetPlayerCharacter(player, character, null);
            }
            else
            {
                character.SetPlayer(player);
                Sync.Players.SetPlayerToCockpit(player, cockpit);
            }
            Sync.Players.RevivePlayer(player);
        }
        public void SpawnAtShip(MyPlayer player, string respawnShipId, MyBotDefinition botDefinition)
        {
            Debug.Assert(Sync.IsServer, "Spawning can only be called on the server!");
            if (!Sync.IsServer)
            {
                return;
            }

            ResetRespawnCooldown(player.Id);
            if (Sync.MultiplayerActive)
            {
                SyncCooldownToPlayer(player.Id.SteamId);
            }

            MyCharacter       character    = null;
            MyCockpit         cockpit      = null;
            List <MyCubeGrid> respawnGrids = new List <MyCubeGrid>();

            var respawnShipDef           = MyDefinitionManager.Static.GetRespawnShipDefinition(respawnShipId);
            MyPrefabDefinition prefabDef = respawnShipDef.Prefab;

            // Deploy ship
            Vector3  direction;
            Vector3D position;

            GetSpawnPosition(prefabDef.BoundingSphere.Radius, out direction, out position);
            MyPrefabManager.Static.SpawnPrefab(
                respawnGrids,
                prefabDef.Id.SubtypeName,
                position,
                -direction,
                Vector3.CalculatePerpendicularVector(-direction),
                spawningOptions: Sandbox.ModAPI.SpawningOptions.RotateFirstCockpitTowardsDirection,
                updateSync: true);

            // Find cockpit
            foreach (var grid in respawnGrids)
            {
                foreach (var block in grid.GetBlocks())
                {
                    if (block.FatBlock is MyCockpit)
                    {
                        cockpit = (MyCockpit)block.FatBlock;
                        break;
                    }
                }
                if (cockpit != null)
                {
                    break;
                }
            }
            System.Diagnostics.Debug.Assert(cockpit != null, "character is spawning in ship without cockpit !");

            // Create character
            MatrixD matrix = MatrixD.Identity;

            if (cockpit != null)
            {
                matrix             = cockpit.WorldMatrix;
                matrix.Translation = cockpit.WorldMatrix.Translation - Vector3.Up - Vector3.Forward;
            }
            else if (respawnGrids.Count > 0)
            {
                matrix.Translation = respawnGrids[0].PositionComp.WorldAABB.Center + respawnGrids[0].PositionComp.WorldAABB.HalfExtents;
            }

            character = MyCharacter.CreateCharacter(matrix, Vector3.Zero, player.Identity.DisplayName, player.Identity.Model, null, botDefinition, cockpit: cockpit, playerSteamId: player.Id.SteamId);

            CloseRespawnShip(player);
            foreach (var respawnGrid in respawnGrids)
            {
                respawnGrid.ChangeGridOwnership(player.Identity.IdentityId, MyOwnershipShareModeEnum.None);
                respawnGrid.IsRespawnGrid = true;
                player.RespawnShip.Add(respawnGrid.EntityId);
            }

            if (cockpit != null)
            {
                cockpit.AttachPilot(character, false);
                MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(cockpit.CubeGrid), new EndpointId(player.Id.SteamId));
            }

            if (cockpit == null)
            {
                Sync.Players.SetPlayerCharacter(player, character, null);
            }
            else
            {
                character.SetPlayer(player);
                Sync.Players.SetPlayerToCockpit(player, cockpit);
            }
            Sync.Players.RevivePlayer(player);
        }
Ejemplo n.º 14
0
        public override bool HandleCommand(ulong userId, string[] words)
        {
            bool force = words.FirstOrDefault(x => x.ToLower( ) == "force") != null;
            bool now   = false;

            if (words.Count( ) > 1 && words[1] == "now")
            {
                now = true;
            }

            if (force && !now)
            {
                EntityManagement.RevealAll( );
            }

            else
            {
                HashSet <IMyEntity> entities = new HashSet <IMyEntity>( );
                Wrapper.GameAction(() => MyAPIGateway.Entities.GetEntities(entities));

                List <MyObjectBuilder_EntityBase> addList = new List <MyObjectBuilder_EntityBase>( );
                int count = 0;

                if (!now)
                {
                    Wrapper.GameAction(() =>
                    {
                        foreach (IMyEntity entity in entities)
                        {
                            if (entity.InScene)
                            {
                                continue;
                            }

                            if (!(entity is IMyCubeGrid))
                            {
                                continue;
                            }

                            MyObjectBuilder_CubeGrid builder = CubeGrids.SafeGetObjectBuilder((IMyCubeGrid)entity);
                            if (builder == null)
                            {
                                continue;
                            }

                            //if ( now )
                            //    EntityManagement.RevealEntity( new KeyValuePair<IMyEntity, string>( entity, "Immediate force reveal" ) );

                            count++;
                        }
                    });
                }

                if (now)
                {
                    Wrapper.GameAction(() =>
                    {
                        foreach (IMyEntity entity in entities)
                        {
                            if (entity.InScene)
                            {
                                continue;
                            }

                            if (!(entity is IMyCubeGrid))
                            {
                                continue;
                            }

                            MyObjectBuilder_CubeGrid builder = CubeGrids.SafeGetObjectBuilder((IMyCubeGrid)entity);
                            if (builder == null)
                            {
                                continue;
                            }

                            count++;

                            IMyCubeGrid grid = (IMyCubeGrid)entity;
                            long ownerId     = 0;
                            string ownerName = "";
                            if (grid.BigOwners.Count > 0)
                            {
                                ownerId   = grid.BigOwners.First( );
                                ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name;
                            }


                            builder.PersistentFlags = (MyPersistentEntityFlags2.InScene | MyPersistentEntityFlags2.CastShadows);
                            MyAPIGateway.Entities.RemapObjectBuilder(builder);

                            //Log.Info("Conceal", string.Format("Force Revealing - Id: {0} -> {4} Display: {1} OwnerId: {2} OwnerName: {3}", entity.EntityId, entity.DisplayName.Replace("\r", "").Replace("\n", ""), ownerId, ownerName, builder.EntityId));
                            Log.Info("Revealing");

                            IMyEntity newEntity = MyAPIGateway.Entities.CreateFromObjectBuilder(builder);
                            entity.InScene      = true;
                            entity.OnAddedToScene(entity);
                            BaseEntityNetworkManager.BroadcastRemoveEntity(entity, false);
                            MyAPIGateway.Entities.AddEntity(newEntity);
                            MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(newEntity));
                            entity.Physics.LinearVelocity  = Vector3.Zero;
                            entity.Physics.AngularVelocity = Vector3.Zero;
                        }
                    });
                }

                if (!now)
                {
                    Log.Info(string.Format("Command would reveal {0} grids.  Type /admin reveal force to reveal them.", count));
                }

                else
                {
                    Log.Info(string.Format("Command revealed {0} grids.", count));
                }
            }
            return(true);
        }
Ejemplo n.º 15
0
        public override bool HandleCommand(ulong userId, string[] words)
        {
            if (!PluginSettings.Instance.DockingEnabled)
            {
                return(false);
            }

            if (words.Length < 1)
            {
                Communication.SendPrivateInformation(userId, GetHelp());
                return(true);
            }

            if (m_undocking)
            {
                Communication.SendPrivateInformation(userId, string.Format("Server is busy, try again"));
                return(true);
            }

            m_undocking = true;
            try
            {
                String pylonName = String.Join(" ", words);
                if (PlayerMap.Instance.GetPlayerIdsFromSteamId(userId).Count < 1)
                {
                    Communication.SendPrivateInformation(userId, string.Format("Unable to find player Id: {0}", userId));
                    return(true);
                }

                long playerId = PlayerMap.Instance.GetPlayerIdsFromSteamId(userId).First( );

                Dictionary <String, List <IMyCubeBlock> > testList;
                List <IMyCubeBlock> beaconList;
                DockingZone.FindByName(pylonName, out testList, out beaconList, playerId);

                if (beaconList.Count == 4)
                {
                    foreach (IMyCubeBlock entity in beaconList)
                    {
                        if (!Entity.CheckOwnership(entity, playerId))
                        {
                            Communication.SendPrivateInformation(userId, string.Format("You do not have permission to use '{0}'.  You must either own all the beacons or they must be shared with faction.", pylonName));
                            return(true);
                        }
                    }

                    IMyCubeBlock e      = beaconList.First( );
                    IMyCubeGrid  parent = (IMyCubeGrid)e.Parent;

                    long[]             beaconListIds = beaconList.Select(p => p.EntityId).ToArray( );
                    long               ownerId       = beaconList.First( ).OwnerId;
                    List <DockingItem> dockingItems  = Docking.Instance.Find(d => d.PlayerId == ownerId && d.TargetEntityId == parent.EntityId && d.DockingBeaconIds.Intersect(beaconListIds).Count( ) == 4);
                    if (dockingItems.Count < 1)
                    {
                        Communication.SendPrivateInformation(userId, string.Format("You have no ships docked in docking zone '{0}'.", pylonName));
                        return(true);
                    }

                    DockingItem dockingItem = dockingItems.First( );

                    // Figure out center of docking area, and other distance information
                    double   maxDistance = 99;
                    Vector3D vPos        = new Vector3D(0, 0, 0);
                    foreach (IMyCubeBlock b in beaconList)
                    {
                        Vector3D beaconPos = Entity.GetBlockEntityPosition(b);
                        vPos += beaconPos;
                    }

                    vPos = vPos / 4;
                    foreach (IMyCubeBlock b in beaconList)
                    {
                        Vector3D beaconPos = Entity.GetBlockEntityPosition(b);
                        maxDistance = Math.Min(maxDistance, Vector3D.Distance(vPos, beaconPos));
                    }

                    List <IMySlimBlock> blocks = new List <IMySlimBlock>( );
                    parent.GetBlocks(blocks);
                    foreach (IMySlimBlock slim_cbe in blocks)
                    {
                        if (slim_cbe is IMyCubeBlock)
                        {
                            IMyCubeBlock cbe = slim_cbe.FatBlock;
                            if (cbe.GetObjectBuilderCubeBlock( ) is MyObjectBuilder_Cockpit)
                            {
                                MyObjectBuilder_Cockpit c = (MyObjectBuilder_Cockpit)cbe.GetObjectBuilderCubeBlock( );
                                if (c.Pilot != null)
                                {
                                    Communication.SendPrivateInformation(userId,
                                                                         string.Format(
                                                                             "Carrier ship has a pilot.  The carrier should be unpiloted and fully stopped before undocking.  (Sometimes this can lag a bit.  Wait 10 seconds and try again)",
                                                                             pylonName));
                                    return(true);
                                }
                            }
                        }
                    }

                    String dockedShipFileName = Essentials.PluginPath + String.Format("\\Docking\\docked_{0}_{1}_{2}.sbc", ownerId, dockingItem.TargetEntityId, dockingItem.DockedEntityId);

                    // Load Entity From File and add to game
                    FileInfo fileInfo = new FileInfo(dockedShipFileName);
                    //CubeGridEntity cubeGrid = new CubeGridEntity(fileInfo);

                    MyObjectBuilder_CubeGrid cubeGrid;
                    MyObjectBuilderSerializer.DeserializeXML(dockedShipFileName, out cubeGrid);

                    // Rotate our ship relative to our saved rotation and the new carrier rotation
                    cubeGrid.PositionAndOrientation =
                        new MyPositionAndOrientation(Matrix.CreateFromQuaternion(Quaternion.CreateFromRotationMatrix(parent.Physics.GetWorldMatrix( ).GetOrientation( )) * dockingItem.SaveQuat).GetOrientation( ));
                    // Move our ship relative to the new carrier position and orientation
                    Quaternion newQuat    = Quaternion.CreateFromRotationMatrix(parent.Physics.GetWorldMatrix( ).GetOrientation( ));
                    Vector3D   rotatedPos = Vector3D.Transform(dockingItem.SavePos, newQuat);
                    //cubeGrid.Position = rotatedPos + parent.GetPosition();
                    cubeGrid.PositionAndOrientation = new MyPositionAndOrientation(rotatedPos + parent.GetPosition( ), cubeGrid.PositionAndOrientation.Value.Forward, cubeGrid.PositionAndOrientation.Value.Up);

                    // Add object to world
                    cubeGrid.EntityId        = BaseEntity.GenerateEntityId( );
                    cubeGrid.LinearVelocity  = Vector3.Zero;
                    cubeGrid.AngularVelocity = Vector3.Zero;

                    bool undock = false;
                    Wrapper.GameAction(() =>
                    {
                        try
                        {
                            IMyEntity entitiy = MyAPIGateway.Entities.CreateFromObjectBuilderAndAdd(cubeGrid);
                            MyMultiplayer.ReplicateImmediatelly(MyExternalReplicable.FindByObject(entitiy));
                            undock = true;
                        }
                        catch (Exception Ex)
                        {
                            Log.Info(string.Format("Error undocking ship: {0}", Ex.ToString( )));
                            Communication.SendPrivateInformation(userId, string.Format("Unable to undock ship due to error."));
                        }
                    });

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

                    //SectorObjectManager.Instance.AddEntity(cubeGrid);

                    // Remove the docking file
                    File.Delete(dockedShipFileName);
                    Docking.Instance.Remove(dockingItem);

                    Communication.SendPrivateInformation(userId, string.Format("The ship '{0}' has been undocked from docking zone '{1}'", dockingItem.DockedName, pylonName));

                    /*
                     * // Queue for cooldown
                     * DockingCooldownItem cItem = new DockingCooldownItem();
                     * cItem.Name = pylonName;
                     * cItem.startTime = DateTime.Now;
                     *
                     * lock (m_cooldownList)
                     *      m_cooldownList.Add(cItem);
                     *
                     * IMyEntity gridEntity = MyAPIGateway.Entities.GetEntityById(dockingItem.DockedEntityId);
                     * IMyCubeGrid cubeGrid = (IMyCubeGrid)gridEntity;
                     *
                     * Quaternion q = Quaternion.CreateFromRotationMatrix(parent.WorldMatrix.GetOrientation()) * dockingItem.SaveQuat;
                     * Quaternion newQuat = Quaternion.CreateFromRotationMatrix(parent.WorldMatrix.GetOrientation());
                     * Vector3 parentPosition = parent.GetPosition();
                     * Vector3 rotatedPos = Vector3.Transform(dockingItem.savePos, newQuat);
                     * Vector3 position = rotatedPos + parentPosition;
                     * Matrix positionMatrix = Matrix.CreateFromQuaternion(q);
                     *
                     * cubeGrid.ChangeGridOwnership(playerId, MyOwnershipShareModeEnum.None);
                     * gridEntity.SetPosition(dockingItem.savePos);
                     *
                     * gridEntity.WorldMatrix = positionMatrix;
                     * gridEntity.SetPosition(position);
                     *
                     * // We need to update again, as this doesn't seem to sync properly?  I set world matrix, and setposition, and it doesn't go where it should, and I
                     * // have to bump into it for it to show up, it's mega weird.
                     *
                     * if (PluginDocking.Settings.DockingItems == null)
                     *      throw new Exception("DockingItems is null");
                     *
                     * // Remove from docked items
                     * PluginDocking.Settings.DockingItems.Remove(dockingItem);
                     *
                     * // Notify user
                     * Communication.SendPrivateInformation(userId, string.Format("The ship '{0}' has been undocked from docking zone '{1}'", gridEntity.DisplayName, pylonName));
                     */
                    // Queue for cooldown

                    /*
                     * DockingCooldownItem cItem = new DockingCooldownItem();
                     * cItem.name = pylonName;
                     * cItem.startTime = DateTime.Now;
                     * PluginDocking.CooldownList.Add(cItem);
                     */
                }
                else if (beaconList.Count > 4)                   // Too many beacons, must be 4
                {
                    Communication.SendPrivateInformation(userId,
                                                         string.Format("Too many beacons with the name or another zone with the name '{0}'.  Place only 4 beacons to create a zone or try a different zone name.",
                                                                       pylonName));
                }
                else                 // Can't find docking zone
                {
                    Communication.SendPrivateInformation(userId,
                                                         string.Format("Can not locate docking zone '{0}'.  There must be 4 beacons with the name '{0}' to create a docking zone.  Beacons must be fully built!",
                                                                       pylonName));
                }
            }
            catch (NullReferenceException ex)
            {
                Log.Error(ex);
            }
            finally
            {
                m_undocking = false;
            }

            return(true);
        }