//public static string CubeGridManagerManagerGetPowerManagerMethod = "get_PowerDistributor"; //public static string CubeGridManagerManagerGetThrusterManagerMethod = "get_ThrustSystem"; #endregion "Attributes" #region "Constructors and Initializers" public CubeGridManagerManager( CubeGridEntity parent, Object backingObject ) { m_parent = parent; m_backingObject = backingObject; //m_thrusterManager = new CubeGridThrusterManager( GetThrusterManager( ), m_parent ); }
public static void SendClientMessage(ulong steamId, string message) { if (PlayerMap.Instance.GetPlayerIdsFromSteamId(steamId).Count < 1) { Log.Info(string.Format("Unable to locate playerId for user with steamId: {0}", steamId)); return; } CubeGridEntity entity = new CubeGridEntity(new FileInfo(Conquest.PluginPath + "CommRelay.sbc")); long entityId = BaseEntity.GenerateEntityId(); entity.EntityId = entityId; entity.DisplayName = string.Format("CommRelayOutput{0}", PlayerMap.Instance.GetPlayerIdsFromSteamId(steamId).First()); entity.PositionAndOrientation = new MyPositionAndOrientation(VRageMath.GenerateRandomEdgeVector(), Vector3.Forward, Vector3.Up); foreach (MyObjectBuilder_CubeBlock block in entity.BaseCubeBlocks) { MyObjectBuilder_Beacon beacon = block as MyObjectBuilder_Beacon; if (beacon != null) { beacon.CustomName = message; } } SectorObjectManager.Instance.AddEntity(entity); }
public void Process() { lock (m_items) { if (!m_items.Any()) return; for (int r = m_items.Count() - 1; r >= 0; r--) { TimedEntityCleanupItem item = m_items[r]; if (DateTime.Now - item.addedTime > TimeSpan.FromSeconds(item.secondsAfterAdding)) { try { IMyEntity entity = null; Wrapper.GameAction(() => { MyAPIGateway.Entities.TryGetEntityById(item.entityId, out entity); }); if(entity != null) { MyObjectBuilder_CubeGrid gridBuilder = CubeGrids.SafeGetObjectBuilder((IMyCubeGrid)entity); if (gridBuilder == null) continue; CubeGridEntity entityToDispose = new CubeGridEntity((MyObjectBuilder_CubeGrid)entity.GetObjectBuilder(), entity); entityToDispose.Dispose(); } else Log.Info("Entity is null"); } catch (Exception ex) { Log.Info(string.Format("Dispose Error: {0}", ex.ToString())); } m_items.RemoveAt(r); } } } }
public static Vector3D RemoveGridsInSphere( ulong userId, Vector3D startPosition, float radius, RemoveGridTypes removeType ) { List<IMyEntity> entitiesToMove = new List<IMyEntity>( ); BoundingSphereD sphere = new BoundingSphereD( startPosition, radius ); Wrapper.GameAction( ( ) => { entitiesToMove = MyAPIGateway.Entities.GetEntitiesInSphere( ref sphere ); } ); List<IMyEntity> entitiesToRemove = new List<IMyEntity>( ); int count = 0; Wrapper.GameAction( ( ) => { foreach ( IMyEntity entity in entitiesToMove ) { if ( !( entity is IMyCubeGrid ) ) continue; IMyCubeGrid grid = (IMyCubeGrid)entity; MyObjectBuilder_CubeGrid cubeGrid = (MyObjectBuilder_CubeGrid)grid.GetObjectBuilder( ); if ( removeType == RemoveGridTypes.Ships && cubeGrid.IsStatic ) continue; if ( removeType == RemoveGridTypes.Stations && !cubeGrid.IsStatic ) continue; entitiesToRemove.Add( entity ); Communication.SendPrivateInformation( userId, string.Format( "Deleting entity '{0}' at {1}", entity.DisplayName, General.Vector3DToString( entity.GetPosition( ) ) ) ); count++; } } ); for ( int r = entitiesToRemove.Count - 1; r >= 0; r-- ) { IMyEntity entity = entitiesToRemove[ r ]; //MyAPIGateway.Entities.RemoveEntity(entity); CubeGridEntity gridEntity = new CubeGridEntity( (MyObjectBuilder_CubeGrid)entity.GetObjectBuilder( ), entity ); gridEntity.Dispose( ); } Communication.SendPrivateInformation( userId, string.Format( "Total entities removed: {0}", count ) ); return startPosition; }
public static void SendBroadcastMessage(string message) { CubeGridEntity entity = new CubeGridEntity(new FileInfo(Essentials.PluginPath + "CommRelay.sbc")); long entityId = BaseEntity.GenerateEntityId(); entity.EntityId = entityId; entity.DisplayName = string.Format("CommRelayBroadcast{0}", m_random.Next(1, 10000)); entity.PositionAndOrientation = new MyPositionAndOrientation(Vector3D.Zero, Vector3.Forward, Vector3.Up); foreach (MyObjectBuilder_CubeBlock block in entity.BaseCubeBlocks) { if (block is MyObjectBuilder_Beacon) { MyObjectBuilder_Beacon beacon = (MyObjectBuilder_Beacon)block; beacon.CustomName = message; } } SectorObjectManager.Instance.AddEntity(entity); TimedEntityCleanup.Instance.Add(entityId); }
public override bool HandleCommand(ulong userId, string[] words) { HashSet<IMyEntity> entitiesFound = CubeGrids.ScanCleanup(userId, words); foreach (IMyEntity entity in entitiesFound) { CubeGridEntity removeEntity = new CubeGridEntity((MyObjectBuilder_CubeGrid)entity.GetObjectBuilder(), entity); removeEntity.Dispose(); IMyCubeGrid grid = (IMyCubeGrid)entity; long ownerId = 0; string ownerName = ""; if (grid.BigOwners.Count > 0) { ownerId = grid.BigOwners.First(); ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name; } Log.Info("Cleanup", string.Format("Cleanup Removed Grid - Id: {0} Display: {1} OwnerId: {2} OwnerName: {3}", entity.EntityId, entity.DisplayName, ownerId, ownerName)); } return true; }
public CubeGridThrusterManager( Object thrusterManager, CubeGridEntity parent ) { m_thrusterManager = thrusterManager; m_parent = parent; }
protected MultiblockStructure( CubeGridEntity parent ) { m_parent = parent; m_definition = new Dictionary<Vector3I, StructureEntry>( ); m_blocks = new List<CubeBlockEntity>( ); }
public List<Vector3I> GetDefinitionMatches( CubeGridEntity cubeGrid ) { try { List<Vector3I> anchorList = new List<Vector3I>( ); foreach ( CubeBlockEntity cubeBlock in cubeGrid.CubeBlocks ) { if ( IsDefinitionMatch( cubeBlock ) ) anchorList.Add( m_anchor.Position ); } return anchorList; } catch ( Exception ex ) { ApplicationLog.BaseLog.Error( ex ); return new List<Vector3I>( ); } }
public void SpawnCargoShipGroup(Vector3 startPosition, Vector3 stopPosition, ulong remoteUserId = 0) { try { //Calculate lowest and highest frequencies float lowestFrequency = 999999; float highestFrequency = 0; foreach (MySpawnGroupDefinition entry in MyDefinitionManager.Static.GetSpawnGroupDefinitions()) { if (entry.Frequency < lowestFrequency) lowestFrequency = entry.Frequency; if (entry.Frequency > highestFrequency) highestFrequency = entry.Frequency; } if (lowestFrequency <= 0) lowestFrequency = 1; //Get a list of which groups *could* spawn Random random = new Random((int)DateTime.Now.ToBinary()); double randomChance = random.NextDouble(); randomChance = randomChance * (highestFrequency / lowestFrequency); List<MySpawnGroupDefinition> possibleGroups = new List<MySpawnGroupDefinition>(); foreach (MySpawnGroupDefinition entry in MyDefinitionManager.Static.GetSpawnGroupDefinitions()) { if (entry.Frequency >= randomChance) { possibleGroups.Add(entry); } } //Determine which group *will* spawn randomChance = random.NextDouble(); int randomShipIndex = Math.Max(0, Math.Min((int)Math.Round(randomChance * possibleGroups.Count, 0), possibleGroups.Count - 1)); MySpawnGroupDefinition randomSpawnGroup = possibleGroups[randomShipIndex]; ChatManager.Instance.SendPrivateChatMessage(remoteUserId, "Spawning cargo group '" + randomSpawnGroup.DisplayNameText.ToString() + "' ..."); //Spawn the ships in the group Matrix orientation = Matrix.CreateLookAt(startPosition, stopPosition, new Vector3(0, 1, 0)); foreach (MySpawnGroupDefinition.SpawnGroupPrefab entry in randomSpawnGroup.Prefabs) { MyPrefabDefinition matchedPrefab = null; foreach (var prefabEntry in MyDefinitionManager.Static.GetPrefabDefinitions()) { MyPrefabDefinition prefabDefinition = prefabEntry.Value; if (prefabDefinition.Id.SubtypeId.ToString() == entry.SubtypeId) { matchedPrefab = prefabDefinition; break; } } if (matchedPrefab == null) continue; //TODO - Build this to iterate through all cube grids in the prefab MyObjectBuilder_CubeGrid objectBuilder = matchedPrefab.CubeGrids[0]; //Create the ship CubeGridEntity cubeGrid = new CubeGridEntity(objectBuilder); //Set the ship position and orientation Vector3 shipPosition = Vector3.Transform(entry.Position, orientation) + startPosition; orientation.Translation = shipPosition; MyPositionAndOrientation newPositionOrientation = new MyPositionAndOrientation(orientation); cubeGrid.PositionAndOrientation = newPositionOrientation; //Set the ship velocity //Speed is clamped between 1.0f and the max cube grid speed Vector3 travelVector = stopPosition - startPosition; travelVector.Normalize(); Vector3 shipVelocity = travelVector * (float)Math.Min(cubeGrid.MaxLinearVelocity, Math.Max(1.0f, entry.Speed)); cubeGrid.LinearVelocity = shipVelocity; cubeGrid.IsDampenersEnabled = false; foreach (MyObjectBuilder_CubeBlock cubeBlock in cubeGrid.BaseCubeBlocks) { //Set the beacon names if (cubeBlock.TypeId == typeof(MyObjectBuilder_Beacon)) { MyObjectBuilder_Beacon beacon = (MyObjectBuilder_Beacon)cubeBlock; beacon.CustomName = entry.BeaconText; } //Set the owner of every block //TODO - Find out if setting to an arbitrary non-zero works for this // TODO Fix the rest of the player manager methods //cubeBlock.Owner = PlayerMap.Instance.GetServerVirtualPlayerId(); cubeBlock.ShareMode = MyOwnershipShareModeEnum.Faction; } //And add the ship to the world SectorObjectManager.Instance.AddEntity(cubeGrid); } ChatManager.Instance.SendPrivateChatMessage(remoteUserId, "Cargo group '" + randomSpawnGroup.DisplayNameText.ToString() + "' spawned with " + randomSpawnGroup.Prefabs.Count.ToString() + " ships at " + startPosition.ToString()); } catch (Exception ex) { LogManager.ErrorLog.WriteLine(ex); } }
public CubeGridThrusterManager(Object thrusterManager, CubeGridEntity parent) { m_thrusterManager = thrusterManager; m_parent = parent; }
public void OnCubeGridMoved( CubeGridEntity cubeGrid ) { }
public void OnCubeGridDeleted( CubeGridEntity cubeGrid ) { foreach ( ProcessHandlerBase handler in _processHandlers ) handler.OnCubeGridDeleted( cubeGrid ); }
protected void Command_Import( ChatEvent chatEvent ) { List<string> commandParts = CommandParser.GetCommandParts( chatEvent.Message ); int paramCount = commandParts.Count - 1; if ( paramCount == 1 ) { try { string fileName = commandParts[ 1 ]; Regex rgx = new Regex( "[^a-zA-Z0-9]" ); string cleanFileName = rgx.Replace( fileName, string.Empty ); string modPath = MyFileSystem.ModsPath; if ( Directory.Exists( modPath ) ) { string exportPath = Path.Combine( modPath, "Exports" ); if ( Directory.Exists( exportPath ) ) { FileInfo importFile = new FileInfo( Path.Combine( exportPath, cleanFileName ) ); if ( importFile.Exists ) { string objectBuilderTypeName = string.Empty; using ( XmlReader reader = XmlReader.Create( importFile.OpenText( ) ) ) { while ( reader.Read( ) ) { if ( reader.NodeType == XmlNodeType.XmlDeclaration ) continue; if ( reader.NodeType != XmlNodeType.Element ) continue; objectBuilderTypeName = reader.Name; break; } } if ( string.IsNullOrEmpty( objectBuilderTypeName ) ) return; switch ( objectBuilderTypeName ) { case "MyObjectBuilder_CubeGrid": CubeGridEntity cubeGrid = new CubeGridEntity( importFile ); SectorObjectManager.Instance.AddEntity( cubeGrid ); break; default: break; } } } } } catch ( Exception ex ) { ApplicationLog.BaseLog.Error( ex ); } } }
private void AddGlobalRelay() { CubeGridEntity entity = new CubeGridEntity(new FileInfo(Essentials.PluginPath + "CommRelay.sbc")); entity.EntityId = BaseEntity.GenerateEntityId(); entity.DisplayName = "CommRelayGlobal"; ApplicationLog.BaseLog.Debug("Attempting to place global relay"); entity.PositionAndOrientation = new MyPositionAndOrientation(MathUtility.GenerateRandomEdgeVector(), Vector3.Forward, Vector3.Up); List<string> commands = new List<string>(); // Give a list of commands foreach(ChatHandlerBase chatBase in Essentials.ChatHandlers) { if (chatBase.GetMultipleCommandText().Length > 0) { foreach (string cmd in chatBase.GetMultipleCommandText()) { string[] command = cmd.Split(new char[] { ' ' }, 2); if (!commands.Contains(command[0])) commands.Add(command[0]); } } else { string[] command = chatBase.GetCommandText().Split(new char[] { ' ' }, 2); if (!commands.Contains(command[0])) commands.Add(command[0]); } } string finalText = ""; foreach(string command in commands) { if (finalText != "") finalText += "\n"; finalText += command; } finalText += "\n/help"; if (PluginSettings.Instance.ServerName != "") finalText += "\n" + "servername:" + PluginSettings.Instance.ServerName; foreach(MyObjectBuilder_CubeBlock block in entity.BaseCubeBlocks) { MyObjectBuilder_Beacon beacon = block as MyObjectBuilder_Beacon; if (beacon != null) { beacon.CustomName = finalText; } } SectorObjectManager.Instance.AddEntity(entity); }
// /admin movefrom x y z x y z radius public override bool HandleCommand(ulong userId, string[] words) { if (words.Count() != 7 && words.Count() != 0) return false; if (words.Count() != 7) { Communication.SendPrivateInformation(userId, GetHelp()); return true; } // Test Input float test = 0; for(int r = 0; r < 7; r++) { if(!float.TryParse(words[r], out test)) { Communication.SendPrivateInformation(userId, string.Format("The value at position {0} - '{1}' is invalid. Please try the command again.", r + 1, words[r])); return true; } } Vector3D startPosition = new Vector3(float.Parse(words[0]), float.Parse(words[1]), float.Parse(words[2])); Vector3D movePosition = new Vector3(float.Parse(words[3]), float.Parse(words[4]), float.Parse(words[5])); Vector3D difference = startPosition - movePosition; float radius = float.Parse(words[6]); Communication.SendPrivateInformation(userId, string.Format("Moving all grids in a radius of {0} near {1} to {2}", radius, General.Vector3DToString(startPosition), General.Vector3DToString(movePosition))); List<MyObjectBuilder_CubeGrid> gridsToMove = new List<MyObjectBuilder_CubeGrid>(); BoundingSphereD sphere = new BoundingSphereD(startPosition, radius); List<IMyEntity> entitiesToMove = MyAPIGateway.Entities.GetEntitiesInSphere(ref sphere); // Wrapper.GameAction(() => // { foreach (IMyEntity entity in entitiesToMove) { if (!(entity is IMyCubeGrid)) continue; Communication.SendPrivateInformation(userId, string.Format("Moving '{0}' from {1} to {2}", entity.DisplayName, General.Vector3DToString(entity.GetPosition()), General.Vector3DToString(entity.GetPosition() + difference))); gridsToMove.Add((MyObjectBuilder_CubeGrid)entity.GetObjectBuilder()); //MyAPIGateway.Entities.RemoveEntity(entity); CubeGridEntity gridEntity = new CubeGridEntity((MyObjectBuilder_CubeGrid)entity.GetObjectBuilder(), entity); gridEntity.Dispose(); } // }); Log.Info("Entities Removed ... pausing"); Thread.Sleep(5000); Log.Info("Removing entities from closed entities"); Wrapper.GameAction(() => { foreach(IMyEntity entity in entitiesToMove) { if (!(entity is IMyCubeGrid)) continue; Log.Info(string.Format("Removing '{0}' for move", entity.DisplayName)); MyAPIGateway.Entities.RemoveFromClosedEntities(entity); } }); Thread.Sleep(10000); Wrapper.GameAction(() => { foreach(MyObjectBuilder_CubeGrid grid in gridsToMove) { grid.PositionAndOrientation = new MyPositionAndOrientation(grid.PositionAndOrientation.Value.Position + difference, grid.PositionAndOrientation.Value.Forward, grid.PositionAndOrientation.Value.Up); //Log.Info(string.Format("Adding '{0}' for move", grid.DisplayName)); Communication.SendPrivateInformation(userId, string.Format("Adding grid '{0}' back to world.", grid.DisplayName)); SectorObjectManager.Instance.AddEntity(new CubeGridEntity(grid)); Thread.Sleep(1000); } }); Communication.SendPrivateInformation(userId, string.Format("Moved {0} grids", gridsToMove.Count)); return true; }
public virtual void OnCubeGridDeleted(CubeGridEntity entity) { }
public virtual void OnCubeGridCreated(CubeGridEntity entity) { }
public CubeGridNetworkManager(CubeGridEntity cubeGrid) { m_cubeGrid = cubeGrid; var entity = m_cubeGrid.BackingObject; m_netManager = BaseObject.InvokeEntityMethod(entity, CubeGridGetNetManagerMethod); }
public void SpawnCargoShipGroup(Vector3 startPosition, Vector3 stopPosition, ulong remoteUserId = 0) { try { //Load the spawn groups SpawnGroupsDefinitionsManager spawnGroupsDefinitionsManager = new SpawnGroupsDefinitionsManager(); FileInfo contentDataFile = new FileInfo(Path.Combine(MyFileSystem.ContentPath, "Data", "SpawnGroups.sbc")); spawnGroupsDefinitionsManager.Load(contentDataFile); //Calculate lowest and highest frequencies float lowestFrequency = 999999; float highestFrequency = 0; foreach (SpawnGroupDefinition entry in spawnGroupsDefinitionsManager.Definitions) { if (entry.Frequency < lowestFrequency) lowestFrequency = entry.Frequency; if (entry.Frequency > highestFrequency) highestFrequency = entry.Frequency; } if (lowestFrequency <= 0) lowestFrequency = 1; //Get a list of which groups *could* spawn Random random = new Random((int)DateTime.Now.ToBinary()); double randomChance = random.NextDouble(); randomChance = randomChance * (highestFrequency / lowestFrequency); List<SpawnGroupDefinition> possibleGroups = new List<SpawnGroupDefinition>(); foreach (SpawnGroupDefinition entry in spawnGroupsDefinitionsManager.Definitions) { if (entry.Frequency >= randomChance) { possibleGroups.Add(entry); } } //Determine which group *will* spawn randomChance = random.NextDouble(); int randomShipIndex = Math.Max(0, Math.Min((int)Math.Round(randomChance * possibleGroups.Count, 0), possibleGroups.Count-1)); SpawnGroupDefinition randomSpawnGroup = possibleGroups[randomShipIndex]; ChatManager.Instance.SendPrivateChatMessage(remoteUserId, "Spawning cargo group '" + randomSpawnGroup.Name + "' ..."); //Spawn the ships in the group Matrix orientation = Matrix.CreateLookAt(startPosition, stopPosition, new Vector3(0, 1, 0)); foreach (SpawnGroupPrefab entry in randomSpawnGroup.Prefabs) { FileInfo prefabFile = new FileInfo(Path.Combine(MyFileSystem.ContentPath, "Data", "Prefabs", entry.SubtypeId + ".sbc")); if (!prefabFile.Exists) continue; //Create the ship CubeGridEntity cubeGrid = new CubeGridEntity(prefabFile); //Set the ship position and orientation Vector3 shipPosition = Vector3.Transform(entry.Position, orientation) + startPosition; orientation.Translation = shipPosition; MyPositionAndOrientation newPositionOrientation = new MyPositionAndOrientation(orientation); cubeGrid.PositionAndOrientation = newPositionOrientation; //Set the ship velocity //Speed is clamped between 1.0f and the max cube grid speed Vector3 travelVector = stopPosition - startPosition; travelVector.Normalize(); Vector3 shipVelocity = travelVector * (float)Math.Min(cubeGrid.MaxLinearVelocity, Math.Max(1.0f, entry.Speed)); cubeGrid.LinearVelocity = shipVelocity; cubeGrid.IsDampenersEnabled = false; foreach (MyObjectBuilder_CubeBlock cubeBlock in cubeGrid.BaseCubeBlocks) { //Set the beacon names if (cubeBlock.TypeId == typeof(MyObjectBuilder_Beacon)) { MyObjectBuilder_Beacon beacon = (MyObjectBuilder_Beacon)cubeBlock; beacon.CustomName = entry.BeaconText; } //Set the owner of every block //TODO - Find out if setting to an arbitrary non-zero works for this cubeBlock.Owner = PlayerMap.Instance.GetServerVirtualPlayerId(); cubeBlock.ShareMode = MyOwnershipShareModeEnum.Faction; } //And add the ship to the world SectorObjectManager.Instance.AddEntity(cubeGrid); //Force a refresh of the cube grid List<CubeBlockEntity> cubeBlocks = cubeGrid.CubeBlocks; } ChatManager.Instance.SendPrivateChatMessage(remoteUserId, "Cargo group '" + randomSpawnGroup.DisplayName + "' spawned with " + randomSpawnGroup.Prefabs.Length.ToString() + " ships at " + startPosition.ToString()); } catch (Exception ex) { LogManager.ErrorLog.WriteLine(ex); } }
public void UpdateCubeBlock(CubeGridEntity parent, CubeBlockEntity cubeBlock) { ApplicationLog.BaseLog.Info( "WCF Service - Received cube block entity '{0}' with id '{1}'", cubeBlock.Name, cubeBlock.EntityId ); foreach (CubeGridEntity cubeGrid in GetSectorCubeGridEntities()) { if (cubeGrid.EntityId == parent.EntityId) { //Find the matching block by either the entity id or the position of the block in the grid foreach (CubeBlockEntity baseBlock in cubeGrid.CubeBlocks) { //If entity id is defined but there is a mismatch, skip this block if (baseBlock.EntityId != 0 && baseBlock.EntityId != cubeBlock.EntityId) continue; //If entity is is NOT defined but there is a position mismatch, skip this block if (baseBlock.EntityId == 0 && baseBlock.Position != cubeBlock.Position) continue; //Copy over the deserialized dummy cube block to the actual cube block Type type = baseBlock.GetType(); PropertyInfo[] properties = type.GetProperties(); foreach (PropertyInfo property in properties) { try { //Check if the property can be publicly set if (!property.CanWrite) continue; if (property.GetSetMethod() == null) continue; //Check if the property has the [DataMember] attribute object[] dataMemberAttributes = property.GetCustomAttributes(typeof(DataMemberAttribute), true); if (dataMemberAttributes == null || dataMemberAttributes.Length == 0) continue; Object newValue = property.GetValue(cubeBlock, new object[] { }); if (newValue == null) continue; Object oldValue = property.GetValue(baseBlock, new object[] { }); if (newValue.Equals(oldValue)) continue; property.SetValue(baseBlock, newValue, new object[] { }); } catch (Exception) { //Do nothing } } break; } break; } } }
public void OnCubeGridLoaded( CubeGridEntity cubeGrid ) { }
// admin deletearea x y z radius public override bool HandleCommand(ulong userId, string[] words) { if (words.Count() > 3) return false; if (!words.Any()) { Communication.SendPrivateInformation(userId, GetHelp()); return true; } int days = -1; if (!int.TryParse(words[0], out days) || days < 0) { Communication.SendPrivateInformation(userId, string.Format("Invalid argument. Days argument must be an integer that is 0 or greater.")); return true; } // Just assume that anything after the days is going to "ignorenologin" bool removeNoLoginInformation = true; bool removeOwnerless = true; if (words.Count() > 1) { foreach (string word in words) { if (word.ToLower() == "ignorenologin") removeNoLoginInformation = false; if (word.ToLower() == "ignoreownerless") removeOwnerless = false; } } Communication.SendPrivateInformation(userId, string.Format("Scanning for grids with owners that haven't logged in {0} days. (Must Have Login Info={1})", days, removeNoLoginInformation)); HashSet<IMyEntity> entities = new HashSet<IMyEntity>(); Wrapper.GameAction(() => { MyAPIGateway.Entities.GetEntities(entities, x => x is IMyCubeGrid); }); HashSet<IMyEntity> entitiesFound = new HashSet<IMyEntity>(); foreach (IMyEntity entity in entities) { if (!(entity is IMyCubeGrid)) continue; IMyCubeGrid grid = (IMyCubeGrid)entity; CubeGridEntity gridEntity = (CubeGridEntity)GameEntityManager.GetEntity(grid.EntityId); MyObjectBuilder_CubeGrid gridBuilder = CubeGrids.SafeGetObjectBuilder(grid); if (gridBuilder == null) continue; // This entity is protected by whitelist if (PluginSettings.Instance.LoginEntityWhitelist.Length > 0 && PluginSettings.Instance.LoginEntityWhitelist.Contains(grid.EntityId.ToString())) continue; if (CubeGrids.GetAllOwners(gridBuilder).Count < 1 && removeOwnerless) { Communication.SendPrivateInformation(userId, string.Format("Found entity '{0}' ({1}) not owned by anyone.", entity.DisplayName, entity.EntityId)); entitiesFound.Add(entity); continue; } foreach (long player in CubeGrids.GetBigOwners(gridBuilder)) { // This playerId is protected by whitelist if (PluginSettings.Instance.LoginPlayerIdWhitelist.Length > 0 && PluginSettings.Instance.LoginPlayerIdWhitelist.Contains(player.ToString())) continue; MyObjectBuilder_Checkpoint.PlayerItem checkItem = PlayerMap.Instance.GetPlayerItemFromPlayerId(player); if (checkItem.IsDead || checkItem.Name == "") { Communication.SendPrivateInformation(userId, string.Format("Found entity '{0}' ({1}) owned by dead player - ID: {2}", entity.DisplayName, entity.EntityId, player)); entitiesFound.Add(entity); continue; } PlayerItem item = Players.Instance.GetPlayerById(player); if ( item == null ) { if ( removeNoLoginInformation ) { Communication.SendPrivateInformation( userId, string.Format( "Found entity '{0}' ({1}) owned by a player with no login info: {2}", entity.DisplayName, entity.EntityId, checkItem.Name ) ); entitiesFound.Add( entity ); } } else if ( item.LastLogin < DateTime.Now.AddDays( days * -1 ) ) { Communication.SendPrivateInformation( userId, string.Format( "Found entity '{0}' ({1}) owned by inactive player: {2}", entity.DisplayName, entity.EntityId, PlayerMap.Instance.GetPlayerItemFromPlayerId( player ).Name ) ); entitiesFound.Add( entity ); } else if ( item.LastLogin >= DateTime.Now.AddDays( days * -1 ) ) { if ( entitiesFound.Contains( entity ) ) entitiesFound.Remove( entity ); break; } } } Communication.SendPrivateInformation(userId, string.Format("Found {0} grids owned by inactive users", entitiesFound.Count)); foreach(IMyEntity entity in entitiesFound) { if (!(entity is IMyCubeGrid)) continue; CubeGridEntity gridEntity = new CubeGridEntity((MyObjectBuilder_CubeGrid)entity.GetObjectBuilder(), entity); gridEntity.Dispose(); } Communication.SendPrivateInformation(userId, string.Format("Removed {0} grids owned by inactive users", entitiesFound.Count())); return true; }
public static bool WaitForLoadingEntity( CubeGridEntity grid ) { int count = 0; while ( grid.IsLoading ) { Thread.Sleep( 100 ); count++; if ( count > 10 ) return false; } return true; }
public void SpawnCargoShipGroup( Vector3 startPosition, Vector3 stopPosition, ulong remoteUserId = 0 ) { try { //Calculate lowest and highest frequencies double lowestFrequency = double.MaxValue; double highestFrequency = 0d; foreach ( MySpawnGroupDefinition entry in MyDefinitionManager.Static.GetSpawnGroupDefinitions( ) ) { if ( entry.Frequency < lowestFrequency ) lowestFrequency = entry.Frequency; if ( entry.Frequency > highestFrequency ) highestFrequency = entry.Frequency; } if ( lowestFrequency <= 0d ) lowestFrequency = 1d; //Get a list of which groups *could* spawn Random random = new Random( ); double randomChance = random.NextDouble( ); randomChance = randomChance * ( highestFrequency / lowestFrequency ); List<MySpawnGroupDefinition> possibleGroups = MyDefinitionManager.Static.GetSpawnGroupDefinitions( ).Where( entry => entry.Frequency >= randomChance ).ToList( ); //Determine which group *will* spawn randomChance = random.NextDouble( ); int randomShipIndex = Math.Max( 0, Math.Min( (int) Math.Round( randomChance * possibleGroups.Count, 0 ), possibleGroups.Count - 1 ) ); MySpawnGroupDefinition randomSpawnGroup = possibleGroups[ randomShipIndex ]; ChatManager.Instance.SendPrivateChatMessage( remoteUserId, string.Format( "Spawning cargo group '{0}' ...", randomSpawnGroup.DisplayNameText ) ); //Spawn the ships in the group Matrix orientation = Matrix.CreateLookAt( startPosition, stopPosition, new Vector3( 0, 1, 0 ) ); foreach ( MySpawnGroupDefinition.SpawnGroupPrefab entry in randomSpawnGroup.Prefabs ) { MyPrefabDefinition matchedPrefab = MyDefinitionManager.Static.GetPrefabDefinitions( ).Select( prefabEntry => prefabEntry.Value ).FirstOrDefault( prefabDefinition => prefabDefinition.Id.SubtypeId.ToString( ) == entry.SubtypeId ); if ( matchedPrefab == null ) continue; foreach ( MyObjectBuilder_CubeGrid objectBuilder in matchedPrefab.CubeGrids ) { //Create the ship CubeGridEntity cubeGrid = new CubeGridEntity( objectBuilder ); //Set the ship position and orientation Vector3 shipPosition = Vector3.Transform( entry.Position, orientation ) + startPosition; orientation.Translation = shipPosition; MyPositionAndOrientation newPositionOrientation = new MyPositionAndOrientation( orientation ); cubeGrid.PositionAndOrientation = newPositionOrientation; //Set the ship velocity //Speed is clamped between 1.0f and the max cube grid speed Vector3 travelVector = stopPosition - startPosition; travelVector.Normalize( ); Vector3 shipVelocity = travelVector * Math.Min( cubeGrid.MaxLinearVelocity, Math.Max( 1.0f, entry.Speed ) ); cubeGrid.LinearVelocity = shipVelocity; //cubeGrid.IsDampenersEnabled = false; foreach ( MyObjectBuilder_CubeBlock cubeBlock in cubeGrid.BaseCubeBlocks ) { //Set the beacon names MyObjectBuilder_Beacon beacon = cubeBlock as MyObjectBuilder_Beacon; if ( beacon != null ) { beacon.CustomName = entry.BeaconText; } //Set the owner of every block //TODO - Find out if setting to an arbitrary non-zero works for this //cubeBlock.Owner = PlayerMap.Instance.GetServerVirtualPlayerId(); cubeBlock.Owner = 0; cubeBlock.ShareMode = MyOwnershipShareModeEnum.Faction; } //And add the ship to the world SectorObjectManager.Instance.AddEntity( cubeGrid ); } } ChatManager.Instance.SendPrivateChatMessage( remoteUserId, string.Format( "Cargo group '{0}' spawned with {1} ships at {2}", randomSpawnGroup.DisplayNameText, randomSpawnGroup.Prefabs.Count, startPosition ) ); } catch ( ArgumentOutOfRangeException ex ) { ApplicationLog.BaseLog.Error( ex ); } catch ( ArgumentNullException ex ) { ApplicationLog.BaseLog.Error( ex ); } catch ( FormatException ex ) { ApplicationLog.BaseLog.Error( ex ); } catch ( Exception ex ) { ApplicationLog.BaseLog.Error( ex ); } }
// admin deletearea x y z radius public override bool HandleCommand(ulong userId, string[] words) { HashSet<IMyEntity> entities = new HashSet<IMyEntity>(); HashSet<IMyEntity> entitiesToConfirm = new HashSet<IMyEntity>(); HashSet<IMyEntity> entitiesConnected = new HashSet<IMyEntity>(); HashSet<IMyEntity> entitiesFound = new HashSet<IMyEntity>(); Wrapper.GameAction(() => { MyAPIGateway.Entities.GetEntities(entities, x => x is IMyCubeGrid); }); foreach (IMyEntity entity in entities) { if (!(entity is IMyCubeGrid)) continue; IMyCubeGrid grid = (IMyCubeGrid)entity; MyObjectBuilder_CubeGrid gridBuilder = CubeGrids.SafeGetObjectBuilder(grid); if (gridBuilder == null) continue; bool found = false; foreach (MyObjectBuilder_CubeBlock block in gridBuilder.CubeBlocks) { if (block.TypeId == typeof(MyObjectBuilder_Beacon)) { found = true; break; } } if (!found) entitiesToConfirm.Add(grid); } CubeGrids.GetGridsUnconnected(entitiesFound, entitiesToConfirm); foreach (IMyEntity entity in entitiesFound) { CubeGridEntity gridEntity = (CubeGridEntity)GameEntityManager.GetEntity(entity.EntityId); if (gridEntity == null) { Log.Info("A found entity gridEntity was null!"); continue; } Communication.SendPrivateInformation(userId, string.Format("Found entity '{0}' ({1}) at {2} with no beacon.", gridEntity.Name, entity.EntityId, General.Vector3DToString(entity.GetPosition()))); } for(int r = entitiesFound.Count - 1; r >= 0; r--) { //MyAPIGateway.Entities.RemoveEntity(entity); IMyEntity entity = entitiesFound.ElementAt(r); CubeGridEntity gridEntity = new CubeGridEntity((MyObjectBuilder_CubeGrid)entity.GetObjectBuilder(), entity); gridEntity.Dispose(); } Communication.SendPrivateInformation(userId, string.Format("Removed {0} grids with no beacons", entitiesFound.Count)); return true; }
public List<Vector3I> GetDefinitionMatches(CubeGridEntity cubeGrid) { try { List<Vector3I> anchorList = new List<Vector3I>(); foreach (CubeBlockEntity cubeBlock in cubeGrid.CubeBlocks) { if(IsDefinitionMatch(cubeBlock)) anchorList.Add(m_anchor.Min); } return anchorList; } catch (Exception ex) { LogManager.ErrorLog.WriteLine(ex); return new List<Vector3I>(); } }