private void ProcessProjector(IMyProjector projector) { MyCubeGrid grid = (MyCubeGrid)projector.ProjectedGrid; foreach (IMySlimBlock block in grid.GetBlocks()) { if (projector.CanBuild(block, false) == BuildCheckResult.OK) { using (Lock.AcquireExclusiveUsing()) { if (!PotentialTargetList.Contains(block)) { PotentialTargetList.Add(block); } } } } }
public void FoundPilotedShip(long playerIdentityId, MyCubeGrid ship) { var shipPosition = ship.PositionComp.GetPosition(); var shipBlocks = ship.GetBlocks(); var totalBlocks = shipBlocks.Count(); FoundShips[playerIdentityId] = new ZoneScanResultItem() { PlayerIdentityId = playerIdentityId, Ship = ship, DistanceToCenter = Vector3D.Distance(ZoneCenter, shipPosition) //, //IsLargeShip = (largeBlocks > smallBlocks), //ShipBlockCount = largeBlocks + smallBlocks //TODO: This should be probably based on large block count }; ShipsFound = FoundShips.Count; }
//gets the grid with largest number of blocks in logical group public MyCubeGrid GetLogicalGroupRepresentative(MyCubeGrid grid) { var group = MyCubeGridGroups.Static.Logical.GetGroup(grid); if (group == null || group.Nodes.Count == 0) { return(grid); } MyCubeGrid output = group.Nodes.First().NodeData; foreach (var node in group.Nodes) { if (node.NodeData.GetBlocks().Count > output.GetBlocks().Count) { output = node.NodeData; } } return(output); }
public void CollectMassElements(MyCubeGrid grid, IDictionary <Vector3I, HkMassElement> massResults) { foreach (var block in grid.GetBlocks()) { if (block.FatBlock is MyCompoundCubeBlock) { foreach (var cmpBlock in ((MyCompoundCubeBlock)(block.FatBlock)).GetBlocks()) { if (cmpBlock.BlockDefinition.BlockTopology == MyBlockTopology.TriangleMesh) { AddMass(cmpBlock, massResults); } } } else { AddMass(block, massResults); } } }
public bool AddGrid(MyCubeGrid grid) { HashSet <Sandbox.Game.Entities.Cube.MySlimBlock> lst = new HashSet <Sandbox.Game.Entities.Cube.MySlimBlock>(); foreach (var block in grid.GetBlocks()) { if (block.FatBlock is MyCompoundCubeBlock) { bool added = false; foreach (var subb in (block.FatBlock as MyCompoundCubeBlock).GetBlocks()) { if (AddBlock(subb)) { added = true; } } if (added) { lst.Add(block); } } else { if (AddBlock(block)) { lst.Add(block); } } } foreach (var b in lst) { Vector3I pos = b.Position; Vector3UByte size = new Vector3UByte(1, 1, 1); grid.RazeBlocks(ref pos, ref size); // grid.RemoveBlock(b, true); not synced } return(lst.Count > 0); }
internal bool AddGridSmallToLargeConnection(MyCubeGrid grid) { if (!grid.IsStatic) { return(false); } if (!grid.EnableSmallToLargeConnections || !grid.SmallToLargeConnectionsInitialized) { return(false); } bool flag = false; foreach (MySlimBlock block in grid.GetBlocks()) { if (!(block.FatBlock is MyFracturedBlock)) { flag |= this.AddBlockSmallToLargeConnection(block); } } return(flag); }
public void CollectMassElements(MyCubeGrid grid, IDictionary <Vector3I, HkMassElement> massResults) { if (massResults != null) { foreach (MySlimBlock block in grid.GetBlocks()) { if (block.FatBlock is MyCompoundCubeBlock) { foreach (MySlimBlock block2 in ((MyCompoundCubeBlock)block.FatBlock).GetBlocks()) { if (block2.BlockDefinition.BlockTopology == MyBlockTopology.TriangleMesh) { this.AddMass(block2, massResults); } } continue; } this.AddMass(block, massResults); } } }
public static ulong GetBattlePoints(MyCubeGrid grid) { ulong points = 0; foreach (var block in grid.GetBlocks()) { MyCompoundCubeBlock compoundBlock = block.FatBlock as MyCompoundCubeBlock; if (compoundBlock != null) { foreach (var blockInCompound in compoundBlock.GetBlocks()) { points += GetBattlePoints(blockInCompound); } } else { points += GetBattlePoints(block); } } return(points); }
public void Collect(MyCubeGrid grid, MyVoxelSegmentation segmenter, MyVoxelSegmentationType segmentationType, IDictionary <Vector3I, HkMassElement> massResults) { foreach (var block in grid.GetBlocks()) { if (block.FatBlock is MyCompoundCubeBlock) { CollectCompoundBlock((MyCompoundCubeBlock)block.FatBlock, massResults); Debug.Assert(IsValid(), "Overlapping shapes detected, block shapes cannot overlap!"); } else { CollectBlock(block, block.BlockDefinition.PhysicsOption, massResults); Debug.Assert(IsValid(), "Overlapping shapes detected, block shapes cannot overlap!"); } } AddSegmentedParts(grid.GridSize, segmenter, segmentationType); m_tmpCubes.Clear(); Debug.Assert(Shapes.Count > 0, "Shape count cannot be zero"); Debug.Assert(massResults == null || massResults.Count > 0, "No mass elements, something is wrong!"); }
public static bool Repair(MyGroups <MyCubeGrid, MyGridPhysicalGroupData> .Group group, CommandContext Context) { foreach (MyGroups <MyCubeGrid, MyGridPhysicalGroupData> .Node groupNodes in group.Nodes) { MyCubeGrid grid = groupNodes.NodeData; var gridOwner = OwnershipUtils.GetOwner(grid); HashSet <MySlimBlock> blocks = grid.GetBlocks(); foreach (MySlimBlock block in blocks) { long owner = block.OwnerId; if (owner == 0) { owner = gridOwner; } if (block.CurrentDamage > 0 || block.HasDeformation) { block.ClearConstructionStockpile(null); block.IncreaseMountLevel(block.MaxIntegrity, owner, null, 10000, true); MyCubeBlock cubeBlock = block.FatBlock; if (cubeBlock != null) { grid.ChangeOwnerRequest(grid, cubeBlock, 0, MyOwnershipShareModeEnum.Faction); if (owner != 0) { grid.ChangeOwnerRequest(grid, cubeBlock, owner, MyOwnershipShareModeEnum.Faction); } } } } } return(true); }
public void RemoveGrid(MyCubeGrid grid) { grid.OnNameChanged -= OnGridNameChange; grid.OnGridSplit -= OnGridSplit; //grid.OnStaticChanged -= OnStaticStateChanged; grid.OnBlockAdded -= OnBlockAdded; grid.OnBlockRemoved -= OnBlockRemoved; //grid.OnBlockIntegrityChanged -= OnBlockIntegrityChanged; //grid.OnBlockOwnershipChanged -= OnOwnershipChanged; SQLQueryData.WriteToDatabase(new GridDescription() { GridId = grid.EntityId, Removed = Tools.DateTime }); foreach (MySlimBlock block in grid.GetBlocks()) { OnBlockRemoved(block); } }
private void SetPrefabPosition(MyEntity entity, MatrixD newWorldMatrix) { MyCubeGrid cubeGrid = entity as MyCubeGrid; if (cubeGrid != null) { if (cubeGrid.IsStatic) { Vector3 rounded = default(Vector3I); if (MyCubeBuilder.CubeBuilderDefinition.BuildingSettings.StaticGridAlignToCenter) { rounded = Vector3I.Round(newWorldMatrix.Translation / cubeGrid.GridSize) * cubeGrid.GridSize; } else { rounded = Vector3I.Round(newWorldMatrix.Translation / cubeGrid.GridSize + 0.5f) * cubeGrid.GridSize - 0.5f * cubeGrid.GridSize; } //moveVector = new Vector3D(rounded - newWorldMatrix.Translation); newWorldMatrix.Translation = rounded; cubeGrid.PositionComp.SetWorldMatrix(newWorldMatrix, forceUpdate: true); if (MyPerGameSettings.Destruction) { Debug.Assert(cubeGrid.Physics != null && cubeGrid.Physics.Shape != null); if (cubeGrid.Physics != null && cubeGrid.Physics.Shape != null) { cubeGrid.Physics.Shape.RecalculateConnectionsToWorld(cubeGrid.GetBlocks()); } } } else { //newWorldMatrix.Translation += moveVector; cubeGrid.PositionComp.SetWorldMatrix(newWorldMatrix, forceUpdate: true); } } }
private bool Refresh() { m_frameCounter++; // Change detected by changing block count if (m_grid.GetBlocks().Count == BlockCount && !m_needsRecalc) { return(false); } m_needsRecalc = false; m_selectedGrid = m_grid; var ts = Stopwatch.GetTimestamp(); BlockCount = m_grid.GetBlocks().Count; LoadBlocks(); AddNeighbours(); if (AlgIndex == 0) { using (Stats.Timing.Measure("SI TOTAL - FindAndCaculateFromStatic", VRage.Stats.MyStatTypeEnum.Sum | VRage.Stats.MyStatTypeEnum.DontDisappearFlag)) { FindAndCaculateFromStatic(); } } else if (AlgIndex == 1) { using (Stats.Timing.Measure("SI TOTAL - FindAndCaculateFromDynamic", VRage.Stats.MyStatTypeEnum.Sum | VRage.Stats.MyStatTypeEnum.DontDisappearFlag)) { FindAndCaculateFromDynamic(); } } else if (AlgIndex == 2) { using (Stats.Timing.Measure("SI TOTAL - FindAndCaculateAdvanced", VRage.Stats.MyStatTypeEnum.Sum | VRage.Stats.MyStatTypeEnum.DontDisappearFlag)) { FindAndCaculateFromAdvanced(); } } else { using (Stats.Timing.Measure("SI TOTAL - FindAndCaculateAdvancedStatic", VRage.Stats.MyStatTypeEnum.Sum | VRage.Stats.MyStatTypeEnum.DontDisappearFlag)) { FindAndCaculateFromAdvancedStatic(); } } using (Stats.Timing.Measure("SI - Sum", VRage.Stats.MyStatTypeEnum.Sum | VRage.Stats.MyStatTypeEnum.DontDisappearFlag)) { foreach (var node in All) { //node.Value.TotalSupportingWeight = 0; } foreach (var node in All) { float sum = 0; for (int i = 0; i < 6; i++) { sum += Math.Abs(node.Value.SupportingWeights[i]); //sum = Math.Max(sum, Math.Abs(node.Value.SupportingWeights[i])); } if (!(sum == 0 && node.Value.PathCount == 0)) { // sum = sum * 2 - 1; node.Value.TotalSupportingWeight += node.Value.IsStatic ? 0 : (sum * 0.5f / node.Value.PathCount); } } // Idea behind blur: // When block is supporting too much weight, it deforms still supports something, but allows neighbour block to support more weight, thus sharing support for (int i = 0; BlurEnabled && i < BlurIterations; i++) { foreach (var node in DynamicBlocks) { node.Ratio = 0; } foreach (var node in DynamicBlocks) { float sum = node.TotalSupportingWeight; int count = 1; foreach (var n in node.Neighbours) { if (!BlurStaticShareSupport && n.IsStatic) { continue; } sum += n.TotalSupportingWeight; count++; } float avg = sum / count; node.Ratio += (avg - node.TotalSupportingWeight) * BlurAmount; foreach (var n in node.Neighbours) { if (n.IsStatic) { continue; } n.Ratio += (avg - n.TotalSupportingWeight) * BlurAmount; } } foreach (var node in DynamicBlocks) { node.TotalSupportingWeight += node.Ratio; } } foreach (var node in All) { TotalMax = Math.Max(TotalMax, node.Value.TotalSupportingWeight); } var timeMs = (Stopwatch.GetTimestamp() - ts) / (float)Stopwatch.Frequency * 1000.0f; //Console.WriteLine(String.Format("Generated structural integrity, time: {0}ms, object name: {1}", timeMs, m_grid.ToString())); } return(true); }
public MyOndraSimulator3(MyCubeGrid grid) { m_grid = grid; m_selectedGrid = m_grid; SelectedCube = m_grid.GetBlocks().First().Position; }
public MyTomasInputComponent() { AddShortcut(MyKeys.Delete, true, true, false, false, () => "Delete all characters", delegate { foreach (var obj in MyEntities.GetEntities().OfType <MyCharacter>()) { if (obj == MySession.ControlledEntity) { MySession.SetCameraController(MyCameraControllerEnum.Spectator); } obj.Close(); } foreach (var obj in MyEntities.GetEntities().OfType <MyCubeGrid>()) { foreach (var obj2 in obj.GetBlocks()) { if (obj2.FatBlock is MyCockpit) { var cockpit = obj2.FatBlock as MyCockpit; if (cockpit.Pilot != null) { cockpit.Pilot.Close(); } } } } return(true); }); AddShortcut(MyKeys.NumPad4, true, false, false, false, () => "Spawn cargo ship or barbarians", delegate { var theEvent = MyGlobalEvents.GetEventById(new MyDefinitionId(typeof(MyObjectBuilder_GlobalEventBase), "SpawnCargoShip")); if (theEvent == null) { theEvent = MyGlobalEvents.GetEventById(new MyDefinitionId(typeof(MyObjectBuilder_GlobalEventBase), "SpawnBarbarians")); } if (theEvent != null) { MyGlobalEvents.RemoveGlobalEvent(theEvent); theEvent.SetActivationTime(TimeSpan.FromSeconds(1)); MyGlobalEvents.AddGlobalEvent(theEvent); } return(true); }); AddShortcut(MyKeys.NumPad5, true, false, false, false, () => "Spawn random meteor", delegate { var camera = MySector.MainCamera; var target = camera.Position + MySector.MainCamera.ForwardVector * 20.0f; var spawnPosition = target + MySector.DirectionToSunNormalized * 1000.0f; if (MyUtils.GetRandomFloat(0.0f, 1.0f) < 0.2f) { MyMeteor.SpawnRandomLarge(spawnPosition, -MySector.DirectionToSunNormalized); } else { MyMeteor.SpawnRandomSmall(spawnPosition, -MySector.DirectionToSunNormalized); } return(true); }); AddShortcut(MyKeys.NumPad8, true, false, false, false, () => "Switch control to next entity", delegate { if (MySession.ControlledEntity != null) { //we already are controlling this object var cameraController = MySession.GetCameraControllerEnum(); if (cameraController != MyCameraControllerEnum.Entity && cameraController != MyCameraControllerEnum.ThirdPersonSpectator) { MySession.SetCameraController(MyCameraControllerEnum.Entity, MySession.ControlledEntity.Entity); } else { var entities = MyEntities.GetEntities().ToList(); int lastKnownIndex = entities.IndexOf(MySession.ControlledEntity.Entity); var entitiesList = new List <MyEntity>(); if (lastKnownIndex + 1 < entities.Count) { entitiesList.AddRange(entities.GetRange(lastKnownIndex + 1, entities.Count - lastKnownIndex - 1)); } if (lastKnownIndex != -1) { entitiesList.AddRange(entities.GetRange(0, lastKnownIndex + 1)); } MyCharacter newControlledObject = null; for (int i = 0; i < entitiesList.Count; i++) { var character = entitiesList[i] as MyCharacter; if (character != null) { newControlledObject = character; break; } } if (newControlledObject != null) { MySession.LocalHumanPlayer.Controller.TakeControl(newControlledObject); } } } return(true); }); AddShortcut(MyKeys.NumPad7, true, false, false, false, () => "Use next ship", delegate { MyCharacterInputComponent.UseNextShip(); return(true); }); AddShortcut(MyKeys.NumPad9, true, false, false, false, () => "Debug new grid screen", delegate { MyGuiSandbox.AddScreen(new DebugNewGridScreen()); return(true); }); AddShortcut(MyKeys.N, true, false, false, false, () => "Refill all batteries", delegate { foreach (var entity in MyEntities.GetEntities()) { MyCubeGrid grid = entity as MyCubeGrid; if (grid != null) { foreach (var block in grid.GetBlocks()) { MyBatteryBlock battery = block.FatBlock as MyBatteryBlock; if (battery != null) { battery.CurrentStoredPower = battery.MaxStoredPower; } } } } return(true); }); AddShortcut(MyKeys.U, true, false, false, false, () => "Spawn new character", delegate { var character = MyCharacterInputComponent.SpawnCharacter(); return(true); }); AddShortcut(MyKeys.NumPad2, true, false, false, false, () => "Merge static grids", delegate { // Try to merge all static large grids HashSet <MyCubeGrid> ignoredGrids = new HashSet <MyCubeGrid>(); while (true) { // Flag that we need new entities enumeration bool needNewEntitites = false; foreach (var entity in MyEntities.GetEntities()) { MyCubeGrid grid = entity as MyCubeGrid; if (grid != null && grid.IsStatic && grid.GridSizeEnum == MyCubeSize.Large) { if (ignoredGrids.Contains(grid)) { continue; } List <MySlimBlock> blocks = grid.GetBlocks().ToList(); foreach (var block in blocks) { var mergedGrid = grid.DetectMerge(block); if (mergedGrid == null) { continue; } needNewEntitites = true; // Grid merged to other grid? Then break and loop all entities again. if (mergedGrid != grid) { break; } } if (!needNewEntitites) { ignoredGrids.Add(grid); } } if (needNewEntitites) { break; } } if (!needNewEntitites) { break; } } return(true); }); AddShortcut(MyKeys.Add, true, false, false, false, () => "Increase wheel animation speed", delegate { USE_WHEEL_ANIMATION_SPEED += 0.05f; return(true); }); AddShortcut(MyKeys.Subtract, true, false, false, false, () => "Decrease wheel animation speed", delegate { USE_WHEEL_ANIMATION_SPEED -= 0.05f; return(true); }); AddShortcut(MyKeys.Divide, true, false, false, false, () => "Show model texture names", delegate { MyFakes.ENABLE_DEBUG_DRAW_TEXTURE_NAMES = !MyFakes.ENABLE_DEBUG_DRAW_TEXTURE_NAMES; return(true); }); AddShortcut(MyKeys.NumPad1, true, false, false, false, () => "Throw from spectator: " + Sandbox.Game.Components.MySessionComponentThrower.USE_SPECTATOR_FOR_THROW, delegate { Sandbox.Game.Components.MySessionComponentThrower.USE_SPECTATOR_FOR_THROW = !Sandbox.Game.Components.MySessionComponentThrower.USE_SPECTATOR_FOR_THROW; return(true); }); AddShortcut(MyKeys.F2, true, false, false, false, () => "Spectator to next small grid", () => SpectatorToNextGrid(MyCubeSize.Small)); AddShortcut(MyKeys.F3, true, false, false, false, () => "Spectator to next large grid", () => SpectatorToNextGrid(MyCubeSize.Large)); }
public void CollectMassElements(MyCubeGrid grid, IDictionary<Vector3I, HkMassElement> massResults) { foreach (var block in grid.GetBlocks()) { if (block.FatBlock is MyCompoundCubeBlock) { foreach (var cmpBlock in ((MyCompoundCubeBlock)(block.FatBlock)).GetBlocks()) { if (cmpBlock.BlockDefinition.BlockTopology == MyBlockTopology.TriangleMesh) { AddMass(cmpBlock, massResults); } } } else { AddMass(block, massResults); } } }
public MyFatBlockReader(MyCubeGrid grid) { m_enumerator = grid.GetBlocks().GetEnumerator(); }
private void RecreateControls() { Debug.Assert(m_infoPage != null, "Terminal page is null"); if (m_infoPage == null) { return; } if (MyFakes.ENABLE_CENTER_OF_MASS) { var centerBtn = (MyGuiControlCheckbox)m_infoPage.Controls.GetControlByName("CenterBtn"); centerBtn.IsChecked = MyCubeGrid.ShowCenterOfMass; centerBtn.IsCheckedChanged = centerBtn_IsCheckedChanged; var pivotBtn = (MyGuiControlCheckbox)m_infoPage.Controls.GetControlByName("PivotBtn"); pivotBtn.IsChecked = MyCubeGrid.ShowGridPivot; pivotBtn.IsCheckedChanged = pivotBtn_IsCheckedChanged; } var showGravityGizmoBtn = (MyGuiControlCheckbox)m_infoPage.Controls.GetControlByName("ShowGravityGizmo"); showGravityGizmoBtn.IsChecked = MyCubeGrid.ShowGravityGizmos; showGravityGizmoBtn.IsCheckedChanged = showGravityGizmos_IsCheckedChanged; var showSenzorGizmoBtn = (MyGuiControlCheckbox)m_infoPage.Controls.GetControlByName("ShowSenzorGizmo"); showSenzorGizmoBtn.IsChecked = MyCubeGrid.ShowSenzorGizmos; showSenzorGizmoBtn.IsCheckedChanged = showSenzorGizmos_IsCheckedChanged; var showAntenaGizmoBtn = (MyGuiControlCheckbox)m_infoPage.Controls.GetControlByName("ShowAntenaGizmo"); showAntenaGizmoBtn.IsChecked = MyCubeGrid.ShowAntennaGizmos; showAntenaGizmoBtn.IsCheckedChanged = showAntenaGizmos_IsCheckedChanged; var friendAntennaRange = (MyGuiControlSlider)m_infoPage.Controls.GetControlByName("FriendAntennaRange"); friendAntennaRange.Value = MyHudMarkerRender.FriendAntennaRange; friendAntennaRange.ValueChanged += (MyGuiControlSlider s) => { MyHudMarkerRender.FriendAntennaRange = s.Value; }; var enemyAntennaRange = (MyGuiControlSlider)m_infoPage.Controls.GetControlByName("EnemyAntennaRange"); enemyAntennaRange.Value = MyHudMarkerRender.EnemyAntennaRange; enemyAntennaRange.ValueChanged += (MyGuiControlSlider s) => { MyHudMarkerRender.EnemyAntennaRange = s.Value; }; var ownedAntennaRange = (MyGuiControlSlider)m_infoPage.Controls.GetControlByName("OwnedAntennaRange"); ownedAntennaRange.Value = MyHudMarkerRender.OwnerAntennaRange; ownedAntennaRange.ValueChanged += (MyGuiControlSlider s) => { MyHudMarkerRender.OwnerAntennaRange = s.Value; }; if (MyFakes.ENABLE_TERMINAL_PROPERTIES) { var renameShipLabel = (MyGuiControlLabel)m_infoPage.Controls.GetControlByName("RenameShipLabel"); var renameShipBtn = (MyGuiControlButton)m_infoPage.Controls.GetControlByName("RenameShipButton"); var renameShipText = (MyGuiControlTextbox)m_infoPage.Controls.GetControlByName("RenameShipText"); if (renameShipText != null && m_grid != null) { renameShipText.Text = m_grid.DisplayName; } var showRenameShip = IsPlayerOwner(m_grid); renameShipLabel.Visible = showRenameShip; renameShipBtn.Visible = showRenameShip; renameShipText.Visible = showRenameShip; } var convertBtn = (MyGuiControlButton)m_infoPage.Controls.GetControlByName("ConvertBtn"); var convertToStationBtn = (MyGuiControlButton)m_infoPage.Controls.GetControlByName("ConvertToStationBtn"); MyGuiControlList list = (MyGuiControlList)m_infoPage.Controls.GetControlByName("InfoList"); list.Controls.Clear(); var setDestructibleBlocks = (MyGuiControlCheckbox)m_infoPage.Controls.GetControlByName("SetDestructibleBlocks"); setDestructibleBlocks.Visible = MySession.Static.Settings.ScenarioEditMode || MySession.Static.IsScenario; setDestructibleBlocks.Enabled = MySession.Static.Settings.ScenarioEditMode; if (m_grid == null || m_grid.Physics == null) { convertBtn.Enabled = false; convertToStationBtn.Enabled = false; RecreateServerLimitInfo(list); return; } if (!m_grid.IsStatic) { convertBtn.Enabled = false; convertToStationBtn.Enabled = true; } else { convertBtn.Enabled = true; convertToStationBtn.Enabled = false; } if (m_grid.GridSizeEnum == MyCubeSize.Small) { convertToStationBtn.Enabled = false; } if (!m_grid.BigOwners.Contains(MySession.Static.LocalPlayerId)) { convertBtn.Enabled = false; convertToStationBtn.Enabled = false; } setDestructibleBlocks.IsChecked = m_grid.DestructibleBlocks; setDestructibleBlocks.IsCheckedChanged = setDestructibleBlocks_IsCheckedChanged; int gravityCounter = 0; if (m_grid.BlocksCounters.ContainsKey(typeof(MyObjectBuilder_GravityGenerator))) { gravityCounter = m_grid.BlocksCounters[typeof(MyObjectBuilder_GravityGenerator)]; } int massCounter = 0; if (m_grid.BlocksCounters.ContainsKey(typeof(MyObjectBuilder_VirtualMass))) { massCounter = m_grid.BlocksCounters[typeof(MyObjectBuilder_VirtualMass)]; } int lightCounter = 0; if (m_grid.BlocksCounters.ContainsKey(typeof(MyObjectBuilder_InteriorLight))) { lightCounter = m_grid.BlocksCounters[typeof(MyObjectBuilder_InteriorLight)]; } var conveyorCounter = 0; foreach (var key in m_grid.BlocksCounters.Keys) { Type blockType = MyCubeBlockFactory.GetProducedType(key); if (typeof(IMyConveyorSegmentBlock).IsAssignableFrom(blockType) || typeof(IMyConveyorEndpointBlock).IsAssignableFrom(blockType)) { conveyorCounter += m_grid.BlocksCounters[key]; } } int polygonCounter = 0; foreach (var block in m_grid.GetBlocks()) { if (block.FatBlock != null) { polygonCounter += block.FatBlock.Model.GetTrianglesCount(); } } foreach (var cell in m_grid.RenderData.Cells.Values) { foreach (var part in cell.CubeParts) { polygonCounter += part.Model.GetTrianglesCount(); } } int thrustCount = 0; var thrustComp = m_grid.Components.Get <MyEntityThrustComponent>(); if (thrustComp != null) { thrustCount = thrustComp.ThrustCount; } MyGuiControlLabel thrustCountLabel = new MyGuiControlLabel(text: new StringBuilder().AppendStringBuilder(MyTexts.Get(MySpaceTexts.TerminalTab_Info_Thrusters)).AppendInt32(thrustCount).ToString()); MyGuiControlLabel polygonCount = new MyGuiControlLabel(text: new StringBuilder().AppendStringBuilder(MyTexts.Get(MySpaceTexts.TerminalTab_Info_Triangles)).AppendInt32(polygonCounter).ToString()); polygonCount.SetToolTip(MySpaceTexts.TerminalTab_Info_TrianglesTooltip); MyGuiControlLabel cubeCount = new MyGuiControlLabel(text: new StringBuilder().AppendStringBuilder(MyTexts.Get(MySpaceTexts.TerminalTab_Info_Blocks)).AppendInt32(m_grid.GetBlocks().Count).ToString()); cubeCount.SetToolTip(MySpaceTexts.TerminalTab_Info_BlocksTooltip); MyGuiControlLabel blockCount = new MyGuiControlLabel(text: new StringBuilder().AppendStringBuilder(MyTexts.Get(MySpaceTexts.TerminalTab_Info_NonArmor)).AppendInt32(m_grid.Hierarchy.Children.Count).ToString()); MyGuiControlLabel lightCount = new MyGuiControlLabel(text: new StringBuilder().Clear().AppendStringBuilder(MyTexts.Get(MySpaceTexts.TerminalTab_Info_Lights)).AppendInt32(lightCounter).ToString()); MyGuiControlLabel reflectorCount = new MyGuiControlLabel(text: new StringBuilder().AppendStringBuilder(MyTexts.Get(MySpaceTexts.TerminalTab_Info_Reflectors)).AppendInt32(m_grid.GridSystems.ReflectorLightSystem.ReflectorCount).ToString()); //MyGuiControlLabel wheelCount = new MyGuiControlLabel(text: new StringBuilder().AppendStringBuilder(MyTexts.Get(MySpaceTexts.TerminalTab_Info_Rotors)).AppendInt32(m_grid.WheelSystem.WheelCount)); MyGuiControlLabel gravityCount = new MyGuiControlLabel(text: new StringBuilder().AppendStringBuilder(MyTexts.Get(MySpaceTexts.TerminalTab_Info_GravGens)).AppendInt32(gravityCounter).ToString()); MyGuiControlLabel massCount = new MyGuiControlLabel(text: new StringBuilder().AppendStringBuilder(MyTexts.Get(MySpaceTexts.TerminalTab_Info_VirtualMass)).AppendInt32(massCounter).ToString()); MyGuiControlLabel conveyorCount = new MyGuiControlLabel(text: new StringBuilder().AppendStringBuilder(MyTexts.Get(MySpaceTexts.TerminalTab_Info_Conveyors)).AppendInt32(conveyorCounter).ToString()); var mainCockpit = m_grid.MainCockpit as MyShipController; MyCharacter pilot = null; if (mainCockpit != null) { pilot = mainCockpit.Pilot; } MyGuiControlLabel gridMass = new MyGuiControlLabel(text: new StringBuilder().AppendStringBuilder(MyTexts.Get(MySpaceTexts.TerminalTab_Info_GridMass)).AppendInt32(m_grid.GetCurrentMass(pilot)).ToString()); list.InitControls(new MyGuiControlBase[] { cubeCount, blockCount, conveyorCount, thrustCountLabel, lightCount, reflectorCount, gravityCount, massCount, polygonCount, gridMass }); }
public virtual void OnAddedToGroup(MyGridLogicalGroupData group) { Debug.Assert(group.TerminalSystem != null, "Terminal system is null!"); TerminalSystem = group.TerminalSystem; ResourceDistributor = group.ResourceDistributor; WeaponSystem = group.WeaponSystem; m_cubeGrid.OnBlockAdded += ResourceDistributor.CubeGrid_OnBlockAddedOrRemoved; m_cubeGrid.OnBlockRemoved += ResourceDistributor.CubeGrid_OnBlockAddedOrRemoved; var gridThrustComponent = CubeGrid.Components.Get <MyEntityThrustComponent>(); if (gridThrustComponent != null) { ResourceDistributor.AddSink(gridThrustComponent.ResourceSink); } ResourceDistributor.AddSink(GyroSystem.ResourceSink); ResourceDistributor.AddSink(ConveyorSystem.ResourceSink); foreach (var g in m_cubeGrid.BlockGroups) { TerminalSystem.AddUpdateGroup(g); } TerminalSystem.GroupAdded += m_terminalSystem_GroupAdded; TerminalSystem.GroupRemoved += m_terminalSystem_GroupRemoved; foreach (var block in m_cubeGrid.GetBlocks()) { if (block.FatBlock == null) { continue; } if (!block.FatBlock.MarkedForClose) { var functionalBlock = block.FatBlock as MyTerminalBlock; if (functionalBlock != null) { TerminalSystem.Add(functionalBlock); } var producer = block.FatBlock.Components.Get <MyResourceSourceComponent>(); if (producer != null) { ResourceDistributor.AddSource(producer); } var consumer = block.FatBlock.Components.Get <MyResourceSinkComponent>(); if (consumer != null) { ResourceDistributor.AddSink(consumer); } var socketOwner = block.FatBlock as IMyRechargeSocketOwner; if (socketOwner != null) { socketOwner.RechargeSocket.ResourceDistributor = group.ResourceDistributor; } var weapon = block.FatBlock as IMyGunObject <MyDeviceBase>; if (weapon != null) { WeaponSystem.Register(weapon); } } } }
private void OnGridSplit(MyCubeGrid original, MyCubeGrid newGrid) { Logging.Instance.WriteLine(string.Format("WARNING Split detected: {0} - {1} ({2})", original.EntityId, newGrid.EntityId, newGrid.GetBlocks().Count)); ((IMyCubeGrid)original).Physics.LinearVelocity = Vector3.Zero; ((IMyCubeGrid)original).Physics.AngularVelocity = Vector3.Zero; //original.Physics.Enabled = false; //AddPhysicless((IMyCubeGrid)original); ((IMyCubeGrid)newGrid).Physics.LinearVelocity = Vector3.Zero; ((IMyCubeGrid)newGrid).Physics.AngularVelocity = Vector3.Zero; ((IMyCubeGrid)newGrid).Physics.LinearDamping = 100.0f; ((IMyCubeGrid)newGrid).Physics.AngularDamping = 100.0f; //newGrid.Physics.Enabled = false; AddPhysicless((IMyCubeGrid)newGrid); newGrid.OnGridSplit += OnGridSplit; }
public void CutGroup(MyCubeGrid grid, GridLinkTypeEnum groupType) { if (grid == null) return; CopyGroup(grid, groupType); if (MyFakes.ENABLE_COPY_GROUP) { var group = MyCubeGridGroups.Static.GetGroups(groupType).GetGroupNodes(grid); foreach (var node in group) { foreach (var block in node.GetBlocks()) { block.RemoveAuthorship(); var cockpit = block.FatBlock as MyCockpit; if (cockpit != null && cockpit.Pilot != null) cockpit.Use(); } node.SyncObject.SendCloseRequest(); } } else { foreach (var block in grid.GetBlocks()) { block.RemoveAuthorship(); var cockpit = block.FatBlock as MyCockpit; if (cockpit != null && cockpit.Pilot != null) cockpit.Use(); } grid.SyncObject.SendCloseRequest(); } }
public static bool Recharge(MyGroups <MyCubeGrid, MyGridPhysicalGroupData> .Group group, string blockpairName, float fillPercentage, CommandContext Context) { int changedBlocks = 0; int changedGrids = 0; foreach (MyGroups <MyCubeGrid, MyGridPhysicalGroupData> .Node groupNodes in group.Nodes) { MyCubeGrid grid = groupNodes.NodeData; bool gridChanged = false; HashSet <MySlimBlock> blocks = grid.GetBlocks(); foreach (MySlimBlock block in blocks) { MyCubeBlock cubeBlock = block.FatBlock; if (cubeBlock != null) { if (blockpairName == "battery" && cubeBlock is MyBatteryBlock battery) { battery.CurrentStoredPower = battery.MaxStoredPower * fillPercentage; changedBlocks++; gridChanged = true; } if (blockpairName == "jumpdrive" && cubeBlock is MyJumpDrive jumpDrive) { jumpDrive.CurrentStoredPower = jumpDrive.BlockDefinition.PowerNeededForJump * fillPercentage; changedBlocks++; gridChanged = true; } if ((blockpairName == "o2tank" || blockpairName == "tank") && cubeBlock is MyGasTank o2tank && o2tank.BlockDefinition.StoredGasId == OXYGEN_DEFINITION) { o2tank.ChangeFillRatioAmount(fillPercentage); changedBlocks++; gridChanged = true; } if ((blockpairName == "h2tank" || blockpairName == "tank") && cubeBlock is MyGasTank h2tank && h2tank.BlockDefinition.StoredGasId == HYDROGEN_DEFINITION) { h2tank.ChangeFillRatioAmount(fillPercentage); changedBlocks++; gridChanged = true; } } } if (gridChanged) { changedGrids++; } } Context.Respond(changedBlocks + " blocks on " + changedGrids + " grids recharged to " + (fillPercentage * 100).ToString("0.0") + "%!"); return(true); }
public bool Disconnect(MyCubeGrid grid, MySlimBlock testBlock = null, bool testDisconnect = false) { ProfilerShort.Begin("Collect+IsInVoxels"); m_largestGroupWithPhysics = default(Group); m_groups.Clear(); m_sortedBlocks.Clear(); m_disconnectHelper.Clear(); foreach (var block in grid.GetBlocks()) { if (block == testBlock) continue; m_disconnectHelper.Add(block); } ProfilerShort.End(); ProfilerShort.Begin("GroupBy"); while (m_disconnectHelper.Count > 0) { Group group = default(Group); group.FirstBlockIndex = m_sortedBlocks.Count; AddNeighbours(m_disconnectHelper.FirstElement(), out group.IsValid, testBlock); group.BlockCount = m_sortedBlocks.Count - group.FirstBlockIndex; if (group.IsValid && group.BlockCount > m_largestGroupWithPhysics.BlockCount) { if (m_largestGroupWithPhysics.BlockCount > 0) // Is valid { // order matters, insert in correct place int i = 0; for (i = 0; i < m_groups.Count; i++) { if (m_groups[i].FirstBlockIndex > m_largestGroupWithPhysics.FirstBlockIndex) { m_groups.Insert(i, m_largestGroupWithPhysics); break; } } if (i == m_groups.Count) { m_groups.Add(m_largestGroupWithPhysics); } } m_largestGroupWithPhysics = group; } else { m_groups.Add(group); } } ProfilerShort.End(); ProfilerShort.Begin("RemoveLargestGroup"); m_sortedBlocks.RemoveRange(m_largestGroupWithPhysics.FirstBlockIndex, m_largestGroupWithPhysics.BlockCount); for (int i = 0; i < m_groups.Count; i++) { var g = m_groups[i]; if (g.FirstBlockIndex > m_largestGroupWithPhysics.FirstBlockIndex) { g.FirstBlockIndex -= m_largestGroupWithPhysics.BlockCount; m_groups[i] = g; } } ProfilerShort.End(); ProfilerShort.Begin("CreateSplits"); if (m_groups.Count > 0) { if (testDisconnect) { m_groups.Clear(); m_sortedBlocks.Clear(); m_disconnectHelper.Clear(); return true; } MyCubeGrid.CreateSplits(grid, m_sortedBlocks, m_groups); } else { if (!MySession.Static.Settings.StationVoxelSupport) { if (grid.IsStatic) grid.TestDynamic = MyCubeGrid.MyTestDynamicReason.GridSplit; } } ProfilerShort.End(); m_groups.Clear(); m_sortedBlocks.Clear(); m_disconnectHelper.Clear(); return false; }
public bool Disconnect(MyCubeGrid grid, MySlimBlock testBlock = null, bool testDisconnect = false) { ProfilerShort.Begin("Collect+IsInVoxels"); m_largestGroupWithPhysics = default(Group); m_groups.Clear(); m_sortedBlocks.Clear(); m_disconnectHelper.Clear(); foreach (var block in grid.GetBlocks()) { if (block == testBlock) { continue; } m_disconnectHelper.Add(block); } ProfilerShort.End(); ProfilerShort.Begin("GroupBy"); while (m_disconnectHelper.Count > 0) { Group group = default(Group); group.FirstBlockIndex = m_sortedBlocks.Count; AddNeighbours(m_disconnectHelper.FirstElement(), out group.IsValid, testBlock); group.BlockCount = m_sortedBlocks.Count - group.FirstBlockIndex; if (group.IsValid && group.BlockCount > m_largestGroupWithPhysics.BlockCount) { if (m_largestGroupWithPhysics.BlockCount > 0) // Is valid { // order matters, insert in correct place int i = 0; for (i = 0; i < m_groups.Count; i++) { if (m_groups[i].FirstBlockIndex > m_largestGroupWithPhysics.FirstBlockIndex) { m_groups.Insert(i, m_largestGroupWithPhysics); break; } } if (i == m_groups.Count) { m_groups.Add(m_largestGroupWithPhysics); } } m_largestGroupWithPhysics = group; } else { m_groups.Add(group); } } ProfilerShort.End(); ProfilerShort.Begin("RemoveLargestGroup"); m_sortedBlocks.RemoveRange(m_largestGroupWithPhysics.FirstBlockIndex, m_largestGroupWithPhysics.BlockCount); for (int i = 0; i < m_groups.Count; i++) { var g = m_groups[i]; if (g.FirstBlockIndex > m_largestGroupWithPhysics.FirstBlockIndex) { g.FirstBlockIndex -= m_largestGroupWithPhysics.BlockCount; m_groups[i] = g; } } ProfilerShort.End(); ProfilerShort.Begin("CreateSplits"); if (m_groups.Count > 0) { if (testDisconnect) { m_groups.Clear(); m_sortedBlocks.Clear(); m_disconnectHelper.Clear(); ProfilerShort.End(); return(true); } MyCubeGrid.CreateSplits(grid, m_sortedBlocks, m_groups); } else { if (!MySession.Static.Settings.StationVoxelSupport) { if (grid.IsStatic) { grid.TestDynamic = MyCubeGrid.MyTestDynamicReason.GridSplit; } } } ProfilerShort.End(); m_groups.Clear(); m_sortedBlocks.Clear(); m_disconnectHelper.Clear(); return(false); }
public void CutGrid(MyCubeGrid grid) { if (grid == null) return; CopyGrid(grid); foreach (var block in grid.GetBlocks()) { var cockpit = block.FatBlock as MyCockpit; if (cockpit != null && cockpit.Pilot != null) cockpit.Use(); } grid.SyncObject.SendCloseRequest(); Deactivate(); }
public void Collect(MyCubeGrid grid, MyVoxelSegmentation segmenter, MyVoxelSegmentationType segmentationType, IDictionary<Vector3I, HkMassElement> massResults) { foreach (var block in grid.GetBlocks()) { if (block.FatBlock is MyCompoundCubeBlock) { CollectCompoundBlock((MyCompoundCubeBlock)block.FatBlock, massResults); Debug.Assert(IsValid(), "Overlapping shapes detected, block shapes cannot overlap!"); } else { CollectBlock(block, block.BlockDefinition.PhysicsOption, massResults); Debug.Assert(IsValid(), "Overlapping shapes detected, block shapes cannot overlap!"); } } AddSegmentedParts(grid.GridSize, segmenter, segmentationType); m_tmpCubes.Clear(); Debug.Assert(Shapes.Count > 0, "Shape count cannot be zero"); Debug.Assert(massResults == null || massResults.Count > 0, "No mass elements, something is wrong!"); }
public override void Update() { //NEED TO PULL THIS INFO FROM WPF LIST string NPCName = "Space Pirates"; //Run first checks! // Grap space pirate entities id (im assuming its all the same for each world?) if (!RunOnce) { PirateEntityID = GetActiveNPCSIds(NPCName); RunOnce = true; } if (PluginTickCounter >= MaxTickCounter && Config.PluginEnabled) { //Get active NPC Grids and store to wacthlist Parallel.ForEach(MyCubeGridGroups.Static.Mechanical.Groups, group => { foreach (MyGroups <MyCubeGrid, MyGridMechanicalGroupData> .Node groupNodes in group.Nodes) { MyCubeGrid cubeGrid = groupNodes.NodeData; Tracker TGrid = new Tracker(); TGrid.GridEntityID = cubeGrid.EntityId; TGrid.GridDisplayName = cubeGrid.DisplayName; TGrid.Grid = cubeGrid; if (cubeGrid == null || cubeGrid.Physics == null) { continue; } if (TrackedGrids.Any(item => item.GridEntityID == TGrid.GridEntityID)) //Checkwatchlist { continue; } //Grab all blocks built by space pirates. HashSet <MySlimBlock> Blocks = cubeGrid.FindBlocksBuiltByID(PirateEntityID); HashSet <MySlimBlock> NobodyBlocks = cubeGrid.FindBlocksBuiltByID(0); //Entity ID is ownedby Nobody //Combine these hash sets Blocks.UnionWith(NobodyBlocks); if (Blocks.Count != 0 && cubeGrid.BlocksCount >= Config.BlockThreshold) //Checks to see if the grid is greater than 3 blocks. Debris Limit { //Blocks build by space pirates means the grid still has pcu of space pirate therefore must still be an npc grid. if (cubeGrid.EntityId != null) //Check to make sure its not null and not in the list { //Alert logs and add it to the collection of tracked grids Log.Info("Grid: " + cubeGrid.DisplayName + " Is being tracked with EntityID of (" + cubeGrid.EntityId + ")"); TrackedGrids.Add(TGrid); } } /* * Log.Info(cubeGrid.DisplayName + " Has large owners:"); * foreach (long BigOwnerID in cubeGrid.BigOwners) * { * Log.Info(BigOwnerID); * //Log.Info(BigOwnerID); * if(BigOwnerID == PirateEntityID) * { * * //Add this cubegrid to tracked entities * //Log.Info(cubeGrid.EntityId + " : " + TrackedGrids.Count); * * if (cubeGrid.EntityId != null && !TrackedGrids.Contains(cubeGrid.EntityId)) * { * Log.Info("Grid: " + cubeGrid.DisplayName + " Is being tracked with EntityID of ("+cubeGrid.EntityId+")"); * TrackedGrids.Add(cubeGrid.EntityId); * } * } * } * * * Log.Info(cubeGrid.DisplayName + " Has small owners:"); * foreach (long SmallOwnerID in cubeGrid.SmallOwners) * { * Log.Info(SmallOwnerID); * //cubeGrid.owner * } */ } }); PluginTickCounter = 0; //Check owner/grid changes to see if player captured npc grids Parallel.ForEach(TrackedGrids, grid => { IMyCubeGrid cubeGrid = null; try { foreach (IMyCubeGrid gridentity in MyEntities.GetEntities().OfType <IMyCubeGrid>().Where(g => g.EntityId == grid.GridEntityID)) { //Get Cubegrid so we can transfer all blocks built by! cubeGrid = gridentity; } if (cubeGrid == null) { Log.Info("Entity was removed from the game. Removing from watchlist!"); TrackedGrids.Remove(grid); return; } } catch (Exception e) { Log.Warn("Entity cannot be converted to IMyCubeGrid! Removing entity from tracked list!"); TrackedGrids.Remove(grid); Log.Warn(e); return; } var gts = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(cubeGrid); List <Sandbox.ModAPI.Ingame.IMyShipController> blockList = new List <Sandbox.ModAPI.Ingame.IMyShipController>(); gts.GetBlocksOfType <Sandbox.ModAPI.Ingame.IMyShipController>(blockList); //Message to alert players when they start taking the grid? //Example: This grid requires your to take all control blocks //Undoo this comment to debug tracked grids! //Log.Info("Checking grid changes on: " + cubeGrid.DisplayName); if (blockList.Count == 0) { //Log.Info("Grid doesnt have any control blocks!"); return; } bool AllControlersCaptured = true; long PlayerWhoCapturedNPC = 0; foreach (IMyShipController controler in blockList) { if (controler.OwnerId == PirateEntityID) { AllControlersCaptured = false; continue; } //Basically grab last owner and transfer it all to him. (I dont really care about other faction mates right now. They can transfer between them) PlayerWhoCapturedNPC = controler.OwnerId; } //Transfer all blocks to last block owner if (AllControlersCaptured && PlayerWhoCapturedNPC != 0) { Log.Info("Player " + PlayerWhoCapturedNPC + " captured all the control blocks!"); MyCubeGrid Cubegrid = grid.Grid; if (Cubegrid != null) { Log.Info("Transfering " + Cubegrid.DisplayName + " to new player!"); MyIdentity NewPlayer = MySession.Static.Players.TryGetIdentity(PlayerWhoCapturedNPC); MyBlockLimits blockLimits = NewPlayer.BlockLimits; ulong UserSteamID = MyModAPIHelper.MyMultiplayer.Static.Players.TryGetSteamId(PlayerWhoCapturedNPC); //Transfer Blocks! List <long> authors = new List <long>(); foreach (MySlimBlock block in Cubegrid.GetBlocks()) { if (block.BuiltBy == 0 || block.BuiltBy == PirateEntityID) { block.TransferAuthorshipClient(PlayerWhoCapturedNPC); block.AddAuthorship(); if (!authors.Contains(block.BuiltBy)) { authors.Add(block.BuiltBy); } } } foreach (long author in authors) { MyMultiplayer.RaiseEvent(Cubegrid, x => new Action <long, long>(x.TransferBlocksBuiltByID), author, PlayerWhoCapturedNPC, new EndpointId()); } int CurrentPcu = blockLimits.PCUBuilt; int MaxPcu = blockLimits.PCU + CurrentPcu; var sb = new StringBuilder(); sb.AppendLine(""); sb.AppendLine("Current PCU: " + CurrentPcu + "/" + MaxPcu); if (CurrentPcu / MaxPcu >= 1.0) { /* * If they dont have room, Add list to secondary watch list on removing grid * This watch list will be saved to file so if server crashes we can still track grid and remove it when it re-starts * * * * * */ sb.AppendLine("Your are over your PCU Limits! This grid will be deleted on player log-off or server restart!"); sb.AppendLine("If you manage to get under your PCU limits before these times, the grid wont be deleted."); Tracker TGrid = new Tracker(); TGrid.GridEntityID = grid.GridEntityID; TGrid.PlayerEntityID = NewPlayer; TGrid.GridDisplayName = Cubegrid.DisplayName; TGrid.PlayerName = NewPlayer.DisplayName; TGrid.Grid = Cubegrid; DeleteList.Add(TGrid); Debug("Ship was added to delete watcher"); } //Log.Info(NewPlayer.DisplayName); //Will this work with entity id? ModCommunication.SendMessageTo(new DialogMessage("NPC-Takeover", $"All control blocks captured!", "Transfering authorship on " + Cubegrid.DisplayName + " to you! " + sb), UserSteamID); //ModCommunication.SendMessageTo(new TorchChatMessage("NPC-Takeover", $"All control blocks captured!", "Transfering authorship on " + Cubegrid.DisplayName + " to you!"), UserSteamID); //MyAPIGateway.Utilities.SendMessage(76561198045096439, "PrivateTxt", "Target is Space Pirate"); //Cubegrid.TransferBlocksBuiltByID(PirateEntityID, PlayerWhoCapturedNPC); //MyCubeGridGroups.Static.UpdateDynamicState(Cubegrid); Debug("Removed grid from watchlist"); TrackedGrids.Remove(grid); return; } } }); //Check deleted grids list if player is offline or under pcu limit Parallel.ForEach(DeleteList, grid => { IMyCubeGrid cubeGrid = null; try { foreach (IMyCubeGrid gridentity in MyEntities.GetEntities().OfType <IMyCubeGrid>().Where(g => g.EntityId == grid.GridEntityID)) { //Get Cubegrid so we can transfer all blocks built by! cubeGrid = gridentity; } if (cubeGrid == null) { Log.Info("Entity was removed from the game. Removing from watchlist!"); DeleteList.Remove(grid); return; } } catch (Exception e) { Log.Warn("Entity cannot be converted to IMyCubeGrid! Removing entity from tracked list!"); DeleteList.Remove(grid); Log.Warn(e); return; } //Get player offline bool PlayerIsOffline = true; foreach (MyPlayer Player in MySession.Static.Players.GetOnlinePlayers()) { //Log.Info("Player " + Player.DisplayName + " is online!"); if (Player.Identity.IdentityId == grid.PlayerEntityID.IdentityId) { //Player is online PlayerIsOffline = false; } } if (PlayerIsOffline) { //Debuggin if players report their grid got deleted Log.Info("Grid owner: " + grid.PlayerName + " is offline. Deleting grid " + grid.GridDisplayName + " (" + grid.GridEntityID + ")"); //Remove entitiy from game and delete from list MyEntities.Close(cubeGrid as MyEntity); DeleteList.Remove(grid); } bool GridFitsWithinPlayerlimits = false; try { MyIdentity NewPlayer = MySession.Static.Players.TryGetIdentity(grid.PlayerEntityID.IdentityId); MyBlockLimits blockLimits = NewPlayer.BlockLimits; int CurrentPcu = blockLimits.PCUBuilt; int MaxPcu = blockLimits.PCU + CurrentPcu; //Get Current PCU of grid? int GridPCU = grid.Grid.BlocksPCU; if (MaxPcu - CurrentPcu >= GridPCU) { //Grid fits withing player PCU! Remove from watchlist! Log.Info("Grid " + grid.GridDisplayName + " has been removed from watchlist. Player cleared PCU"); //Maybe alert player? DeleteList.Remove(grid); } } catch (Exception e) { //Failure to get player entitiy or Cubegrid class Log.Warn(e); } }); //SaveList to file } PluginTickCounter++; }
public void Disconnect(MyCubeGrid grid) { ProfilerShort.Begin("Collect+IsInVoxels"); m_largestGroupWithPhysics = default(Group); m_groups.Clear(); m_sortedBlocks.Clear(); m_disconnectHelper.Clear(); foreach (var block in grid.GetBlocks()) { m_disconnectHelper.Add(block); } ProfilerShort.End(); ProfilerShort.Begin("GroupBy"); while (m_disconnectHelper.Count > 0) { Group group = default(Group); group.FirstBlockIndex = m_sortedBlocks.Count; AddNeighbours(m_disconnectHelper.FirstElement(), out group.IsValid); group.BlockCount = m_sortedBlocks.Count - group.FirstBlockIndex; if (group.IsValid && group.BlockCount > m_largestGroupWithPhysics.BlockCount) { if (m_largestGroupWithPhysics.BlockCount > 0) // Is valid { // order matters, insert in correct place int i = 0; for (i = 0; i < m_groups.Count; i++) { if (m_groups[i].FirstBlockIndex > m_largestGroupWithPhysics.FirstBlockIndex) { m_groups.Insert(i, m_largestGroupWithPhysics); break; } } if (i == m_groups.Count) { m_groups.Add(m_largestGroupWithPhysics); } } m_largestGroupWithPhysics = group; } else { m_groups.Add(group); } } ProfilerShort.End(); ProfilerShort.Begin("RemoveLargestGroup"); m_sortedBlocks.RemoveRange(m_largestGroupWithPhysics.FirstBlockIndex, m_largestGroupWithPhysics.BlockCount); for (int i = 0; i < m_groups.Count; i++) { var g = m_groups[i]; if (g.FirstBlockIndex > m_largestGroupWithPhysics.FirstBlockIndex) { g.FirstBlockIndex -= m_largestGroupWithPhysics.BlockCount; m_groups[i] = g; } } ProfilerShort.End(); ProfilerShort.Begin("CreateSplits"); if (m_groups.Count > 0) MyCubeGrid.CreateSplits(grid, m_sortedBlocks, m_groups); ProfilerShort.End(); m_groups.Clear(); m_sortedBlocks.Clear(); m_disconnectHelper.Clear(); }
private void OnGridSplit(MyCubeGrid original, MyCubeGrid newGrid) { Logging.Instance.WriteLine(string.Format("[Deconstruction] Warning - Split detected: {0} - {1} ({2})", original.EntityId, newGrid.EntityId, newGrid.GetBlocks().Count), 1); ((IMyCubeGrid)original).Physics.LinearVelocity = Vector3.Zero; ((IMyCubeGrid)original).Physics.AngularVelocity = Vector3.Zero; ((IMyCubeGrid)newGrid).Physics.LinearVelocity = Vector3.Zero; ((IMyCubeGrid)newGrid).Physics.AngularVelocity = Vector3.Zero; ((IMyCubeGrid)newGrid).Physics.LinearDamping = 100.0f; ((IMyCubeGrid)newGrid).Physics.AngularDamping = 100.0f; AddPhysicless((IMyCubeGrid)newGrid); newGrid.OnGridSplit += OnGridSplit; }
private static void FillContainer() { if (count == 16) { SendMessageTemp("PvP Event", "Event is over", Color.Red); bTimer.Close(); return; } count++; MyCubeGrid TechGrid = null; ConcurrentBag <MyGroups <MyCubeGrid, MyGridPhysicalGroupData> .Group> groups = GridFinder.FindGridGroup(gridName); Parallel.ForEach(MyCubeGridGroups.Static.Physical.Groups, group => { foreach (MyGroups <MyCubeGrid, MyGridPhysicalGroupData> .Node groupNodes in group.Nodes) { MyCubeGrid grid = groupNodes.NodeData; //does the grid have the same name as the input bool found = false; foreach (VRage.Game.ModAPI.IMySlimBlock block in grid.GetBlocks()) { if (block != null && block.BlockDefinition.Id.SubtypeName.Contains("PrizeboxD") && grid.DisplayName.Equals(gridName)) { TechGrid = grid; found = true; } } if (!found) { continue; } break; } }); if (TechGrid != null) { Sandbox.ModAPI.IMyTerminalBlock container = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid(TechGrid).GetBlockWithName("Tech Container") as IMyTerminalBlock; Random random = new Random(); int num = random.Next(100); if (num <= 1) { if (!billion) { container.GetInventory().AddItems(VRage.MyFixedPoint.DeserializeStringSafe("50000000"), new MyObjectBuilder_PhysicalObject() { SubtypeName = "SpaceCredit" }); SendMessageTemp("PvP " + gridName, "50 Million SC.", Color.Red); billion = true; } else { container.GetInventory().AddItems(VRage.MyFixedPoint.DeserializeStringSafe("10000000"), new MyObjectBuilder_PhysicalObject() { SubtypeName = "SpaceCredit" }); SendMessageTemp("PvP " + gridName, "10 Million SC.", Color.Red); return; } return; } if (num <= 50) { container.GetInventory().AddItems(VRage.MyFixedPoint.DeserializeStringSafe("10000000"), new MyObjectBuilder_PhysicalObject() { SubtypeName = "SpaceCredit" }); SendMessageTemp("PvP " + gridName, "10 Million SC.", Color.Red); return; } else { num = random.Next(100); if (num <= 10) { int num2 = random.Next(100); if (num2 <= 10) { container.GetInventory().AddItems(VRage.MyFixedPoint.DeserializeStringSafe("50"), new MyObjectBuilder_Component() { SubtypeName = "Tech8x" }); SendMessageTemp("PvP " + gridName, "50 Exotic", Color.Red); } else { container.GetInventory().AddItems(VRage.MyFixedPoint.DeserializeStringSafe("10"), new MyObjectBuilder_Component() { SubtypeName = "Tech8x" }); SendMessageTemp("PvP " + gridName, "10 Exotic", Color.Red); } return; } if (num <= 30) { int num2 = random.Next(100); if (num2 <= 40) { container.GetInventory().AddItems(VRage.MyFixedPoint.DeserializeStringSafe("75"), new MyObjectBuilder_Component() { SubtypeName = "Tech4x" }); SendMessageTemp("PvP " + gridName, "75 Rare", Color.Red); } else { container.GetInventory().AddItems(VRage.MyFixedPoint.DeserializeStringSafe("25"), new MyObjectBuilder_Component() { SubtypeName = "Tech4x" }); SendMessageTemp("PvP " + gridName, "25 Rare", Color.Red); } return; } if (num <= 100) { int num2 = random.Next(100); if (num2 <= 50) { container.GetInventory().AddItems(VRage.MyFixedPoint.DeserializeStringSafe("100"), new MyObjectBuilder_Component() { SubtypeName = "Tech2x" }); SendMessageTemp("PvP " + gridName, "100 Common", Color.Red); } else { container.GetInventory().AddItems(VRage.MyFixedPoint.DeserializeStringSafe("50"), new MyObjectBuilder_Component() { SubtypeName = "Tech2x" }); SendMessageTemp("PvP " + gridName, "50 Common", Color.Red); } return; } } } }
public static int CheckGroup(out MyCubeGrid biggestGrid, MyGroups <MyCubeGrid, MyGridPhysicalGroupData> .Group group) { biggestGrid = null; try { double num = 0.0; Dictionary <MyCubeGrid, List <TopPart> > connectionMap = new Dictionary <MyCubeGrid, List <TopPart> >(); foreach (MyGroups <MyCubeGrid, MyGridPhysicalGroupData> .Node groupNodes in group.Nodes) { MyCubeGrid cubeGrid = groupNodes.NodeData; if (cubeGrid == null) { continue; } if (cubeGrid.Physics == null) { continue; } double volume = cubeGrid.PositionComp.WorldAABB.Size.Volume; if (volume > num) { num = volume; biggestGrid = cubeGrid; } HashSet <MySlimBlock> blocks = new HashSet <MySlimBlock>(cubeGrid.GetBlocks()); foreach (MySlimBlock block in blocks) { if (block == null || block.CubeGrid == null || block.IsDestroyed) { continue; } MyCubeBlock cubeBlock = block.FatBlock; if (cubeBlock == null) { continue; } if (cubeBlock is MyMotorStator rotor) { if (MyMechanicalConnectionBlockBasePatch.IsIrrelevantType(rotor)) { continue; } MyCubeGrid top = rotor.TopGrid; MyCubeGrid bottom = cubeGrid; List <TopPart> connections; if (top != null && !connectionMap.ContainsKey(top)) { connectionMap.Add(top, new List <TopPart>()); } if (!connectionMap.ContainsKey(bottom)) { connections = new List <TopPart>(); connectionMap.Add(bottom, connections); } else { connections = connectionMap[bottom]; } connections.Add(new TopPart(top)); } } } int maxCount = 0; foreach (MyCubeGrid grid in new List <MyCubeGrid>(connectionMap.Keys)) { maxCount = Math.Max(maxCount, GetMaxTiefe(grid, connectionMap)); } return(maxCount); } catch (Exception e) { Log.Error(e, "Error while checking grid!"); return(0); } }
public bool Simulate(float deltaTime) { if (m_grid.Physics == null) { return(false); } m_frameCounter++; if (m_simulationDataReady) { SwapSimulatedDatas(); m_simulationDataReady = false; m_simulationDataPrepared = true; return(true); } // Change detected by changing block count if (m_grid.GetBlocks().Count == m_finishedData.BlockCount && !ForceRecalc && m_simulationDataPrepared && !m_needsRecalc) { return(false); } m_needsRecalc = true; ForceRecalc = false; // m_selectedGrid = m_grid; if (m_simulationInProgress) { return(false); } m_simulationInProgress = true; //Loading blocks must be synchronized, we dont support multithreaded blocks management (add, remove) LoadBlocks(m_simulatedData); if (!Multithreaded) { m_needsRecalc = false; using (Stats.Timing.Measure("SI TOTAL - FindAndCaculateAdvancedStatic", VRage.Stats.MyStatTypeEnum.Sum | VRage.Stats.MyStatTypeEnum.DontDisappearFlag)) { FindAndCaculateFromAdvancedStatic(m_simulatedData); } SwapSimulatedDatas(); m_simulationInProgress = false; m_simulationDataPrepared = true; } else { m_needsRecalc = false; Parallel.Start(() => { FindAndCaculateFromAdvancedStatic(m_simulatedData); }, () => { m_simulationInProgress = false; m_simulationDataReady = true; }); } return(true); }
public override bool DebugDraw() { if (MyDebugDrawSettings.DEBUG_DRAW_GRID_NAMES || MyDebugDrawSettings.DEBUG_DRAW_GRID_CONTROL) { string text = ""; var color = Color.White; if (MyDebugDrawSettings.DEBUG_DRAW_GRID_NAMES) { text += m_cubeGrid.ToString() + " "; } if (MyDebugDrawSettings.DEBUG_DRAW_GRID_CONTROL) { var controllingPlayer = Sync.Players.GetControllingPlayer(m_cubeGrid); if (controllingPlayer != null) { text += "Controlled by: " + controllingPlayer.DisplayName; color = Color.LightGreen; } } MyRenderProxy.DebugDrawText3D(m_cubeGrid.PositionComp.WorldAABB.Center, text, color, 0.7f, false, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER); } MyRenderComponentCubeGrid gridRender = m_cubeGrid.Render; if (MyDebugDrawSettings.DEBUG_DRAW_BLOCK_GROUPS) { var tpos = m_cubeGrid.PositionComp.WorldMatrix.Translation; foreach (var group in m_cubeGrid.BlockGroups) { MyRenderProxy.DebugDrawText3D(tpos, group.Name.ToString(), Color.Red, 1, false); tpos += m_cubeGrid.PositionComp.WorldMatrix.Right * group.Name.Length * 0.1f; } } if (MyDebugDrawSettings.DEBUG_DRAW_GRID_DIRTY_BLOCKS) { foreach (var b in m_dirtyBlocks) { var color = m_cubeGrid.GetCubeBlock(b.Key) != null?Color.Red.ToVector3() : Color.Yellow.ToVector3(); var m = Matrix.CreateScale(m_cubeGrid.GridSize) * Matrix.CreateTranslation(b.Key * m_cubeGrid.GridSize) * m_cubeGrid.WorldMatrix; MyRenderProxy.DebugDrawOBB(m, color, 0.15f, false, true); } } // Bone debug draw if (MyDebugDrawSettings.DEBUG_DRAW_DISPLACED_BONES) { Vector3 cameraPos = (Vector3)MySector.MainCamera.Position; foreach (var bone in m_cubeGrid.Skeleton.Bones) { var bonePos = (bone.Key / (float)m_cubeGrid.Skeleton.BoneDensity) * gridRender.GridSize + bone.Value; bonePos -= new Vector3(gridRender.GridSize / m_cubeGrid.Skeleton.BoneDensity); Vector3 pos = Vector3.Transform(bonePos, (Matrix)m_cubeGrid.PositionComp.WorldMatrix); MyRenderProxy.DebugDrawSphere(pos, 0.05f, Color.Red.ToVector3(), 0.5f, false, true); if ((cameraPos - pos).LengthSquared() < 200.0f) { MyRenderProxy.DebugDrawText3D(pos, bone.Key.ToString(), Color.Red, 0.4f, false); } } } if (MyDebugDrawSettings.DEBUG_DRAW_STRUCTURAL_INTEGRITY && m_cubeGrid.StructuralIntegrity != null) { m_cubeGrid.StructuralIntegrity.DebugDraw(); } if (MyDebugDrawSettings.DEBUG_DRAW_CUBES) { foreach (var cubeBlock in m_cubeGrid.CubeBlocks) { var cb = cubeBlock.FatBlock; if (cb == null) { continue; } cb.DebugDraw(); } } m_cubeGrid.GridSystems.DebugDraw(); if (MyDebugDrawSettings.DEBUG_DRAW_GRID_TERMINAL_SYSTEMS) { /* if (grid.OnBlockAdded != null) * { * MyRenderProxy.DebugDrawText3D(Entity.PositionComp.WorldMatrix.Translation + new Vector3(0.0f, 0.0f, 0.5f), grid.OnBlockAdded.GetInvocationList().Count().ToString(), Color.NavajoWhite, 1.0f, false); * }*/ } if (MyFakes.ENABLE_TRASH_REMOVAL && MyDebugDrawSettings.DEBUG_DRAW_TRASH_REMOVAL) { Color color = m_cubeGrid.IsTrash() ? Color.Red : Color.Green; float sphereRadius = m_cubeGrid.PositionComp.LocalAABB.HalfExtents.AbsMax(); MyRenderProxy.DebugDrawSphere(m_cubeGrid.Physics != null ? m_cubeGrid.Physics.CenterOfMassWorld : m_cubeGrid.PositionComp.WorldMatrix.Translation, sphereRadius, color, 1.0f, false); } if (MyDebugDrawSettings.DEBUG_DRAW_GRID_ORIGINS) { MyRenderProxy.DebugDrawAxis(m_cubeGrid.PositionComp.WorldMatrix, 1.0f, false); } if (MyDebugDrawSettings.ENABLE_DEBUG_DRAW && MyDebugDrawSettings.DEBUG_DRAW_MOUNT_POINTS_ALL) { foreach (MySlimBlock block in m_cubeGrid.GetBlocks()) { if ((m_cubeGrid.GridIntegerToWorld(block.Position) - MySector.MainCamera.Position).LengthSquared() < 200) { DebugDrawMountPoints(block); } } } foreach (var b in m_cubeGrid.GetBlocks()) { if (b.FatBlock is MyFracturedBlock) { MyRenderProxy.DebugDrawText3D(m_cubeGrid.GridIntegerToWorld(b.Position), "F", Color.Red, 1, false); } } return(base.DebugDraw()); }
// Creates prefab, but won't add into scene // WorldMatrix is the matrix of the first grid in the prefab. The others will be transformed to keep their relative positions private void CreateGridsFromPrefab(List <MyCubeGrid> results, string prefabName, MatrixD worldMatrix, bool spawnAtOrigin = false, bool ignoreMemoryLimits = true) { var prefabDefinition = MyDefinitionManager.Static.GetPrefabDefinition(prefabName); Debug.Assert(prefabDefinition != null, "Could not spawn prefab named " + prefabName); if (prefabDefinition == null) { return; } if (prefabDefinition.CubeGrids == null) { MyDefinitionManager.Static.ReloadPrefabsFromFile(prefabDefinition.PrefabPath); prefabDefinition = MyDefinitionManager.Static.GetPrefabDefinition(prefabName); } MyObjectBuilder_CubeGrid[] gridObs = prefabDefinition.CubeGrids; Debug.Assert(gridObs.Count() != 0); if (gridObs.Count() == 0) { return; } MyEntities.RemapObjectBuilderCollection(gridObs); MatrixD translateToOriginMatrix; if (spawnAtOrigin) { Vector3D translation = Vector3D.Zero; if (prefabDefinition.CubeGrids[0].PositionAndOrientation.HasValue) { translation = prefabDefinition.CubeGrids[0].PositionAndOrientation.Value.Position; } translateToOriginMatrix = MatrixD.CreateWorld(-translation, Vector3D.Forward, Vector3D.Up); } else { translateToOriginMatrix = MatrixD.CreateWorld(-prefabDefinition.BoundingSphere.Center, Vector3D.Forward, Vector3D.Up); } List <MyCubeGrid> gridsToMove = new List <MyCubeGrid>(); bool needMove = true; Vector3D moveVector = new Vector3D(); bool ignoreMemoryLimitsPrevious = MyEntities.IgnoreMemoryLimits; MyEntities.IgnoreMemoryLimits = ignoreMemoryLimits; for (int i = 0; i < gridObs.Count(); ++i) { MyEntity entity = MyEntities.CreateFromObjectBuilder(gridObs[i]); MyCubeGrid cubeGrid = entity as MyCubeGrid; Debug.Assert(cubeGrid != null, "Could not create grid prefab!"); if (cubeGrid != null) { MatrixD originalGridMatrix = gridObs[i].PositionAndOrientation.HasValue ? gridObs[i].PositionAndOrientation.Value.GetMatrix() : MatrixD.Identity; MatrixD newWorldMatrix; newWorldMatrix = MatrixD.Multiply(originalGridMatrix, MatrixD.Multiply(translateToOriginMatrix, worldMatrix)); Sandbox.Game.Gui.MyCestmirDebugInputComponent.AddDebugPoint(newWorldMatrix.Translation, Color.Red); if (cubeGrid.IsStatic) { Debug.Assert(Vector3.IsZero(newWorldMatrix.Forward - Vector3.Forward, 0.001f), "Creating a static grid with orientation that is not identity"); Debug.Assert(Vector3.IsZero(newWorldMatrix.Up - Vector3.Up, 0.001f), "Creating a static grid with orientation that is not identity"); Vector3 rounded = default(Vector3I); if (MyPerGameSettings.BuildingSettings.StaticGridAlignToCenter) { rounded = Vector3I.Round(newWorldMatrix.Translation / cubeGrid.GridSize) * cubeGrid.GridSize; } else { rounded = Vector3I.Round(newWorldMatrix.Translation / cubeGrid.GridSize + 0.5f) * cubeGrid.GridSize - 0.5f * cubeGrid.GridSize; } moveVector = new Vector3D(rounded - newWorldMatrix.Translation); newWorldMatrix.Translation = rounded; cubeGrid.WorldMatrix = newWorldMatrix; needMove = false; if (MyPerGameSettings.Destruction) { Debug.Assert(cubeGrid.Physics != null && cubeGrid.Physics.Shape != null); if (cubeGrid.Physics != null && cubeGrid.Physics.Shape != null) { cubeGrid.Physics.Shape.RecalculateConnectionsToWorld(cubeGrid.GetBlocks()); } } } else { newWorldMatrix.Translation += moveVector; cubeGrid.WorldMatrix = newWorldMatrix; if (needMove) { gridsToMove.Add(cubeGrid); } } //if some mods are missing prefab can have 0 blocks, //we don't want to process this grid if (cubeGrid.CubeBlocks.Count > 0) { results.Add(cubeGrid); } } } foreach (var grid in gridsToMove) { MatrixD wmatrix = grid.WorldMatrix; wmatrix.Translation += moveVector; } MyEntities.IgnoreMemoryLimits = ignoreMemoryLimitsPrevious; }
public void CutGroup(MyCubeGrid grid) { if (grid == null) return; CopyGroup(grid); if (MyFakes.ENABLE_COPY_GROUP) { var group = MyCubeGridGroups.Static.Logical.GetGroup(grid); foreach (var node in group.Nodes) { foreach (var block in node.NodeData.GetBlocks()) { var cockpit = block.FatBlock as MyCockpit; if (cockpit != null && cockpit.Pilot != null) cockpit.Use(); } node.NodeData.SyncObject.SendCloseRequest(); } } else { foreach (var block in grid.GetBlocks()) { var cockpit = block.FatBlock as MyCockpit; if (cockpit != null && cockpit.Pilot != null) cockpit.Use(); } grid.SyncObject.SendCloseRequest(); } Deactivate(); }
private void RecreateControls() { Debug.Assert(m_infoPage != null, "Terminal page is null"); if (m_infoPage == null) { return; } if (MyFakes.ENABLE_CENTER_OF_MASS) { var centerBtn = (MyGuiControlCheckbox)m_infoPage.Controls.GetControlByName("CenterBtn"); centerBtn.IsChecked = MyCubeGrid.ShowCenterOfMass; centerBtn.IsCheckedChanged = centerBtn_IsCheckedChanged; var pivotBtn = (MyGuiControlCheckbox)m_infoPage.Controls.GetControlByName("PivotBtn"); pivotBtn.IsChecked = MyCubeGrid.ShowGridPivot; pivotBtn.IsCheckedChanged = pivotBtn_IsCheckedChanged; } var showGravityGizmoBtn = (MyGuiControlCheckbox)m_infoPage.Controls.GetControlByName("ShowGravityGizmo"); showGravityGizmoBtn.IsChecked = MyCubeGrid.ShowGravityGizmos; showGravityGizmoBtn.IsCheckedChanged = showGravityGizmos_IsCheckedChanged; var showSenzorGizmoBtn = (MyGuiControlCheckbox)m_infoPage.Controls.GetControlByName("ShowSenzorGizmo"); showSenzorGizmoBtn.IsChecked = MyCubeGrid.ShowSenzorGizmos; showSenzorGizmoBtn.IsCheckedChanged = showSenzorGizmos_IsCheckedChanged; var showAntenaGizmoBtn = (MyGuiControlCheckbox)m_infoPage.Controls.GetControlByName("ShowAntenaGizmo"); showAntenaGizmoBtn.IsChecked = MyCubeGrid.ShowAntennaGizmos; showAntenaGizmoBtn.IsCheckedChanged = showAntenaGizmos_IsCheckedChanged; var friendAntennaRange = (MyGuiControlSlider)m_infoPage.Controls.GetControlByName("FriendAntennaRange"); friendAntennaRange.Value = MyHudMarkerRender.FriendAntennaRange; friendAntennaRange.ValueChanged += (MyGuiControlSlider s) => { MyHudMarkerRender.FriendAntennaRange = s.Value; }; var enemyAntennaRange = (MyGuiControlSlider)m_infoPage.Controls.GetControlByName("EnemyAntennaRange"); enemyAntennaRange.Value = MyHudMarkerRender.EnemyAntennaRange; enemyAntennaRange.ValueChanged += (MyGuiControlSlider s) => { MyHudMarkerRender.EnemyAntennaRange = s.Value; }; var ownedAntennaRange = (MyGuiControlSlider)m_infoPage.Controls.GetControlByName("OwnedAntennaRange"); ownedAntennaRange.Value = MyHudMarkerRender.OwnerAntennaRange; ownedAntennaRange.ValueChanged += (MyGuiControlSlider s) => { MyHudMarkerRender.OwnerAntennaRange = s.Value; }; if (MyFakes.ENABLE_TERMINAL_PROPERTIES) { var renameShipLabel = (MyGuiControlLabel)m_infoPage.Controls.GetControlByName("RenameShipLabel"); var renameShipBtn = (MyGuiControlButton)m_infoPage.Controls.GetControlByName("RenameShipButton"); var renameShipText = (MyGuiControlTextbox)m_infoPage.Controls.GetControlByName("RenameShipText"); if (renameShipText != null && m_grid != null) { renameShipText.Text = m_grid.DisplayName; } var showRenameShip = IsPlayerOwner(m_grid); renameShipLabel.Visible = showRenameShip; renameShipBtn.Visible = showRenameShip; renameShipText.Visible = showRenameShip; } var convertBtn = (MyGuiControlButton)m_infoPage.Controls.GetControlByName("ConvertBtn"); MyGuiControlList list = (MyGuiControlList)m_infoPage.Controls.GetControlByName("InfoList"); list.Controls.Clear(); if (m_grid == null || m_grid.Physics == null) { convertBtn.Enabled = false; MyGuiControlLabel noShip = new MyGuiControlLabel(text: MyTexts.GetString(MySpaceTexts.ScreenTerminalError_ShipNotConnected), font: Common.MyFontEnum.Red); list.Controls.Add(noShip); return; } if (!m_grid.IsStatic || m_grid.MarkedForClose) { convertBtn.Enabled = false; } int gravityCounter = 0; if (m_grid.BlocksCounters.ContainsKey(typeof(MyGravityGenerator))) { gravityCounter = m_grid.BlocksCounters[typeof(MyGravityGenerator)]; } int massCounter = 0; if (m_grid.BlocksCounters.ContainsKey(typeof(MyVirtualMass))) { massCounter = m_grid.BlocksCounters[typeof(MyVirtualMass)]; } int lightCounter = 0; if (m_grid.BlocksCounters.ContainsKey(typeof(MyInteriorLight))) { lightCounter = m_grid.BlocksCounters[typeof(MyInteriorLight)]; } var conveyorCounter = 0; foreach (var key in m_grid.BlocksCounters.Keys) { if (typeof(IMyConveyorSegmentBlock).IsAssignableFrom(key) || typeof(IMyConveyorEndpointBlock).IsAssignableFrom(key)) { conveyorCounter += m_grid.BlocksCounters[key]; } } int polygonCounter = 0; foreach (var block in m_grid.GetBlocks()) { if (block.FatBlock != null) { polygonCounter += block.FatBlock.Model.GetTrianglesCount(); } } foreach (var cell in m_grid.RenderData.Cells.Values) { foreach (var part in cell.CubeParts) { polygonCounter += part.Model.GetTrianglesCount(); } } MyGuiControlLabel polygonCount = new MyGuiControlLabel(text: new StringBuilder().AppendStringBuilder(MyTexts.Get(MySpaceTexts.TerminalTab_Info_Triangles)).AppendInt32(polygonCounter).ToString()); polygonCount.SetToolTip(MySpaceTexts.TerminalTab_Info_TrianglesTooltip); MyGuiControlLabel cubeCount = new MyGuiControlLabel(text: new StringBuilder().AppendStringBuilder(MyTexts.Get(MySpaceTexts.TerminalTab_Info_Blocks)).AppendInt32(m_grid.GetBlocks().Count).ToString()); cubeCount.SetToolTip(MySpaceTexts.TerminalTab_Info_BlocksTooltip); MyGuiControlLabel blockCount = new MyGuiControlLabel(text: new StringBuilder().AppendStringBuilder(MyTexts.Get(MySpaceTexts.TerminalTab_Info_NonArmor)).AppendInt32(m_grid.Hierarchy.Children.Count).ToString()); MyGuiControlLabel thrustCount = new MyGuiControlLabel(text: new StringBuilder().AppendStringBuilder(MyTexts.Get(MySpaceTexts.TerminalTab_Info_Thrusters)).AppendInt32(m_grid.GridSystems.ThrustSystem.ThrustCount).ToString()); MyGuiControlLabel lightCount = new MyGuiControlLabel(text: new StringBuilder().Clear().AppendStringBuilder(MyTexts.Get(MySpaceTexts.TerminalTab_Info_Lights)).AppendInt32(lightCounter).ToString()); MyGuiControlLabel reflectorCount = new MyGuiControlLabel(text: new StringBuilder().AppendStringBuilder(MyTexts.Get(MySpaceTexts.TerminalTab_Info_Reflectors)).AppendInt32(m_grid.GridSystems.ReflectorLightSystem.ReflectorCount).ToString()); //MyGuiControlLabel wheelCount = new MyGuiControlLabel(text: new StringBuilder().AppendStringBuilder(MyTexts.Get(MySpaceTexts.TerminalTab_Info_Rotors)).AppendInt32(m_grid.WheelSystem.WheelCount)); MyGuiControlLabel gravityCount = new MyGuiControlLabel(text: new StringBuilder().AppendStringBuilder(MyTexts.Get(MySpaceTexts.TerminalTab_Info_GravGens)).AppendInt32(gravityCounter).ToString()); MyGuiControlLabel massCount = new MyGuiControlLabel(text: new StringBuilder().AppendStringBuilder(MyTexts.Get(MySpaceTexts.TerminalTab_Info_VirtualMass)).AppendInt32(massCounter).ToString()); MyGuiControlLabel conveyorCount = new MyGuiControlLabel(text: new StringBuilder().AppendStringBuilder(MyTexts.Get(MySpaceTexts.TerminalTab_Info_Conveyors)).AppendInt32(conveyorCounter).ToString()); list.InitControls(new MyGuiControlBase[] { cubeCount, blockCount, conveyorCount, thrustCount, lightCount, reflectorCount, gravityCount, massCount, polygonCount }); }
public override bool DebugDraw() { if (MyDebugDrawSettings.DEBUG_DRAW_FIXED_BLOCK_QUERIES) { foreach (var b in m_cubeGrid.GetBlocks()) { var geometryBox = b.FatBlock.GetGeometryLocalBox(); //geometryBox.Inflate(0.5f); Vector3 halfExtents = geometryBox.Size / 2; Vector3D pos; b.ComputeScaledCenter(out pos); pos += geometryBox.Center; pos = Vector3D.Transform(pos, m_cubeGrid.WorldMatrix); Matrix blockMatrix; b.Orientation.GetMatrix(out blockMatrix); var q = Quaternion.CreateFromRotationMatrix(blockMatrix * m_cubeGrid.WorldMatrix.GetOrientation()); Sandbox.Engine.Physics.MyPhysics.GetPenetrationsBox(ref halfExtents, ref pos, ref q, m_penetrations, Sandbox.Engine.Physics.MyPhysics.CollideWithStaticLayer); bool isStatic = false; foreach (var p in m_penetrations) { var e = p.GetCollisionEntity(); if (e != null && e is MyVoxelMap) { isStatic = true; break; } } m_penetrations.Clear(); MyOrientedBoundingBoxD obb = new MyOrientedBoundingBoxD(pos, halfExtents, q); MyRenderProxy.DebugDrawOBB(obb, isStatic ? Color.Green : Color.Red, 0.1f, false, false); } } if (MyDebugDrawSettings.DEBUG_DRAW_GRID_NAMES || MyDebugDrawSettings.DEBUG_DRAW_GRID_CONTROL) { string text = ""; var color = Color.White; if (MyDebugDrawSettings.DEBUG_DRAW_GRID_NAMES) { text += m_cubeGrid.ToString() + " "; } if (MyDebugDrawSettings.DEBUG_DRAW_GRID_CONTROL) { var controllingPlayer = Sync.Players.GetControllingPlayer(m_cubeGrid); if (controllingPlayer != null) { text += "Controlled by: " + controllingPlayer.DisplayName; color = Color.LightGreen; } } MyRenderProxy.DebugDrawText3D(m_cubeGrid.PositionComp.WorldAABB.Center, text, color, 0.7f, false, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER); } MyRenderComponentCubeGrid gridRender = m_cubeGrid.Render; if (MyDebugDrawSettings.DEBUG_DRAW_BLOCK_GROUPS) { var tpos = m_cubeGrid.PositionComp.WorldMatrix.Translation; foreach (var group in m_cubeGrid.BlockGroups) { MyRenderProxy.DebugDrawText3D(tpos, group.Name.ToString(), Color.Red, 1, false); tpos += m_cubeGrid.PositionComp.WorldMatrix.Right * group.Name.Length * 0.1f; } } if (MyDebugDrawSettings.DEBUG_DRAW_GRID_DIRTY_BLOCKS) { foreach (var b in m_dirtyBlocks) { var color = m_cubeGrid.GetCubeBlock(b.Key) != null?Color.Red.ToVector3() : Color.Yellow.ToVector3(); var m = Matrix.CreateScale(m_cubeGrid.GridSize) * Matrix.CreateTranslation(b.Key * m_cubeGrid.GridSize) * m_cubeGrid.WorldMatrix; MyRenderProxy.DebugDrawOBB(m, color, 0.15f, false, true); } } // Bone debug draw if (MyDebugDrawSettings.DEBUG_DRAW_DISPLACED_BONES) { Vector3 cameraPos = (Vector3)MySector.MainCamera.Position; foreach (var bone in m_cubeGrid.Skeleton.Bones) { var bonePos = (bone.Key / (float)m_cubeGrid.Skeleton.BoneDensity) * gridRender.GridSize + bone.Value; bonePos -= new Vector3(gridRender.GridSize / m_cubeGrid.Skeleton.BoneDensity); Vector3 pos = Vector3.Transform(bonePos, (Matrix)m_cubeGrid.PositionComp.WorldMatrix); MyRenderProxy.DebugDrawSphere(pos, 0.05f, Color.Red.ToVector3(), 0.5f, false, true); if ((cameraPos - pos).LengthSquared() < 200.0f) { MyRenderProxy.DebugDrawText3D(pos, bone.Key.ToString(), Color.Red, 0.4f, false); } } } if (MyDebugDrawSettings.DEBUG_DRAW_STRUCTURAL_INTEGRITY && m_cubeGrid.StructuralIntegrity != null) { m_cubeGrid.StructuralIntegrity.DebugDraw(); } if (MyDebugDrawSettings.DEBUG_DRAW_CUBES) { foreach (var cubeBlock in m_cubeGrid.CubeBlocks) { var cb = cubeBlock.FatBlock; if (cb == null) { continue; } cb.DebugDraw(); } } m_cubeGrid.GridSystems.DebugDraw(); if (MyDebugDrawSettings.DEBUG_DRAW_GRID_TERMINAL_SYSTEMS) { /* if (grid.OnBlockAdded != null) * { * MyRenderProxy.DebugDrawText3D(Entity.PositionComp.WorldMatrix.Translation + new Vector3(0.0f, 0.0f, 0.5f), grid.OnBlockAdded.GetInvocationList().Count().ToString(), Color.NavajoWhite, 1.0f, false); * }*/ } if (MyFakes.ENABLE_TRASH_REMOVAL && MyDebugDrawSettings.DEBUG_DRAW_TRASH_REMOVAL) { Color color = m_cubeGrid.IsTrash() ? Color.Red : Color.Green; float sphereRadius = m_cubeGrid.PositionComp.LocalAABB.HalfExtents.AbsMax(); MyRenderProxy.DebugDrawSphere(m_cubeGrid.Physics != null ? m_cubeGrid.Physics.CenterOfMassWorld : m_cubeGrid.PositionComp.WorldMatrix.Translation, sphereRadius, color, 1.0f, false); } if (MyDebugDrawSettings.DEBUG_DRAW_GRID_ORIGINS) { MyRenderProxy.DebugDrawAxis(m_cubeGrid.PositionComp.WorldMatrix, 1.0f, false); } if (MyDebugDrawSettings.ENABLE_DEBUG_DRAW && MyDebugDrawSettings.DEBUG_DRAW_MOUNT_POINTS_ALL) { foreach (MySlimBlock block in m_cubeGrid.GetBlocks()) { if ((m_cubeGrid.GridIntegerToWorld(block.Position) - MySector.MainCamera.Position).LengthSquared() < 200) { DebugDrawMountPoints(block); } } } if (MyDebugDrawSettings.DEBUG_DRAW_BLOCK_INTEGRITY) { if (MySector.MainCamera != null && (MySector.MainCamera.Position - m_cubeGrid.PositionComp.WorldVolume.Center).Length() < 16 + m_cubeGrid.PositionComp.WorldVolume.Radius) { foreach (var cubeBlock in m_cubeGrid.CubeBlocks) { var pos = m_cubeGrid.GridIntegerToWorld(cubeBlock.Position); if (m_cubeGrid.GridSizeEnum == MyCubeSize.Large || (MySector.MainCamera != null && (MySector.MainCamera.Position - pos).LengthSquared() < 9)) { float integrity = 0; if (cubeBlock.FatBlock is MyCompoundCubeBlock) { foreach (var b in (cubeBlock.FatBlock as MyCompoundCubeBlock).GetBlocks()) { integrity += b.Integrity; } } else { integrity = cubeBlock.Integrity; } MyRenderProxy.DebugDrawText3D(m_cubeGrid.GridIntegerToWorld(cubeBlock.Position), ((int)integrity).ToString(), Color.White, m_cubeGrid.GridSizeEnum == MyCubeSize.Large ? 0.65f : 0.5f, false); } } } } return(base.DebugDraw()); }