public static bool Intersects(this MyPlanet planet, BoundingSphereD sphere) { Vector3D centre = sphere.Center; Vector3D closestPoint = planet.GetClosestSurfacePointGlobal(ref centre); double minDistance = sphere.Radius; minDistance *= minDistance; return Vector3D.DistanceSquared(centre, closestPoint) <= minDistance; }
public override void UpdateBeforeSimulation() { base.UpdateBeforeSimulation(); m_updateCounter++; if (m_updateCounter % 100 == 0 && MySession.Static.LocalCharacter != null) { m_detectedGrids.Clear(); BoundingSphereD playerSphere = new BoundingSphereD(MySession.Static.LocalCharacter.PositionComp.GetPosition(), 500f); MyGamePruningStructure.GetAllTopMostEntitiesInSphere(ref playerSphere, m_detectedGrids); for (int i = 0; i < m_detectedGrids.Count; i++) { MyCubeGrid grid = m_detectedGrids[i] as MyCubeGrid; if (grid != null) { foreach (var block in grid.CubeBlocks) { if (block.FatBlock is MyFunctionalBlock) (block.FatBlock as MyFunctionalBlock).UpdateSoundEmitters(); } } } foreach (var key in m_emitterLibraryToRemove) { if (m_emitterLibrary.ContainsKey(key)) { m_emitterLibrary[key].StopSound(true); m_emitterLibrary.Remove(key); } } m_emitterLibraryToRemove.Clear(); foreach (var emitter in m_emitterLibrary.Values) emitter.Update(); } }
public static bool FindClosestTreeInRadius(Vector3D fromPosition, float radius, out ItemInfo result) { result = default(ItemInfo); BoundingSphereD sphere = new BoundingSphereD(fromPosition, (double)radius); var entities = MyEntities.GetEntitiesInSphere(ref sphere); double closestDistanceSq = double.MaxValue; foreach (MyEntity entity in entities) { MyTrees trees = entity as MyTrees; if (trees == null) continue; trees.GetPhysicalItemsInRadius(fromPosition, radius, m_tmpEnvItemList); foreach (var tree in m_tmpEnvItemList) { double distanceSq = Vector3D.DistanceSquared(fromPosition, tree.Transform.Position); if (distanceSq < closestDistanceSq) { result.ItemsEntityId = entity.EntityId; result.ItemId = tree.LocalId; result.Target = tree.Transform.Position; closestDistanceSq = distanceSq; } } } entities.Clear(); return closestDistanceSq != double.MaxValue; }
public static void UpdateLcds() { if (!EconomyScript.Instance.ServerConfig.EnableLcds) return; var players = new List<IMyPlayer>(); MyAPIGateway.Players.GetPlayers(players, p => p != null); var updatelist = new HashSet<IMyTextPanel>(); foreach (var player in players) { // Establish a visual range of the LCD. // if there are no players closer than this, don't bother updating it. var sphere = new BoundingSphereD(player.GetPosition(), 75); var list = MyAPIGateway.Entities.GetEntitiesInSphere(ref sphere); foreach (var block in list) { // TODO: projected ship check? var textPanel = block as IMyTextPanel; if (textPanel != null && textPanel.IsFunctional && textPanel.IsWorking && EconomyConsts.LCDTags.Any(tag => textPanel.CustomName.IndexOf(tag, StringComparison.InvariantCultureIgnoreCase) >= 0)) { updatelist.Add((IMyTextPanel)block); } } } foreach (var textPanel in updatelist) ProcessLcdBlock(textPanel); }
private void FindNearbyStuff() { var bs = new BoundingSphereD(Ship.GetPosition(), ConquestMod.MaxEngagementRange); var ents = MyAPIGateway.Entities.GetEntitiesInSphere(ref bs); var closeBy = ents;//entitiesFiltered.Where(z => (z.GetPosition() - drone.GetPosition()).Length() < MaxEngagementRange).ToList(); //var closeAsteroids = asteroids.Where(z => (z.GetPosition() - drone.GetPosition()).Length() < MaxEngagementRange).ToList(); ClearNearbyObjects(); foreach (var closeItem in closeBy) { try { if (closeItem is IMyCubeGrid && !closeItem.Transparent && closeItem.Physics.Mass > 2000) AddNearbyFloatingItem(closeItem); if (closeItem is IMyVoxelBase) { ConquestDroneManager.GetInstance().AddDiscoveredAsteroid(closeItem as IMyVoxelBase); AddNearbyAsteroid((IMyVoxelBase)closeItem); } } catch { //This catches duplicate key entries being put in KnownEntities. } } }
private void FindNearbyStuff() { var bs = new BoundingSphereD(Ship.GetPosition(), ConquestMod.MaxEngagementRange); var ents = MyAPIGateway.Entities.GetEntitiesInSphere(ref bs); var closeBy = ents; //entitiesFiltered.Where(z => (z.GetPosition() - drone.GetPosition()).Length() < MaxEngagementRange).ToList(); //var closeAsteroids = asteroids.Where(z => (z.GetPosition() - drone.GetPosition()).Length() < MaxEngagementRange).ToList(); ClearNearbyObjects(); foreach (var closeItem in closeBy) { try { if (closeItem is Sandbox.ModAPI.IMyCubeGrid) AddNearbyFloatingItem(closeItem); if (closeItem is IMyVoxelBase) { //_entitiesNearDcDrones.Add(closeItem) AddNearbyAsteroid((IMyVoxelBase) closeItem); } } catch { //This catches duplicate key entries being put in KnownEntities. } } }
public MySphereDensityFunction(Vector3D center, double radius, double additionalFalloff) { m_center = center; m_sphereMax = new BoundingSphereD(center, radius + additionalFalloff); m_innerRadius = radius; m_halfFalloff = additionalFalloff / 2.0; m_middleRadius = radius + m_halfFalloff; m_outerRadius = radius + additionalFalloff; }
public static void CollectObjects(ulong steamId, Vector3D destination, double range) { var sphere = new BoundingSphereD(destination, range); var floatingList = MyAPIGateway.Entities.GetEntitiesInSphere(ref sphere); //floatingList = floatingList.Where(e => (e is Sandbox.ModAPI.IMyFloatingObject) || (e is Sandbox.ModAPI.IMyCharacter)).ToList(); floatingList = floatingList.Where(e => (e is Sandbox.ModAPI.IMyFloatingObject) || (e is Sandbox.Game.Entities.MyReplicableEntity)).ToList(); _instance._timer100.Stop(); _instance._workQueue.Clear(); for (var i = 0; i < floatingList.Count; i++) { var item = floatingList[i]; // Check for null physics and IsPhantom, to prevent picking up primitives. if (item.Physics != null && !item.Physics.IsPhantom) { if (item is Sandbox.ModAPI.IMyCharacter) { var character = item.GetObjectBuilder() as MyObjectBuilder_Character; if (!character.Health.HasValue || character.Health.Value > 0) // ignore living players { // TODO: not working currently. It causes body duplicates? //item.Physics.ClearSpeed(); //_workQueue.Enqueue(delegate() { item.SetPosition(destination); }); } } else if (item is IMyFloatingObject || item is Sandbox.Game.Entities.MyReplicableEntity) { // Need to queue the objects, and relocate them over a number of frames, otherwise if they // are all moved simultaneously to the same point in space, they will become stuck. _instance._workQueue.Enqueue(delegate() { //item.SyncObject.UpdatePosition(); // causes Null exception. if (item.Physics != null) { if (MyAPIGateway.Multiplayer.MultiplayerActive) { item.Physics.ClearSpeed(); item.SetPosition(destination); // Doesn't sync to the server. ConnectionHelper.SendMessageToAllPlayers(new MessageSyncEntityPosition() {EntityId = item.EntityId, Position = destination}); } else if (item.Physics != null) { item.Physics.ClearSpeed(); item.SetPosition(destination); // Doesn't sync to the server. } } }); } } } if (_instance._workQueue.Count > 0) _instance._timer100.Start(); }
public void Init(BoundingSphereD explosion, float explosionDamage) { m_explosion = explosion; m_explosionDamage = explosionDamage; AffectedCubeBlocks.Clear(); AffectedCubeGrids.Clear(); m_damageRemaining.Clear(); m_damagedBlocks.Clear(); m_castBlocks.Clear(); }
public static void GetAllBroadcastersInSphere(BoundingSphereD sphere, List<MyDataBroadcaster> result) { m_aabbTree.OverlapAllBoundingSphere<MyDataBroadcaster>(ref sphere, result, false); for(int i = result.Count -1; i >= 0; i--) { var x = result[i]; var dst = (sphere.Radius + ((MyRadioBroadcaster)x).BroadcastRadius); dst*=dst; if (Vector3D.DistanceSquared(sphere.Center, x.BroadcastPosition) > dst) result.RemoveAtFast(i); } }
// admin scan x y z radius public override bool HandleCommand(ulong userId, string[] words) { if (words.Count() != 8 && words.Count() != 0) return false; if (words.Count() != 8) { Communication.SendPrivateInformation(userId, GetHelp()); return true; } // Test Input float test = 0; for(int r = 0; r < 8; 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 Vector3D(float.Parse(words[0]), float.Parse(words[1]), float.Parse(words[2])); Vector3D targetPosition = new Vector3D(float.Parse(words[3]), float.Parse(words[4]), float.Parse(words[5])); float distance = float.Parse(words[6]); float radius = float.Parse(words[7]); Vector3D targetMovement = targetPosition - startPosition; targetMovement.Normalize(); Vector3D finalPosition = targetMovement * distance; finalPosition += startPosition; List<MyObjectBuilder_CubeGrid> gridsToMove = new List<MyObjectBuilder_CubeGrid>(); BoundingSphereD sphere = new BoundingSphereD(finalPosition, radius); List<IMyEntity> entities = MyAPIGateway.Entities.GetEntitiesInSphere(ref sphere); int count = 0; Communication.SendPrivateInformation(userId, string.Format("Scanning {0} meters around {1}", radius, General.Vector3DToString(finalPosition))); Wrapper.GameAction(() => { foreach (IMyEntity entity in entities) { if (!(entity is IMyCubeGrid)) continue; Communication.SendPrivateInformation(userId, string.Format("Found ship {0} at {1}", entity.DisplayName, General.Vector3DToString(entity.GetPosition()))); count++; } }); Communication.SendPrivateInformation(userId, string.Format("Total ships found: {0}", count)); return true; }
public override bool HandleCommand( ulong userId, string[] words ) { Essentials.Log.Info( "Asteroid cleanup" ); HashSet<IMyEntity> entities = new HashSet<IMyEntity>( ); Wrapper.GameAction( ( ) => { MyAPIGateway.Entities.GetEntities( entities ); foreach ( IMyEntity entity in entities ) { if ( entity == null ) continue; if ( entity is IMyVoxelMap ) asteroidPositions.Add( entity.PositionComp.GetPosition( ), (IMyVoxelMap)entity ); else entityPositions.Add( entity.PositionComp.GetPosition( ) ); } } ); //TODO: Use a thread pool to speed this up? DateTime profile = DateTime.Now; Communication.SendPrivateInformation( userId, $"Found {asteroidPositions.Count} asteroids." ); foreach ( var asteroid in asteroidPositions ) { bool found = false; BoundingSphereD bound = new BoundingSphereD( asteroid.Key, 1000 ); foreach ( Vector3D checkPosition in entityPositions ) { if ( bound.Contains( checkPosition ) == ContainmentType.Contains ) { found = true; break; } } if ( !found ) toRemove.Add( asteroid.Value ); } Communication.SendPrivateInformation( userId, $"Found {toRemove.Count} asteroids to remove." ); int count = 0; foreach ( IMyVoxelMap asteroid in toRemove ) { if ( asteroid == null || asteroid.Closed ) continue; count++; Wrapper.GameAction( ( ) => asteroid.Close( ) ); } Communication.SendPrivateInformation( userId, $"Removed {count} asteroids." ); Essentials.Log.Info( "Asteroid cleanup elapsed time: " + (DateTime.Now - profile) ); return true; }
// Blends-out triangles affected by explosion (radius + some safe delta). Triangles there have zero alpha are flaged to not-draw at all. public static void HideTrianglesAfterExplosion(MyVoxelBase voxelMap, ref BoundingSphereD explosionSphere) { VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("MyDecals::HideTrianglesAfterExplosion"); //MyMwcVector3Int renderCellCoord = voxelMap.GetVoxelRenderCellCoordinateFromMeters(ref explosionSphere.Center); //m_decalsForVoxels.HideTrianglesAfterExplosion(voxelMap.VoxelMapId, ref renderCellCoord, ref explosionSphere); foreach (uint id in voxelMap.Render.RenderObjectIDs) { VRageRender.MyRenderProxy.HideDecals(id, explosionSphere.Center, (float)explosionSphere.Radius); } VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock(); }
// /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, $"Moving all grids in a radius of {radius} near {startPosition} to {movePosition}" ); BoundingSphereD sphere = new BoundingSphereD(startPosition, radius); List<IMyEntity> entitiesToMove = MyAPIGateway.Entities.GetEntitiesInSphere(ref sphere); int moveCount = 0; foreach ( IMyEntity entity in entitiesToMove ) { if ( !( entity is IMyCubeGrid ) ) continue; Vector3D target = entity.GetPosition( ) + difference; Communication.SendPrivateInformation( userId, $"Moving '{entity.DisplayName}' from {entity.GetPosition( )} to {target}" ); //position can be set directly on the server Wrapper.GameAction( ( ) => entity.SetPosition( target ) ); moveCount++; } Communication.SendPrivateInformation(userId, $"Moved {moveCount} grids" ); return true; }
public bool Contains(IMyEntity entity) { switch (Shape) { case ProtectionAreaShape.Cube: var boundingBox = new BoundingBoxD(new Vector3D(Center.X - Size, Center.Y - Size, Center.Z - Size), new Vector3D(Center.X + Size, Center.Y + Size, Center.Z + Size)); return boundingBox.Intersects(entity.WorldAABB); case ProtectionAreaShape.Sphere: var boundingSphere = new BoundingSphereD(Center, Size); return boundingSphere.Intersects(entity.WorldAABB); } return false; }
protected override void ReadEntitiesInRange() { m_entitiesInRange.Clear(); BoundingSphereD bsphere = new BoundingSphereD(Center, m_radius); var res = MyEntities.GetEntitiesInSphere(ref bsphere); for (int i = 0; i < res.Count; ++i) { var rootEntity = res[i].GetTopMostParent(); if (!IgnoredEntities.Contains(rootEntity)) m_entitiesInRange[rootEntity.EntityId] = new DetectionInfo(rootEntity, FrontPoint); } res.Clear(); }
public MyVoxelBase GetOverlappingWithSphere(ref BoundingSphereD sphere) { MyVoxelBase ret = null; MyGamePruningStructure.GetAllVoxelMapsInSphere(ref sphere, m_tmpVoxelMapsList); foreach (var voxelMap in m_tmpVoxelMapsList) { if (voxelMap.DoOverlapSphereTest((float)sphere.Radius, sphere.Center)) { ret = voxelMap; break; } } m_tmpVoxelMapsList.Clear(); return ret; }
public static void ApplyEMP(BoundingSphereD location, float strength, TimeSpan duration) { MyAPIGateway.Utilities.TryInvokeOnGameThread(() => { MyGamePruningStructure.GetAllTopMostEntitiesInSphere(ref location, s_entitiesEMP); foreach (IMyEntity entity in s_entitiesEMP) { IMyCubeGrid grid = entity as IMyCubeGrid; if (grid != null) { EMP e = new EMP(); e.Start(grid, duration, ref strength, long.MinValue); } } s_entitiesEMP.Clear(); }); }
// Return true if object intersects specified sphere. // This method doesn't return exact point of intersection or any additional data. // We don't look for closest intersection - so we stop on first intersection found. public override bool GetIntersectionWithSphere(ref BoundingSphereD sphere) { return false; //Matrix invWorld = Matrix.Invert(WorldMatrix); //Vector3 spherePos = Vector3.Transform(sphere.Center, invWorld); //var definition = MyDefinitionManager.Static.GetCubeBlockDefinition(new MyDefinitionId(MyObjectBuilderTypeEnum.Ladder)); //if (definition.ExcludedAreaForCamera != null) // foreach (var b in definition.ExcludedAreaForCamera) // { // if (b.Contains(new BoundingSphere(spherePos, sphere.Radius)) != ContainmentType.Disjoint) // return false; // } //return base.GetIntersectionWithSphere(ref sphere); }
// admin scan x y z radius public override bool HandleCommand(ulong userId, string[] words) { if (words.Count() != 4 && words.Count() != 0) return false; if (!words.Any()) { Communication.SendPrivateInformation(userId, GetHelp()); return true; } // Test Input float test = 0; for(int r = 0; r < 4; 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])); float radius = float.Parse(words[3]); List<MyObjectBuilder_CubeGrid> gridsToMove = new List<MyObjectBuilder_CubeGrid>(); BoundingSphereD sphere = new BoundingSphereD(startPosition, radius); List<IMyEntity> entitiesToMove = MyAPIGateway.Entities.GetEntitiesInSphere(ref sphere); int count = 0; Wrapper.GameAction(() => { foreach (IMyEntity entity in entitiesToMove) { if (!(entity is IMyCubeGrid)) continue; Communication.SendPrivateInformation(userId, string.Format("Found ship '{0}' ({1}) at {2}", entity.DisplayName, entity.EntityId, General.Vector3DToString(entity.GetPosition()))); count++; } }); Communication.SendPrivateInformation(userId, string.Format("Total ships found: {0}", count)); return true; }
/// <summary> /// Gets all seeds within said bounds. /// If a cell inside the bounds is not loaded, it will generate the seed but wont load the cell. /// </summary> /// <param name="bounds">Bounds to get seeds from</param> /// <param name="list">List to put seeds into.</param> public void GetSeedsInBounds(BoundingSphereD bounds, List <MyObjectSeed> list) { BoundingBoxD box = BoundingBoxD.CreateFromSphere(bounds); Vector3I cellId = Vector3I.Floor(box.Min / m_cellSize); for (var it = GetCellsIterator(box); it.IsValid(); it.GetNext(out cellId)) { if (m_loadedCells.ContainsKey(cellId)) { m_loadedCells[cellId].GetAll(list, false); } else { MyProceduralCell cell = GenerateCellSeeds(cellId); cell.GetAll(list); } } }
public static void ApplyEMP(BoundingSphereD location, int strength, TimeSpan duration) { MyAPIGateway.Utilities.TryInvokeOnGameThread(() => { MyGamePruningStructure.GetAllTopMostEntitiesInSphere(ref location, s_entitiesEMP); foreach (IMyEntity entity in s_entitiesEMP) { IMyCubeGrid grid = entity as IMyCubeGrid; if (grid != null) { EMP e; if (!Registrar.TryGetValue(grid, out e)) e = new EMP(grid); e.AddEffect(duration, strength); } } s_entitiesEMP.Clear(); }, s_logger); }
private void GetEntities() { var players = new List <IMyPlayer>(); MyAPIGateway.Players.GetPlayers(players); var player = players[0]; var playerPosition = player.Character.PositionComp.GetPosition(); var sphere = new BoundingSphereD(playerPosition, radius: 50.0); var entities = MyEntities.GetEntitiesInSphere(ref sphere); var rotor1 = entities .Where(x => x is MyMotorAdvancedStator) .Cast <MyMotorAdvancedStator>() .SingleOrDefault(x => x.CustomName.ToString() == "Rotor 1"); entities.Clear(); }
private void MarkCellsDirty(BoundingSphereD toMark, BoundingSphereD toExclude) { ProfilerShort.Begin("Mark dirty cells"); Vector3I cellId = Vector3I.Floor((toMark.Center - toMark.Radius) / CELL_SIZE); for (var iter = GetCellsIterator(toMark); iter.IsValid(); iter.GetNext(out cellId)) { MyProceduralCell cell; if (m_cells.TryGetValue(cellId, out cell)) { if (toExclude.Contains(cell.BoundingVolume) == ContainmentType.Disjoint) { m_dirtyCellsToAdd.Add(cell); } } } ProfilerShort.End(); }
// Return true if voxel map intersects specified sphere. // This method doesn't return exact point of intersection or any additional data. // We don't look for closest intersection - so we stop on first intersection found. public override bool GetIntersectionWithSphere(ref BoundingSphereD sphere) { ProfilerShort.Begin("MyVoxelMap.GetIntersectionWithSphere()"); try { if (!PositionComp.WorldAABB.Intersects(ref sphere)) { return(false); } var localSphere = new BoundingSphereD(sphere.Center - PositionLeftBottomCorner, sphere.Radius); return(Storage.Geometry.Intersects(ref localSphere)); } finally { ProfilerShort.End(); } }
public static List <CollectibleInfo> FindCollectiblesInRadius(Vector3D fromPosition, double radius) { Debug.Assert(m_retvalCollectibleInfos.Count == 0, "The result of the last call of FindComponentsInRadius was not cleared!"); BoundingSphereD sphere = new BoundingSphereD(fromPosition, radius); var entities = MyEntities.GetEntitiesInSphere(ref sphere); foreach (var entity in entities) { CollectibleInfo info = new CollectibleInfo(); MyCubeBlock block = null; MyCubeGrid grid = TryGetAsComponent(entity, out block); if (grid != null) { info.EntityId = grid.EntityId; info.DefinitionId = GetComponentId(block.SlimBlock); if (block.BlockDefinition.Components != null) { info.Amount = block.BlockDefinition.Components[0].Count; } else { Debug.Assert(false, "Block definition does not have any components!"); info.Amount = 0; } m_retvalCollectibleInfos.Add(info); } else if (entity is MyFloatingObject) { var floatingObj = entity as MyFloatingObject; var defId = floatingObj.Item.Content.GetObjectId(); if (MyDefinitionManager.Static.GetPhysicalItemDefinition(defId).Public) { info.EntityId = floatingObj.EntityId; info.DefinitionId = defId; info.Amount = floatingObj.Item.Amount; m_retvalCollectibleInfos.Add(info); } } } entities.Clear(); return(m_retvalCollectibleInfos); }
private void StartWarp() { grid.GetFreePlayers(ref gridPlayers); warpBubble = grid.WorldVolume(); warpBubble.Radius += WarpConstants.warpBubbleBuffer; if (gridPlayers.Count == 0 && Safety) { return; } if (IsInGravity()) { SendMessage(WarpConstants.warnNoEstablish); return; } if (grid.IsStatic || grid.IsInVoxels()) { SendMessage(WarpConstants.warnStatic); return; } UpdateEffect(WarpDriveSession.WarpEffectUpdate.State.InWarp); WarpState = State.Active; Vector3D?currentVelocity = grid.MainGrid?.Physics?.LinearVelocity; if (currentVelocity.HasValue) { double dot = Vector3D.Dot(currentVelocity.Value, gridMatrix.Forward); if (double.IsNaN(dot) || gridMatrix == MatrixD.Zero) { dot = 0; } currentSpeedPt = MathHelper.Clamp(dot, WarpConstants.startSpeed, WarpConstants.maxSpeed); } else { currentSpeedPt = WarpConstants.startSpeed; } SetStatic(true); }
internal static void Update() { foreach (var component in m_pendingComponentsToInit) { if (component.ShouldHaveFoliage()) { var aabb = component.Owner.Aabb; component.m_btreeProxy = MyScene.FoliageDBVH.AddProxy(ref aabb, component, 0); } } m_pendingComponentsToInit.Clear(); BoundingSphereD sphere = new BoundingSphereD(MyRender11.Environment.Matrices.CameraPosition, MyRender11.RenderSettings.FoliageDetails.GrassDrawDistance()); MyScene.FoliageDBVH.OverlapAllBoundingSphere(ref sphere, m_componentsInRadius); foreach (var foliageComponent in m_activeComponents) { foliageComponent.Updated = false; } foreach (var foliageComponent in m_componentsInRadius) { var renderable = foliageComponent.Owner.GetRenderable(); if (renderable.Lods[0].RenderableProxies.Length == 0) continue; foliageComponent.FillStreams(); if (!m_activeComponents.Contains(foliageComponent)) { m_activeComponents.Add(foliageComponent); } foliageComponent.Updated = true; } foreach (var component in m_activeComponents) { if (!component.Updated) { component.InvalidateStreams(); } } m_activeComponents.RemoveWhere(c => c.Updated == false); }
private bool FieldShapeBlocked() { ModulatorGridComponent modComp; MyGrid.Components.TryGet(out modComp); if (ShieldComp.Modulator == null || ShieldComp.Modulator.ModSet.Settings.ModulateVoxels || Session.Enforced.DisableVoxelSupport == 1) { return(false); } var pruneSphere = new BoundingSphereD(DetectionCenter, BoundingRange); var pruneList = new List <MyVoxelBase>(); MyGamePruningStructure.GetAllVoxelMapsInSphere(ref pruneSphere, pruneList); if (pruneList.Count == 0) { return(false); } MobileUpdate(); Icosphere.ReturnPhysicsVerts(DetectMatrixOutside, ShieldComp.PhysicsOutsideLow); foreach (var voxel in pruneList) { if (voxel.RootVoxel == null || voxel != voxel.RootVoxel) { continue; } if (!CustomCollision.VoxelContact(ShieldComp.PhysicsOutsideLow, voxel)) { continue; } Shield.Enabled = false; DsState.State.FieldBlocked = true; DsState.State.Message = true; if (Session.Enforced.Debug == 3) { Log.Line($"Field blocked: - ShieldId [{Shield.EntityId}]"); } return(true); } DsState.State.FieldBlocked = false; return(false); }
public void Update100() { m_distanceToShip = m_initialized && m_shipGrid.Physics != null ? (m_shouldPlay2D ? 0 : (float)Vector3D.DistanceSquared(MySector.MainCamera.Position, m_shipGrid.PositionComp.GetPosition())) : MAX_UPDATE_RANGE_SQ + 1; if (m_initialized && m_shipGrid.Physics != null && m_shipGrid.IsStatic == false && m_distanceToShip < MAX_UPDATE_RANGE_SQ) { if (m_shipThrusters == null) { m_shipThrusters = m_shipGrid.Components.Get <MyEntityThrustComponent>(); } if (m_shipWheels == null) { m_shipWheels = m_shipGrid.GridSystems.WheelSystem; } CalculateShipCategory(); if (m_shipCategory != ShipTypeEnum.Debris && m_shipState != ShipStateEnum.NoPower && (m_singleThrusterTypeShip == false || ShipHasChanged || m_shipThrusters == null || m_shipThrusters.FinalThrust == Vector3.Zero || m_shipWheels.HasWorkingWheels(false))) { CalculateThrusterComposition(); } if (m_shipSoundSource == null) { m_shipSoundSource = m_shipGrid; } if (m_shipGrid.MainCockpit != null && m_shipGrid.GridSizeEnum == MyCubeSize.Small) { m_shipSoundSource = m_shipGrid.MainCockpit; } if (m_shipGrid.GridSizeEnum == MyCubeSize.Large && MySession.Static.LocalCharacter != null) { BoundingSphereD playerSphere = new BoundingSphereD(MySession.Static.LocalCharacter.PositionComp.GetPosition(), LARGE_SHIP_DETECTION_RADIUS); HashSet <MySlimBlock> detectedBlocks = new HashSet <MySlimBlock>(); m_shipGrid.GetBlocksInsideSphere(ref playerSphere, detectedBlocks); m_insideShip = detectedBlocks.Count > 0; } } for (int i = 0; i < m_emitters.Length; i++) { m_emitters[i].Entity = m_shipSoundSource; m_emitters[i].Update(); } }
private IMyEntity GetTarget(string gridName, string name, IMyCubeGrid startingGrid, ref bool foundGrid) { var gridsToProcess = new List <IMyCubeGrid>(); var gridsProcessed = new HashSet <IMyCubeGrid>(); IMyEntity target = null; foundGrid = false; gridsToProcess.Add(startingGrid); while (target == null && gridsToProcess.Count > 0) { var processing = gridsToProcess.Pop(); Write("Processing Grid: " + processing.DisplayName); var fatBlocks = new List <IMySlimBlock>(); processing.GetBlocks(fatBlocks, x => x?.FatBlock != null); var gridBlocks = fatBlocks.ConvertAll(x => x.FatBlock); if (processing.DisplayName == gridName) { target = gridBlocks.First(x => x?.DisplayNameText == name); foundGrid = true; break; } foreach (var antenna in gridBlocks.Where(x => x is IMyRadioAntenna && OwnershipUtils.isSameFactionOrOwner(processing, x)).Cast <IMyRadioAntenna>()) { var sphere = new BoundingSphereD(antenna.GetPosition(), antenna.Radius); gridsToProcess.AddRange(MyAPIGateway.Entities.GetEntitiesInSphere(ref sphere).Where(x => x is IMyCubeGrid).Cast <IMyCubeGrid>().Where(x => !gridsProcessed.Contains(x) && !gridsToProcess.Contains(x))); } foreach (var antenna in gridBlocks.Where(x => x is IMyLaserAntenna && OwnershipUtils.isSameFactionOrOwner(processing, x)).Cast <IMyLaserAntenna>().Where(x => x.Status == MyLaserAntennaStatus.Connected)) { var sphere = new BoundingSphereD(antenna.TargetCoords, 1); gridsToProcess.AddRange(MyAPIGateway.Entities.GetEntitiesInSphere(ref sphere).Where(x => x is IMyCubeGrid).Cast <IMyCubeGrid>().Where(x => !gridsProcessed.Contains(x) && !gridsToProcess.Contains(x))); } gridsProcessed.Add(processing); } return(target); }
public static void GetBlocksInsideSphereFast(MyCubeGrid grid, ref BoundingSphereD sphere, bool checkDestroyed, List <IMySlimBlock> blocks) { var radius = sphere.Radius; radius *= grid.GridSizeR; var center = grid.WorldToGridInteger(sphere.Center); var gridMin = grid.Min; var gridMax = grid.Max; double radiusSq = radius * radius; int radiusCeil = (int)Math.Ceiling(radius); int i, j, k; Vector3I max2 = Vector3I.Min(Vector3I.One * radiusCeil, gridMax - center); Vector3I min2 = Vector3I.Max(Vector3I.One * -radiusCeil, gridMin - center); for (i = min2.X; i <= max2.X; ++i) { for (j = min2.Y; j <= max2.Y; ++j) { for (k = min2.Z; k <= max2.Z; ++k) { if (i * i + j * j + k * k < radiusSq) { MyCube cube; var vector3I = center + new Vector3I(i, j, k); if (grid.TryGetCube(vector3I, out cube)) { var slim = (IMySlimBlock)cube.CubeBlock; if (slim.Position == vector3I) { if (checkDestroyed && slim.IsDestroyed) { continue; } blocks.Add(slim); } } } } } } }
/// <summary> /// Unloads all cells that have been marked to be unloaded. It will remove all objects inside the sphere from /// the world. It will not unload cells that are still in the tracking volume of a tracked entity. /// </summary> /// <param name="trackedEntities">List of tracked entities</param> public void UnloadCells(Dictionary <MyEntity, MyEntityTracker> trackedEntities) { m_toUnloadCells.ApplyAdditions(); if (m_toUnloadCells.Count == 0) { return; } List <MyObjectSeed> cellObjects = new List <MyObjectSeed>(); foreach (MyProceduralCell cell in m_toUnloadCells) { foreach (MyEntityTracker tracker in trackedEntities.Values) { BoundingSphereD boundingVolume = tracker.BoundingVolume; if (boundingVolume.Contains(cell.BoundingVolume) != ContainmentType.Disjoint) { m_toUnloadCells.Remove(cell); break; } } } m_toUnloadCells.ApplyRemovals(); foreach (var cell in m_toUnloadCells) { cell.GetAll(cellObjects); foreach (MyObjectSeed obj in cellObjects) { if (obj.Params.Generated) { CloseObject(obj); } } cellObjects.Clear(); } foreach (MyProceduralCell cell in m_toUnloadCells) { m_cells.Remove(cell.CellId); m_cellsTree.RemoveProxy(cell.proxyId); } m_toUnloadCells.Clear(); }
internal void ComputeAccelSphere() { NearByEntityCache.Clear(); if (MarkedForClose) { return; } AccelChecked = true; var numOfEntities = NearByEntities > 0 ? NearByEntities : 1f; var ratio = (MyProjectiles / numOfEntities) / 10f; var checkVol = Math.Max(ratio > 1 ? ScanVolume.Radius : ScanVolume.Radius * ratio, 500f); NearByEntitySphere = new BoundingSphereD(MyGrid.PositionComp.WorldAABB.Center, checkVol); var qType = ClosestStaticSqr < (checkVol * 2) * (checkVol * 2) ? MyEntityQueryType.Both : MyEntityQueryType.Dynamic; MyGamePruningStructure.GetAllTopMostEntitiesInSphere(ref NearByEntitySphere, NearByEntityCache, qType); }
protected void EnableDetectorsInArea(Vector3D from) { Debug.Assert(m_detectableEntities.Count == 0, "Detected entities weren't cleared"); var boundingSphere = new BoundingSphereD(from, MyConstants.DEFAULT_INTERACTIVE_DISTANCE); MyGamePruningStructure.GetAllEntitiesInSphere(ref boundingSphere, m_detectableEntities); foreach (var ent in m_detectableEntities) { MyUseObjectsComponentBase use; if (ent.Components.TryGet <MyUseObjectsComponentBase>(out use)) { if (use.DetectorPhysics != null) { use.PositionChanged(use.Container.Get <MyPositionComponentBase>()); use.DetectorPhysics.Enabled = true; } } } }
// Calculates intersection of line with any bounding sphere in this model instance. Center of the bounding sphere will be returned. // It takes boundingSphereRadiusMultiplier argument which serves for extending the influence (radius) for interaction with line. public virtual Vector3D?GetIntersectionWithLineAndBoundingSphere(ref LineD line, float boundingSphereRadiusMultiplier) { if (Render.GetModel() == null) { return(null); } BoundingSphereD vol = PositionComp.WorldVolume; vol.Radius *= boundingSphereRadiusMultiplier; // Check if line intersects phys object's current bounding sphere, and if not, return 'no intersection' if (!MyUtils.IsLineIntersectingBoundingSphere(ref line, ref vol)) { return(null); } return(vol.Center); }
private bool MustBeExecuted(IMyPlayer player) { Vector3D position = player.GetPosition(); BoundingSphereD sphere = new BoundingSphereD(position, 3.0); List <MyEntity> entities = MyEntities.GetEntitiesInSphere(ref sphere); double minDist = int.MaxValue; IMyMedicalRoom nearest = null; foreach (MyEntity entity in entities) { if (!(entity is IMyMedicalRoom)) { continue; } IMyMedicalRoom medicalRoom = entity as IMyMedicalRoom; var dist = Vector3D.DistanceSquared(medicalRoom.GetPosition(), position); if (dist < minDist) { minDist = dist; nearest = medicalRoom; } } if (nearest == null) { return(false); } /* Only affect Medbays that have the following customData */ if (nearest.CustomData.Contains("spawnPointMedbay")) { logger.WriteLine(player.DisplayName + " spawned at " + nearest.CustomName + " on grid " + nearest.CubeGrid.Name); return(true); } return(false); }
public override void UpdateBeforeSimulation() { if (HyperDriveLogic.hyperDriveBlock.Enabled) { //var viewDistance = Session.SessionSettings.ViewDistance; var viewSphere = new BoundingSphereD(MyAPIGateway.Session.Player.GetPosition(), 50000); var entList = new List <MyEntity>(); MyGamePruningStructure.GetAllTopMostEntitiesInSphere(ref viewSphere, entList); foreach (var v in entList) { if (v == HyperDriveLogic.hyperDriveBlock.CubeGrid) { continue; } if (HyperDriveLogic.hyper && HyperDriveLogic.hyperFactor > 30) { if (v is MyVoxelBase) { var myBase = v as MyVoxelBase; if (myBase.ContentChanged) { continue; } v.Physics.Enabled = false; v.Render.UpdateRenderObject(false); } else { v.Render.UpdateRenderObject(false); } } else if (!HyperDriveLogic.hyper) { if (v is MyVoxelBase) { v.Physics.Enabled = true; } v.Render.UpdateRenderObject(true); } } } }
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 Vector3D GenerateRandomEdgeVector( ) { float halfExtent = MyAPIGateway.Entities.WorldSafeHalfExtent( ); int maxDist = (halfExtent == 0 ? 100000 : (int)halfExtent); //if the world is infinite, set an upper bound of 100km for spawn location int minDist = (halfExtent == 0 ? 150000 : 0); //if the world is infinite, set a lower bound of 150km to give us a better chance of not spawning in a planet //if the world has a limited distance, anywhere from origin to safe half extent is fair game. maxDist += minDist; //add our bounds together to create a shell of valid positions about the origin int trycount = 0; Vector3D vectorPosition; BoundingSphereD positionSphere = new BoundingSphereD( ); vectorPosition = new Vector3D(GenerateRandomCoord(maxDist, minDist), GenerateRandomCoord(maxDist, minDist), GenerateRandomCoord(maxDist, minDist)); positionSphere = new BoundingSphereD(vectorPosition, 5000); ApplicationLog.BaseLog.Debug("Trying first generated position..."); //check if there's anything within 5km of our generated position while (MyAPIGateway.Entities.GetIntersectionWithSphere(ref positionSphere) != null) { vectorPosition = new Vector3D(GenerateRandomCoord(maxDist, minDist), GenerateRandomCoord(maxDist, minDist), GenerateRandomCoord(maxDist, minDist)); positionSphere = new BoundingSphereD(vectorPosition, 5000); ApplicationLog.BaseLog.Debug("Position failed, retrying new position..."); ApplicationLog.BaseLog.Debug("Position - X:{0:F2} Y:{1:F2} Z:{2:F2}", vectorPosition.X, vectorPosition.Y, vectorPosition.Z); ++trycount; //try 20 times before giving up //we should probably do something other than break on fail, but the distances are so huge, it's unlikely if (trycount > 20) { break; } } return(vectorPosition); }
//protected virtual void RegisterHostileAction(IMyPlayer player, TimeSpan truceDelay) //{ // try // { // #region Sanity checks // if (player == null) // { // Grid.DebugWrite("RegisterHostileAction", "Error: Damager is null."); // return; // } // if (_ownerFaction == null) // { // _ownerFaction = Grid.GetOwnerFaction(); // } // if (_ownerFaction == null || !_ownerFaction.IsNpc()) // { // Grid.DebugWrite("RegisterHostileAction", $"Error: {(_ownerFaction == null ? "can't find own faction" : "own faction isn't recognized as NPC.")}"); // return; // } // #endregion // IMyFaction hostileFaction = player.GetFaction(); // if (hostileFaction == null) // { // Grid.DebugWrite("RegisterHostileAction", "Error: can't find damager's faction"); // return; // } // if (hostileFaction == _ownerFaction) // { // _ownerFaction.Kick(player); // return; // } // //AiSessionCore.WarDeclared = // AiSessionCore.DeclareWar(_ownerFaction, hostileFaction, truceDelay); // //if (!_ownerFaction.IsLawful()) return; // //AiSessionCore.DeclareWar(Diplomacy.Police, hostileFaction, truceDelay); // //AiSessionCore.DeclareWar(Diplomacy.Army, hostileFaction, truceDelay); // } // catch (Exception scrap) // { // LogError("RegisterHostileAction", scrap); // } //} //protected virtual void RegisterHostileAction(IMyFaction hostileFaction, TimeSpan truceDelay) //{ // try // { // if (hostileFaction != null) // { // //AiSessionCore.WarDeclared = // AiSessionCore.DeclareWar(_ownerFaction, hostileFaction, truceDelay); // //if (!_ownerFaction.IsLawful()) return; // //AiSessionCore.DeclareWar(Diplomacy.Police, hostileFaction, truceDelay); // //AiSessionCore.DeclareWar(Diplomacy.Army, hostileFaction, truceDelay); // } // else // { // Grid.DebugWrite("RegisterHostileAction", "Error: can't find damager's faction"); // } // } // catch (Exception scrap) // { // LogError("RegisterHostileAction", scrap); // } //} //TODO Figure out why there is a NULL REFERENCE EXCEPTION from this call on velocity from MyDetectedEntityInfo // velocity = myCubeGrid.Physics.LinearVelocity; + $exception {System.NullReferenceException: Object reference not set to an instance of an object. // at Sandbox.Game.Entities.MyDetectedEntityInfoHelper.Create(MyEntity entity, Int64 sensorOwner, Nullable`1 hitPosition)} // System.NullReferenceException protected List <MyDetectedEntityInfo> LookAround(float radius, Func <MyDetectedEntityInfo, bool> filter = null) { List <MyDetectedEntityInfo> radarData = new List <MyDetectedEntityInfo>(); BoundingSphereD lookaroundSphere = new BoundingSphereD(GridPosition, radius); List <IMyEntity> entitiesAround = MyAPIGateway.Entities.GetTopMostEntitiesInSphere(ref lookaroundSphere); entitiesAround.RemoveAll(x => x == Grid || GridPosition.DistanceTo(x.GetPosition()) < GridRadius * 1.5); long ownerId; if (_ownerFaction != null) { ownerId = _ownerFaction.FounderId; Grid.DebugWrite("LookAround", "Found owner via faction owner"); } else { ownerId = Rc.OwnerId; Grid.DebugWrite("LookAround", "OWNER FACTION NOT FOUND, found owner via RC owner"); } foreach (IMyEntity detectedEntity in entitiesAround) { if (detectedEntity is IMyFloatingObject || detectedEntity.Physics == null) { continue; } MyDetectedEntityInfo radarDetectedEntity = MyDetectedEntityInfoHelper.Create(detectedEntity as MyEntity, ownerId); if (radarDetectedEntity.Type == MyDetectedEntityType.None || radarDetectedEntity.Type == MyDetectedEntityType.Unknown) { continue; } if (filter == null || filter(radarDetectedEntity)) { radarData.Add(radarDetectedEntity); } } //DebugWrite("LookAround", $"Radar entities detected: {String.Join(" | ", RadarData.Select(x => $"{x.Name}"))}"); return(radarData); }
/// <summary> /// Checks if the specified trajectory intersects any natural gravity wells. /// </summary> /// <param name="start">Starting point of the trajectory.</param> /// <param name="end">Destination of the trajectory.</param> /// <param name="raySize">Size of the ray to test with. (Cylinder test)</param> /// DI: Do you mean capsule? /// <returns></returns> public static bool DoesTrajectoryIntersectNaturalGravity(Vector3D start, Vector3D end, double raySize = 0) { // If the start and end point are identical, do a sphere test instead. Vector3D direction = start - end; if (Vector3D.IsZero(direction)) { return(IsPositionInNaturalGravity(start, raySize)); } Ray trajectory = new Ray(start, Vector3.Normalize(direction)); // Clamp ray size to be at least 0. raySize = MathHelper.Max(raySize, 0); for (int i = 0; i < m_naturalGravityGenerators.Count; i++) { IMyGravityProvider provider = m_naturalGravityGenerators[i]; if (provider == null) { continue; } // This should be done some other way, but works for nau MySphericalNaturalGravityComponent spherical = provider as MySphericalNaturalGravityComponent; if (spherical == null) { continue; } //create a bounding sphere to represent the gravity sphere around the planet BoundingSphereD gravitySphere = new BoundingSphereD(spherical.Position, spherical.GravityLimit + raySize); //check for intersections float?intersect = trajectory.Intersects(gravitySphere); if (intersect.HasValue) { return(true); } } return(false); }
public override void Draw() { if (!_initialized) { return; } if (NetworkHandlerSystem.IsClient && _toDraw.Count > 0) { tmpToDraw.Clear(); var sp = new BoundingSphereD(MyAPIGateway.Session.Camera.Position, visibilityRange); _toDraw.GetAllInSphere(tmpToDraw, ref sp); var oldRange = inRange; inRange = new HashSet <IDrawable>(); foreach (var draw in tmpToDraw) { if (draw.NeedDraw && _toDraw.IsVisible(draw)) { draw.Draw(); } if (draw.NeedSphere) { inRange.Add(draw); oldRange.Remove(draw); draw.InSphere.Value = true; } } foreach (var draw in oldRange) { draw.InSphere.Value = false; } oldRange.Clear(); } if (_toDrawScreen.Count > 0) { drawer.Prepare(); foreach (var draw in _toDrawScreen) { draw.Draw(drawer); } } HandleComponentChanges(); }
private bool TestPlacement() { if (MySession.Static.ControlledEntity != null && (MySession.Static.GetCameraControllerEnum() == MyCameraControllerEnum.Entity || MySession.Static.GetCameraControllerEnum() == MyCameraControllerEnum.ThirdPersonSpectator || MySession.Static.GetCameraControllerEnum() == MyCameraControllerEnum.Spectator)) { for (int i = 0; i < m_previewVoxelMaps.Count; ++i) { var aabb = m_previewVoxelMaps[i].PositionComp.WorldAABB; using (m_tmpResultList.GetClearToken()) { MyGamePruningStructure.GetTopMostEntitiesInBox(ref aabb, m_tmpResultList); if (TestPlacement(m_tmpResultList) == false) { return(false); } } } if (m_planetMode) { for (int i = 0; i < m_copiedVoxelMaps.Count; ++i) { MyObjectBuilder_Planet builder = m_copiedVoxelMaps[i] as MyObjectBuilder_Planet; if (builder != null) { using (m_tmpResultList.GetClearToken()) { BoundingSphereD sphere = new BoundingSphereD(m_pastePosition, builder.Radius * 1.1f); MyGamePruningStructure.GetAllTopMostEntitiesInSphere(ref sphere, m_tmpResultList); if (TestPlacement(m_tmpResultList) == false) { return(false); } } } } } } return(true); }
private static Vector3D CollideWithTriangles(BoundingSphereD sphere, Vector3D velocity, Triangle[] triangles, int recurssionDepth) { if (recurssionDepth > MAX_RECURSSION_DEPTH) { return(Vector3D.Zero); } CollisionResult collision = CollidesWith(sphere, triangles, velocity); if (!collision.FoundCollision) { return(velocity); } Vector3D originalDestinationPoint = sphere.Center + velocity; double intersectionDistance = velocity.Length() * collision.IntersectionTime; //Only update if we aren't very close, and if so only move very close //if (intersectionDistance >= VeryCloseDistance) //{ Vector3D normalizedVelocity = velocity.Normalized(); velocity = (intersectionDistance - VeryCloseDistance) * normalizedVelocity; sphere.Center += velocity; //Fake the collision results to match the very close approximation collision.IntersectionPoint -= normalizedVelocity * VeryCloseDistance; //} PlaneD slidingPlane = CollisionExtensions.Plane(collision.IntersectionPoint, sphere.Center - collision.IntersectionPoint); Vector3D destinationPoint = originalDestinationPoint.ProjectOn(slidingPlane); Vector3D newVelocityVector = destinationPoint - collision.IntersectionPoint; if (newVelocityVector.Length() < VeryCloseDistance) { return(velocity); } return(velocity + CollideWithTriangles(sphere, newVelocityVector, triangles, recurssionDepth + 1)); }
public override bool HandleCommand(ulong userId, string[] words) { var entities = MyEntities.GetEntities( ).ToArray( ); var planets = new HashSet<MyPlanet>( ); int count = 0; foreach (var entity in entities) { MyPlanet item = entity as MyPlanet; if (item != null) planets.Add( item ); } foreach (var planet in planets) { var sphere25 = new BoundingSphereD(planet.PositionComp.GetPosition(), planet.MinimumRadius * 0.25); var sphere75 = new BoundingSphereD(planet.PositionComp.GetPosition(), planet.MinimumRadius * 0.75); foreach (var entity in entities) { if (entity.MarkedForClose || entity.Physics == null || entity is MyCharacter) continue; if (sphere25.Contains(entity.PositionComp.GetPosition()) != ContainmentType.Disjoint) { count++; Wrapper.BeginGameAction( entity.Close, null, null ); continue; } if (Vector3.IsZero(entity.Physics.LinearVelocity)) continue; if (sphere75.Contains(entity.PositionComp.GetPosition()) == ContainmentType.Disjoint) continue; count++; Wrapper.BeginGameAction(entity.Close, null, null); } } Communication.SendPrivateInformation( userId, $"Deleted {count} entities trapped in planets." ); return true; }
private static void StartSurprise(object senderEvent) { BoundingSphereD sphere = new BoundingSphereD(new Vector3D(-18.75f, -2.5f, -1.25f), 2); m_getEntities.Clear(); MyGamePruningStructure.GetAllEntitiesInSphere(ref sphere, m_getEntities); m_spawnMedical = null; foreach (var entity in m_getEntities) { m_spawnMedical = entity as MyMedicalRoom; if (m_spawnMedical != null) { m_spawnMedical.OnClose += delegate { m_spawnMedical = null; }; break; } } m_started = true; }
// Observing entities only pick up entity changes when they move. // They need to know about add/remove too private void MarkNearbyObserversToObserve(ObservableEntity observable) { Log.Trace("begin", "MarkNearbyObservingEntitiesForUpdate"); var viewingSphere = new BoundingSphereD(observable.Position, Settings.Instance.RevealVisibilityMeters); List <ObservingEntity> nearbyObserving = ObservingInSphere(viewingSphere); if (nearbyObserving.Count == 0) { Log.Trace("No nearby observing entities", "MarkNearbyObservingEntitiesForUpdate"); //Log.Trace("viewingSphere has center " + Position + " and radius " + RevealVisibilityMeters, "MarkNearbyObservingEntitiesForUpdate"); return; } Log.Trace("Marking " + nearbyObserving.Count + " nearby observing entities for observe update", "MarkNearbyObservingEntitiesForUpdate"); foreach (ObservingEntity observing in nearbyObserving) { observing.MarkForObservingUpdate(); } }
/// <summary> /// Gets a random point beyond sphere /// </summary> private Vector3D GetRandomTarget(BoundingSphereD sphere) { double randRadius = myRandom.NextDouble() * sphere.Radius / 2; double randAngle1 = myRandom.NextDouble() * MathHelper.TwoPi; double randAngle2 = myRandom.NextDouble() * MathHelper.TwoPi; double x = randRadius * Math.Sin(randAngle1) * Math.Cos(randAngle2); double y = randRadius * Math.Sin(randAngle1) * Math.Sin(randAngle2); double z = randRadius * Math.Cos(randAngle1); Vector3D RandomPoint = new Vector3D(x, y, z) + sphere.Center; // set destination to really far ahead //Vector3D travelVector = Vector3D.Normalize(RandomPoint - NavigationDrill.GetPosition()); //Vector3D destination = travelVector * 131072; //Vector3D RandomPoint = new Vector3D(x, y, z); //myLogger.debugLog("Random point inside sphere: {" + sphere.Center + ", " + sphere.Radius + "} is " + RandomPoint, "GetRandomPointInside()"); return(RandomPoint); }
public static bool Intersects(this MyPlanet planet, ref BoundingSphereD sphere) { Vector3D sphereCentre = sphere.Center; Vector3D planetCentre = planet.GetCentre(); double distSq_sphereToPlanetCentre = Vector3D.DistanceSquared(sphereCentre, planetCentre); double everest = planet.MaximumRadius + sphere.Radius; everest *= everest; if (distSq_sphereToPlanetCentre > everest) return false; return true; Vector3D closestPoint = GetClosestSurfacePointGlobal_Safeish(planet, sphereCentre); double minDistance = sphere.Radius * sphere.Radius; if (Vector3D.DistanceSquared(sphereCentre, closestPoint) <= minDistance) return true; return distSq_sphereToPlanetCentre < Vector3D.DistanceSquared(planetCentre, closestPoint); }
public MyExplosionInfo(float playerDamage, float damage, BoundingSphereD explosionSphere, MyExplosionTypeEnum type, bool playSound, bool checkIntersection = true) { PlayerDamage = playerDamage; Damage = damage; ExplosionSphere = explosionSphere; StrengthImpulse = StrengthAngularImpulse = 0.0f; ExcludedEntity = OwnerEntity = HitEntity = null; CascadeLevel = 0; ExplosionFlags = MyExplosionFlags.AFFECT_VOXELS | MyExplosionFlags.APPLY_FORCE_AND_DAMAGE | MyExplosionFlags.CREATE_DEBRIS | MyExplosionFlags.CREATE_DECALS | MyExplosionFlags.CREATE_PARTICLE_EFFECT | MyExplosionFlags.APPLY_DEFORMATION; ExplosionType = type; LifespanMiliseconds = MyExplosionsConstants.EXPLOSION_LIFESPAN; ObjectsRemoveDelayInMiliseconds = 0; ParticleScale = 1.0f; VoxelCutoutScale = 1.0f; Direction = null; VoxelExplosionCenter = explosionSphere.Center; PlaySound = playSound; CheckIntersections = checkIntersection; Velocity = Vector3.Zero; }
public void Clean() { Entity = null; Projectile = null; Intersection.Length = 0; Intersection.Direction = Vector3D.Zero; Intersection.From = Vector3D.Zero; Intersection.To = Vector3D.Zero; Blocks.Clear(); Hit = false; HitPos = null; HitDist = null; Info = null; EventType = Stale; PruneSphere = new BoundingSphereD(); SphereCheck = false; DamageOverTime = false; PulseTrigger = false; }
public static void SphereIntersects(ICollection <BoundingSphereD> Spheres, ICollection <int> Intersections, long?ID = 0) { if (ID == null) { foreach (var Sphere in Spheres) { BoundingSphereD sphere = Sphere; Intersections.Add(WaterMod.Static.GetClosestWater(Sphere.Center)?.Intersects(ref sphere) ?? 0); } } else { Water Water = WaterMod.Static.Waters[ID.Value]; foreach (var Sphere in Spheres) { BoundingSphereD sphere = Sphere; Intersections.Add(Water.Intersects(ref sphere)); } } }
private string ProcessStationLocations(CommandFeedback feedback) { if (!MyAPIGateway.Session.HasCreativeRights) { return("You must have creative rights to use the station location command"); } var stationModule = Manager.GetDependencyProvider <ProceduralStationModule>(); if (stationModule == null) { return("No station module means no stations"); } var factionModule = Manager.GetDependencyProvider <ProceduralFactions>(); if (factionModule == null) { return("No faction module means no stations"); } var stationNoise = stationModule.StationNoise; var sphere = new BoundingSphereD(MyAPIGateway.Session.Camera.Position, MyAPIGateway.Session.SessionSettings.ViewDistance * 10); var id = MyAPIGateway.Session.Player.IdentityId; var aabb = new BoundingBoxD(sphere.Center - sphere.Radius, sphere.Center + sphere.Radius); foreach (var s in stationNoise.TryGetSpawnIn(aabb, sphere.Intersects)) { var position = new Vector3D(s.Item2.X, s.Item2.Y, s.Item2.Z); var cseed = new ProceduralConstructionSeed(factionModule.SeedAt(s.Item2.XYZ()), s.Item2, null, s.Item1.GetHashCode()); var name = "[" + cseed.Faction.Tag + "] " + cseed.Name; foreach (var gps2 in MyAPIGateway.Session.GPS.GetGpsList(id)) { if (gps2.Name.Equals(name)) { MyAPIGateway.Session.GPS.RemoveGps(id, gps2); } } var gps = MyAPIGateway.Session.GPS.Create(name, "", position, true, true); gps.DiscardAt = MyAPIGateway.Session.ElapsedPlayTime + new TimeSpan(0, 5, 0); MyAPIGateway.Session.GPS.AddGps(id, gps); } return(null); }
/// <summary> /// Method returns intersection point between sphere and triangle (which is defined by vertexes and plane). /// If no intersection found, method returns null. /// See below how intersection point can be calculated, because it's not so easy - for example sphere vs. triangle will /// hardly generate just intersection point... more like intersection area or something. /// </summary> public static Vector3?GetSphereTriangleIntersection(ref BoundingSphereD sphere, ref PlaneD trianglePlane, ref MyTriangle_Vertices triangle) { // Vzdialenost gule od roviny trojuholnika double distance; // Zistim, ci sa gula nachadza pred alebo za rovinou trojuholnika, alebo ju presekava MySpherePlaneIntersectionEnum spherePlaneIntersection = GetSpherePlaneIntersection(ref sphere, ref trianglePlane, out distance); // Ak gula presekava rovinu, tak hladam pseudo-priesecnik if (spherePlaneIntersection == MySpherePlaneIntersectionEnum.INTERSECTS) { // Offset ktory pomoze vypocitat suradnicu stredu gule premietaneho na rovinu trojuholnika Vector3D offset = trianglePlane.Normal * distance; // Priesecnik na rovine trojuholnika, je to premietnuty stred gule na rovine trojuholnika Vector3D intersectionPoint; intersectionPoint.X = sphere.Center.X - offset.X; intersectionPoint.Y = sphere.Center.Y - offset.Y; intersectionPoint.Z = sphere.Center.Z - offset.Z; if (GetInsidePolygonForSphereCollision(ref intersectionPoint, ref triangle)) // Ak priesecnik nachadza v trojuholniku { // Toto je pripad, ked sa podarilo premietnut stred gule na rovinu trojuholnika a tento priesecnik sa // nachadza vnutri trojuholnika (tzn. sedia uhly) return((Vector3)intersectionPoint); } else // Ak sa priesecnik nenachadza v trojuholniku, este stale sa moze nachadzat na hrane trojuholnika { Vector3?edgeIntersection = GetEdgeSphereCollision(ref sphere.Center, (float)sphere.Radius / 1.0f, ref triangle); if (edgeIntersection != null) { // Toto je pripad, ked sa priemietnuty stred gule nachadza mimo trojuholnika, ale intersection gule a trojuholnika tam // je, pretoze gula presekava jednu z hran trojuholnika. Takze vratim suradnice priesecnika na jednej z hran. return(edgeIntersection.Value); } } } // Sphere doesn't collide with any triangle return(null); }
public static bool IntersectsVoxel(ref CapsuleD capsule, out MyVoxelBase hitVoxel, out Vector3D hitPosition, bool checkPlanet, double capsuleLength = -1d) { Profiler.StartProfileBlock(); if (capsuleLength < 0) { Vector3D.Distance(ref capsule.P0, ref capsule.P1, out capsuleLength); } double halfLength = capsuleLength * 0.5d; Vector3D temp; Vector3D.Add(ref capsule.P0, ref capsule.P1, out temp); Vector3D middle; Vector3D.Multiply(ref temp, 0.5d, out middle); double radius = halfLength + capsule.Radius; BoundingSphereD worldSphere = new BoundingSphereD() { Center = middle, Radius = radius }; List <MyVoxelBase> voxels = ResourcePool <List <MyVoxelBase> > .Get(); MyGamePruningStructure.GetAllVoxelMapsInSphere(ref worldSphere, voxels); foreach (MyVoxelBase voxel in voxels) { if ((voxel is MyVoxelMap || voxel is MyPlanet && checkPlanet) && Intersects(ref capsule, voxel, out hitPosition, capsuleLength)) { hitVoxel = voxel; voxels.Clear(); ResourcePool.Return(voxels); Profiler.EndProfileBlock(); return(true); } } voxels.Clear(); ResourcePool.Return(voxels); hitVoxel = null; hitPosition = Vector3.Invalid; Profiler.EndProfileBlock(); return(false); }
public static Vector3D GenerateRandomEdgeVector( ) { float halfExtent = MyAPIGateway.Entities.WorldSafeHalfExtent( ); int maxDist = (halfExtent == 0 ? 100000 : (int)halfExtent); //if the world is infinite, set an upper bound of 100km for spawn location int minDist = (halfExtent == 0 ? 150000 : 0); //if the world is infinite, set a lower bound of 150km to give us a better chance of not spawning in a planet //if the world has a limited distance, anywhere from origin to safe half extent is fair game. maxDist += minDist; //add our bounds together to create a shell of valid positions about the origin int trycount = 0; Vector3D vectorPosition; BoundingSphereD positionSphere = new BoundingSphereD( ); vectorPosition = new Vector3D( GenerateRandomCoord( maxDist, minDist ), GenerateRandomCoord( maxDist, minDist ), GenerateRandomCoord( maxDist, minDist ) ); positionSphere = new BoundingSphereD( vectorPosition, 5000 ); ApplicationLog.BaseLog.Debug( "Trying first generated position..." ); //check if there's anything within 5km of our generated position while ( MyAPIGateway.Entities.GetIntersectionWithSphere( ref positionSphere ) != null ) { vectorPosition = new Vector3D( GenerateRandomCoord( maxDist, minDist ), GenerateRandomCoord( maxDist, minDist ), GenerateRandomCoord( maxDist, minDist ) ); positionSphere = new BoundingSphereD( vectorPosition, 5000 ); ApplicationLog.BaseLog.Debug( "Position failed, retrying new position..." ); ApplicationLog.BaseLog.Debug( "Position - X:{0:F2} Y:{1:F2} Z:{2:F2}", vectorPosition.X, vectorPosition.Y, vectorPosition.Z ); ++trycount; //try 20 times before giving up //we should probably do something other than break on fail, but the distances are so huge, it's unlikely if ( trycount > 20 ) break; } return vectorPosition; }
public override bool Invoke(string messageText) { var match = Regex.Match(messageText, @"/stopall(?:\s{1,}(?<RANGE>[^\s]*)){0,1}", RegexOptions.IgnoreCase); if (match.Success) { var strRange = match.Groups["RANGE"].Captures.Count > 0 ? match.Groups["RANGE"].Captures[0].Value : "100"; double range = 100; double.TryParse(strRange, out range); range = Math.Abs(range); var playerEntity = MyAPIGateway.Session.Player.Controller.ControlledEntity.Entity; var destination = playerEntity.WorldAABB.Center; var sphere = new BoundingSphereD(destination, range); var entityList = MyAPIGateway.Entities.GetEntitiesInSphere(ref sphere); entityList = entityList.Where(e => (e is Sandbox.ModAPI.IMyFloatingObject) || (e is Sandbox.ModAPI.IMyCharacter) || (e is Sandbox.ModAPI.IMyCubeGrid)).ToList(); int counter = 0; foreach (var item in entityList) { // Check for null physics and IsPhantom, to prevent picking up primitives. if (item.Physics != null && !item.Physics.IsPhantom) { if (!MyAPIGateway.Multiplayer.MultiplayerActive) item.Stop(); else ConnectionHelper.SendMessageToServer(new MessageSyncEntity() { EntityId = item.EntityId, Type = SyncEntityType.Stop }); counter++; } } MyAPIGateway.Utilities.ShowMessage("Stopped", "{0} items within {1:N}m.", counter, range); return true; } return false; }
public override bool Invoke(string messageText) { if (messageText.StartsWith("/pullobjects ", StringComparison.InvariantCultureIgnoreCase)) { var match = Regex.Match(messageText, @"/pullobjects\s{1,}(?<R>[+-]?((\d+(\.\d*)?)|(\.\d+)))\s{1,}(?<V>[+-]?((\d+(\.\d*)?)|(\.\d+)))", RegexOptions.IgnoreCase); if (match.Success) { var range = double.Parse(match.Groups["R"].Value, CultureInfo.InvariantCulture); var velocity = double.Parse(match.Groups["V"].Value, CultureInfo.InvariantCulture); var playerEntity = MyAPIGateway.Session.Player.Controller.ControlledEntity.Entity; var destination = playerEntity.WorldAABB.Center; var sphere = new BoundingSphereD(destination, range); var floatingList = MyAPIGateway.Entities.GetEntitiesInSphere(ref sphere); floatingList = floatingList.Where(e => (e is Sandbox.ModAPI.IMyFloatingObject) || (e is Sandbox.ModAPI.IMyCharacter)).ToList(); foreach (var item in floatingList) { // Check for null physics and IsPhantom, to prevent picking up primitives. if (item.Physics != null && !item.Physics.IsPhantom) { if (item is Sandbox.ModAPI.IMyCharacter) { var character = item.GetObjectBuilder() as MyObjectBuilder_Character; if (!character.Health.HasValue || character.Health.Value > 0) // ignore living players continue; } var position = item.GetPosition(); var vector = Vector3D.Normalize(destination - position) * velocity; item.Physics.LinearVelocity = vector; } } return true; } } return false; }
public EffectSoundEmitter(uint id, Vector3 position, MySoundPair sound) { ParticleSoundId = id; Updated = true; MyEntity entity = null; if (MyFakes.ENABLE_NEW_SOUNDS && MySession.Static.Settings.RealisticSound)//snap emitter to closest block - used for realistic sounds { List<MyEntity> m_detectedObjects = new List<MyEntity>(); BoundingSphereD effectSphere = new BoundingSphereD(MySession.Static.LocalCharacter != null ? MySession.Static.LocalCharacter.PositionComp.GetPosition() : MySector.MainCamera.Position, 2f); MyGamePruningStructure.GetAllEntitiesInSphere(ref effectSphere, m_detectedObjects); float distBest = float.MaxValue; float dist; for (int i = 0; i < m_detectedObjects.Count; i++) { MyCubeBlock block = m_detectedObjects[i] as MyCubeBlock; if (block != null) { dist = Vector3.DistanceSquared(MySession.Static.LocalCharacter.PositionComp.GetPosition(), block.PositionComp.GetPosition()); if (dist < distBest) { dist = distBest; entity = block; } } } m_detectedObjects.Clear(); } Emitter = new MyEntity3DSoundEmitter(entity); Emitter.SetPosition(position); if (sound == null) sound = MySoundPair.Empty; Emitter.PlaySound(sound); if (Emitter.Sound != null) OriginalVolume = Emitter.Sound.Volume; else OriginalVolume = 1f; Emitter.Update(); SoundPair = sound; }