public static MyDefinitionBase GetItemDefinition(this MyPhysicalInventoryItem thisItem) { if (thisItem.Content == null) { return(null); } // Block MyDefinitionBase itemDefinition = null; if (thisItem.Content is MyObjectBuilder_BlockItem) { var id = (thisItem.Content as MyObjectBuilder_BlockItem).BlockDefId; MyCubeBlockDefinition blockDef = null; if (MyDefinitionManager.Static.TryGetCubeBlockDefinition(id, out blockDef)) { itemDefinition = blockDef; } } else { itemDefinition = MyDefinitionManager.Static.TryGetComponentBlockDefinition(thisItem.Content.GetId()); } // Floating object if (itemDefinition == null) { MyPhysicalItemDefinition floatingObjectDefinition; if (MyDefinitionManager.Static.TryGetPhysicalItemDefinition(thisItem.Content.GetId(), out floatingObjectDefinition)) { itemDefinition = floatingObjectDefinition; } } return(itemDefinition); }
public static void DrawMountPoints(float cubeSize, MyCubeBlockDefinition def, ref MatrixD drawMatrix) { var mountPoints = def.GetBuildProgressModelMountPoints(1.0f); if (mountPoints == null) { return; } if (!MyDebugDrawSettings.DEBUG_DRAW_MOUNT_POINTS_AUTOGENERATE) { DrawMountPoints(cubeSize, def, drawMatrix, mountPoints); } else { //Generate mount points from model collisions and draw them if (def.Model != null) { int index = 0; MyModel model = MyModels.GetModel(def.Model); foreach (var shape in model.HavokCollisionShapes) { MyPhysicsBody.DrawCollisionShape(shape, drawMatrix, 0.2f, ref index); } var newMountPoints = AutogenerateMountpoints(model, cubeSize); DrawMountPoints(cubeSize, def, drawMatrix, newMountPoints.ToArray()); } } if (MyDebugDrawSettings.DEBUG_DRAW_MOUNT_POINTS_AXIS_HELPERS) { DrawMountPointsAxisHelpers(def, ref drawMatrix, cubeSize); } }
protected void InternalAddCubeBlock( ) { if (_cubeBlockToAddRemove == null) { return; } try { MyObjectBuilder_CubeBlock objectBuilder = _cubeBlockToAddRemove.ObjectBuilder; MyCubeBlockDefinition blockDef = MyDefinitionManager.Static.GetCubeBlockDefinition(objectBuilder); NetworkManager.BroadcastAddCubeBlock(_cubeBlockToAddRemove); Object result = InvokeEntityMethod(BackingObject, CubeGridAddCubeBlockMethod, new object[] { objectBuilder, true, blockDef }); _cubeBlockToAddRemove.BackingObject = result; } catch (Exception ex) { ApplicationLog.BaseLog.Error(ex); } _cubeBlockToAddRemove = null; }
private static void DrawMountPointsAxisHelpers(MyCubeBlockDefinition def, ref MatrixD drawMatrix, float cubeSize) { Vector3I centerGrid = def.Center; Vector3 centerOffset = def.Size * 0.5f; MatrixD drawTransf = MatrixD.CreateTranslation(centerGrid - centerOffset) * MatrixD.CreateScale(cubeSize) * drawMatrix; // Draw axis helpers for the six mount point walls for (int i = 0; i < 6; ++i) { Base6Directions.Direction dir = (Base6Directions.Direction)i; Vector3D position = Vector3D.Zero; position.Z = -0.2f; Vector3D normal = Vector3.Forward; Vector3D right = Vector3.Right; Vector3D up = Vector3.Up; position = def.MountPointLocalToBlockLocal(position, dir); position = Vector3D.Transform(position, drawTransf); normal = def.MountPointLocalNormalToBlockLocal(normal, dir); normal = Vector3D.TransformNormal(normal, drawTransf); up = def.MountPointLocalNormalToBlockLocal(up, dir); up = Vector3D.TransformNormal(up, drawTransf); right = def.MountPointLocalNormalToBlockLocal(right, dir); right = Vector3D.TransformNormal(right, drawTransf); MatrixD rightMat = MatrixD.CreateWorld(position + right * 0.25f, normal, right); MatrixD upMat = MatrixD.CreateWorld(position + up * 0.25f, normal, up); Vector4 rc = Color.Red.ToVector4(); Vector4 uc = Color.Green.ToVector4(); MyRenderProxy.DebugDrawSphere(position, 0.03f * cubeSize, Color.Red.ToVector3(), 1.0f, true); MySimpleObjectDraw.DrawTransparentCylinder(ref rightMat, 0.0f, 0.03f * cubeSize, 0.5f * cubeSize, ref rc, false, 16, 0.01f * cubeSize); MySimpleObjectDraw.DrawTransparentCylinder(ref upMat, 0.0f, 0.03f * cubeSize, 0.5f * cubeSize, ref uc, false, 16, 0.01f * cubeSize); MyRenderProxy.DebugDrawLine3D(position, position - normal * 0.2f, Color.Red, Color.Red, true); float textSizeX = 0.5f * cubeSize; float textSizeY = 0.5f * cubeSize; float textSizeDesc = 0.5f * cubeSize; if (MySector.MainCamera != null) { float distX = (float)(position + right * 0.55f - MySector.MainCamera.Position).Length(); float distY = (float)(position + up * 0.55f - MySector.MainCamera.Position).Length(); float distDesc = (float)(position + normal * 0.1f - MySector.MainCamera.Position).Length(); textSizeX = textSizeX * 6 / distX; textSizeY = textSizeY * 6 / distY; textSizeDesc = textSizeDesc * 6 / distDesc; } MyRenderProxy.DebugDrawText3D(position + right * 0.55f, "X", Color.Red, textSizeX, false, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER); MyRenderProxy.DebugDrawText3D(position + up * 0.55f, "Y", Color.Green, textSizeY, false, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER); MyRenderProxy.DebugDrawText3D(position + normal * 0.1f, m_mountPointSideNames[i], Color.White, textSizeDesc, true, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER); } // If close enough, draw a black grid spaced by tenths of a mount point unit float dist = (float)(drawTransf.Translation - MySector.MainCamera.Position).Length(); BoundingBoxD bb = new BoundingBoxD(-def.Size * cubeSize * 0.5f, def.Size * cubeSize * 0.5f); dist -= (float)bb.Size.Max() * 0.866f; // sqrt(3) * 0.5 - half of the solid diagonal of a cube Color black = Color.Black; if (dist < cubeSize * 3.0f) { MySimpleObjectDraw.DrawTransparentBox(ref drawMatrix, ref bb, ref black, MySimpleObjectRasterizer.Wireframe, def.Size * 10, 0.005f / (float)bb.Size.Max() * cubeSize, onlyFrontFaces: true); } }
public static Vector3 GetScaledSize(this MyCubeBlockDefinition def) { return(def.Size * def.CubeSize.GetSizeM()); }
protected static void AddFastBuildModelWithSubparts(ref MatrixD matrix, List <MatrixD> matrices, List <string> models, MyCubeBlockDefinition blockDefinition, float gridScale) { if (string.IsNullOrEmpty(blockDefinition.Model)) { return; } matrices.Add(matrix); models.Add(blockDefinition.Model); var data = new MyEntitySubpart.Data(); MyCubeBlockDefinition subBlockDefinition; MatrixD subBlockMatrix; Vector3 dummyPosition; MyModel modelData = VRage.Game.Models.MyModels.GetModelOnlyData(blockDefinition.Model); modelData.Rescale(gridScale); foreach (var dummy in modelData.Dummies) { if (MyEntitySubpart.GetSubpartFromDummy(blockDefinition.Model, dummy.Key, dummy.Value, ref data)) { // Rescale model var model = VRage.Game.Models.MyModels.GetModelOnlyData(data.File); if (model != null) { model.Rescale(gridScale); } MatrixD mCopy = MatrixD.Multiply(data.InitialTransform, matrix); matrices.Add(mCopy); models.Add(data.File); } else if (MyFakes.ENABLE_SUBBLOCKS && MyCubeBlock.GetSubBlockDataFromDummy(blockDefinition, dummy.Key, dummy.Value, false, out subBlockDefinition, out subBlockMatrix, out dummyPosition)) { if (!string.IsNullOrEmpty(subBlockDefinition.Model)) { // Rescale model var model = VRage.Game.Models.MyModels.GetModelOnlyData(subBlockDefinition.Model); if (model != null) { model.Rescale(gridScale); } // Repair subblock matrix to have int axes (because preview renderer does not allow such non integer rotation). Vector3I forward = Vector3I.Round(Vector3.DominantAxisProjection(subBlockMatrix.Forward)); Vector3I invForward = Vector3I.One - Vector3I.Abs(forward); Vector3I right = Vector3I.Round(Vector3.DominantAxisProjection((Vector3)subBlockMatrix.Right * invForward)); Vector3I up; Vector3I.Cross(ref right, ref forward, out up); subBlockMatrix.Forward = forward; subBlockMatrix.Right = right; subBlockMatrix.Up = up; MatrixD mCopy = MatrixD.Multiply(subBlockMatrix, matrix); matrices.Add(mCopy); models.Add(subBlockDefinition.Model); } } } // Precache models for generated blocks if (MyFakes.ENABLE_GENERATED_BLOCKS && !blockDefinition.IsGeneratedBlock && blockDefinition.GeneratedBlockDefinitions != null) { foreach (var generatedBlockDefId in blockDefinition.GeneratedBlockDefinitions) { MyCubeBlockDefinition generatedBlockDef; if (MyDefinitionManager.Static.TryGetCubeBlockDefinition(generatedBlockDefId, out generatedBlockDef)) { var model = VRage.Game.Models.MyModels.GetModelOnlyData(generatedBlockDef.Model); if (model != null) { model.Rescale(gridScale); } } } } }
public override void GetBlockPlacementMaterials(MyCubeBlockDefinition definition, Vector3I position, MyBlockOrientation orientation, MyCubeGrid grid) { ClearRequiredMaterials(); GetMaterialsSimple(definition, m_materialList); }
/// <summary> /// Whether connection is allowed to any of the positions between otherBlockMinPos and otherBlockMaxPos (both inclusive). /// Default implementation calls ConnectionAllowed(ref Vector3I otherBlockPos, ref Vector3I faceNormal) in a for loop. /// Override this in a subclass if this is not needed (for example, because all calls would return the same value for the same face) /// </summary> public virtual bool ConnectionAllowed(ref Vector3I otherBlockMinPos, ref Vector3I otherBlockMaxPos, ref Vector3I faceNormal, MyCubeBlockDefinition def) { Vector3I pos = otherBlockMinPos; for (Vector3I.RangeIterator it = new Vector3I.RangeIterator(ref otherBlockMinPos, ref otherBlockMaxPos); it.IsValid(); it.GetNext(out pos)) { if (ConnectionAllowed(ref pos, ref faceNormal, def)) { return(true); } } return(false); }
/// <summary> /// Returns subblock data from dummy, subblock matrix can be offset (according to useOffset parameter) so the dummy position output is also provided. /// </summary> /// <returns>true when dummy is subblock otherwise false</returns> public static bool GetSubBlockDataFromDummy(MyCubeBlockDefinition ownerBlockDefinition, string dummyName, MyModelDummy dummy, bool useOffset, out MyCubeBlockDefinition subBlockDefinition, out MatrixD subBlockMatrix, out Vector3 dummyPosition) { subBlockDefinition = null; subBlockMatrix = MatrixD.Identity; dummyPosition = Vector3.Zero; if (!dummyName.ToLower().StartsWith(MyCubeBlock.DUMMY_SUBBLOCK_ID)) { return(false); } if (ownerBlockDefinition.SubBlockDefinitions == null) { return(false); } string dummyNameShort = dummyName.Substring(MyCubeBlock.DUMMY_SUBBLOCK_ID.Length); MyDefinitionId definitiondId; if (!ownerBlockDefinition.SubBlockDefinitions.TryGetValue(dummyNameShort, out definitiondId)) { Debug.Assert(false, "SubBlock definition not found!"); return(false); } MyDefinitionManager.Static.TryGetCubeBlockDefinition(definitiondId, out subBlockDefinition); if (subBlockDefinition == null) { Debug.Assert(false, "SubBlock definition not found!"); return(false); } const double dotEpsilon = 0.00000001; subBlockMatrix = MatrixD.Normalize(dummy.Matrix); Vector3I forward = Base6Directions.GetIntVector(Base6Directions.GetClosestDirection(subBlockMatrix.Forward)); double forwardDot = Vector3D.Dot(subBlockMatrix.Forward, (Vector3D)forward); if (Math.Abs(1 - forwardDot) <= dotEpsilon) { subBlockMatrix.Forward = forward; } Vector3I right = Base6Directions.GetIntVector(Base6Directions.GetClosestDirection(subBlockMatrix.Right)); double rightDot = Vector3D.Dot(subBlockMatrix.Right, (Vector3D)right); if (Math.Abs(1 - rightDot) <= dotEpsilon) { subBlockMatrix.Right = right; } Vector3I up = Base6Directions.GetIntVector(Base6Directions.GetClosestDirection(subBlockMatrix.Up)); double upDot = Vector3D.Dot(subBlockMatrix.Up, (Vector3D)up); if (Math.Abs(1 - upDot) <= dotEpsilon) { subBlockMatrix.Up = up; } dummyPosition = subBlockMatrix.Translation; if (useOffset) { Vector3 offset = MyCubeBlock.GetBlockGridOffset(subBlockDefinition); subBlockMatrix.Translation -= Vector3D.TransformNormal(offset, subBlockMatrix); } return(true); }
public MyObjectBuilder_CubeBlock CreateCube(MyObjectBuilderType typeId, string subTypeId, MyCubeBlockDefinition definition) { var newCube = SpaceEngineersCore.Resources.CreateNewObject <MyObjectBuilder_CubeBlock>(typeId, subTypeId); newCube.BlockOrientation = Cube.BlockOrientation; newCube.ColorMaskHSV = Cube.ColorMaskHSV; newCube.BuildPercent = Cube.BuildPercent; newCube.EntityId = Cube.EntityId; newCube.IntegrityPercent = Cube.IntegrityPercent; newCube.Min = Cube.Min; newCube.BuiltBy = Cube.BuiltBy; newCube.Owner = Cube.Owner; newCube.ShareMode = Cube.ShareMode; newCube.DeformationRatio = Cube.DeformationRatio; newCube.BlockGeneralDamageModifier = Cube.BlockGeneralDamageModifier; SetProperties(newCube, definition); return(newCube); }
private void BuildBlock(IMySlimBlock block, MyCubeBlock constructionBlock) { MyObjectBuilder_CubeBlock cubeBlock = block.GetObjectBuilder(); MyObjectBuilder_ProjectorBase projectorBuilder = null;// = (MyObjectBuilder_ProjectorBase)constructionBlock.GetObjectBuilderCubeBlock(); MyCubeGrid projectorGrid = null; MyCubeGrid blockGrid = (MyCubeGrid)block.CubeGrid; MyCubeBlock projector = null; foreach (var item in NaniteConstructionManager.ProjectorBlocks) { var projectorTest = item.Value as IMyProjector; if (projectorTest == null) { continue; } if (projectorTest.ProjectedGrid == null) { continue; } if (projectorTest.ProjectedGrid == block.CubeGrid) { projector = (MyCubeBlock)projectorTest; projectorGrid = projector.CubeGrid; projectorBuilder = (MyObjectBuilder_ProjectorBase)projector.GetObjectBuilderCubeBlock(); break; } } /* * Ingame.IMyGridTerminalSystem system = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid((IMyCubeGrid)m_constructionBlock.ConstructionBlock.CubeGrid); * List<Ingame.IMyTerminalBlock> terminalBlocks = new List<Ingame.IMyTerminalBlock>(); * system.GetBlocks(terminalBlocks); * foreach(var item in terminalBlocks) * { * if (!(item is IMyFunctionalBlock) || !((IMyFunctionalBlock)item).Enabled) * continue; * * if (!(item is Ingame.IMyProjector)) * continue; * * var cube = (MyCubeBlock)item; * MyObjectBuilder_ProjectorBase testBuilder = (MyObjectBuilder_ProjectorBase)cube.GetObjectBuilderCubeBlock(); * if (testBuilder.ProjectedGrid == null) * continue; * * if(testBuilder.ProjectedGrid.DisplayName == blockGrid.DisplayName) * { * projector = cube; * projectorGrid = cube.CubeGrid; * projectorBuilder = testBuilder; * break; * } * } */ if (projectorBuilder == null) { Logging.Instance.WriteLine("PROBLEM Can not locate projector that is projecting target!"); return; } Quaternion quat = Quaternion.Identity; var orientation = block.Orientation; Matrix local; orientation.GetMatrix(out local); var gridOrientation = GetGridOrientation(projectorBuilder); if (gridOrientation != Matrix.Identity) { var afterRotation = Matrix.Multiply(local, gridOrientation); orientation = new MyBlockOrientation(ref afterRotation); } Quaternion projQuat = Quaternion.Identity; projector.Orientation.GetQuaternion(out projQuat); orientation.GetQuaternion(out quat); quat = Quaternion.Multiply(projQuat, quat); // Get real block max MyCubeBlockDefinition blockDefinition = (MyCubeBlockDefinition)block.BlockDefinition; Vector3I blockMax = block.Max; Vector3I blockMin = cubeBlock.Min; Vector3I position = block.Position; Vector3I min = projectorGrid.WorldToGridInteger(blockGrid.GridIntegerToWorld(blockMin)); Vector3I max = projectorGrid.WorldToGridInteger(blockGrid.GridIntegerToWorld(blockMax)); Vector3I pos = projectorGrid.WorldToGridInteger(blockGrid.GridIntegerToWorld(block.Position)); Vector3I projectedMin = new Vector3I(Math.Min(min.X, max.X), Math.Min(min.Y, max.Y), Math.Min(min.Z, max.Z)); Vector3I projectedMax = new Vector3I(Math.Max(min.X, max.X), Math.Max(min.Y, max.Y), Math.Max(min.Z, max.Z)); MyCubeGrid.MyBlockLocation location = new MyCubeGrid.MyBlockLocation(blockDefinition.Id, projectedMin, projectedMax, pos, quat, 0, constructionBlock.OwnerId); /* * MyObjectBuilder_CubeGrid originalGridBuilder = (MyObjectBuilder_CubeGrid)blockGrid.GetObjectBuilder(); * MyObjectBuilder_CubeBlock objectBuilder = null; * //Find original grid builder * foreach (var blockBuilder in originalGridBuilder.CubeBlocks) * { * if (blockBuilder.GetId() == blockDefinition.Id) * { * if ((Vector3I)blockBuilder.Min == blockMin) * { * objectBuilder = (MyObjectBuilder_CubeBlock)blockBuilder.Clone(); * objectBuilder.SetupForProjector(); * } * } * } */ MyObjectBuilder_CubeBlock objectBuilder = cubeBlock; objectBuilder.SetupForProjector(); var functionalBuilder = objectBuilder as MyObjectBuilder_FunctionalBlock; if (functionalBuilder != null && !functionalBuilder.Enabled) { functionalBuilder.Enabled = true; } var terminalBuilder = objectBuilder as MyObjectBuilder_TerminalBlock; if (terminalBuilder != null) { terminalBuilder.Owner = constructionBlock.OwnerId; } var shipConnector = objectBuilder as MyObjectBuilder_ShipConnector; if (shipConnector != null) { shipConnector.Connected = false; shipConnector.ConnectedEntityId = 0; shipConnector.MasterToSlaveGrid = null; shipConnector.MasterToSlaveTransform = null; } //if (objectBuilder == null) // objectBuilder = cubeBlock; location.EntityId = 0; // MyEntityIdentifier.AllocateId(); objectBuilder.EntityId = 0; objectBuilder.ConstructionInventory = null; projector.CubeGrid.BuildBlockRequest(block.GetColorMask().PackHSVToUint(), location, objectBuilder, constructionBlock.EntityId, false, constructionBlock.OwnerId); }
private static InventoryEditorModel ParseInventory(MyObjectBuilder_Inventory inventory, MyCubeBlockDefinition definition = null) { if (inventory == null) { return(null); } float volumeMultiplier = 1f; // Unsure if there should be a default of 1 if there isn't a InventorySize defined. if (definition == null) { volumeMultiplier = 0.4f; } else { var definitionType = definition.GetType(); var invSizeField = definitionType.GetField("InventorySize"); var inventoryMaxVolumeField = definitionType.GetField("InventoryMaxVolume"); if (invSizeField != null) { var invSize = (Vector3)invSizeField.GetValue(definition); volumeMultiplier = invSize.X * invSize.Y * invSize.Z; } if (inventoryMaxVolumeField != null) { var maxSize = (float)inventoryMaxVolumeField.GetValue(definition); volumeMultiplier = MathHelper.Min(volumeMultiplier, maxSize); } } var settings = SpaceEngineersCore.WorldResource.Checkpoint.Settings; return(new InventoryEditorModel(inventory, volumeMultiplier * 1000 * settings.InventorySizeMultiplier, null) { Name = inventory.InventoryFlags.ToString(), IsValid = true }); }
public static ObservableCollection <InventoryEditorModel> GetInventory(this MyObjectBuilder_ComponentContainer componentContainer, MyCubeBlockDefinition definition = null) { var inventoryEditors = new ObservableCollection <InventoryEditorModel>(); if (componentContainer != null) { var inventoryBase = componentContainer.Components.FirstOrDefault(e => e.TypeId == "MyInventoryBase"); if (inventoryBase != null) { var singleInventory = inventoryBase.Component as MyObjectBuilder_Inventory; if (singleInventory != null) { var iem = ParseInventory(singleInventory, definition); if (iem != null) { inventoryEditors.Add(iem); } } var aggregate = inventoryBase.Component as MyObjectBuilder_InventoryAggregate; if (aggregate != null) { foreach (var field in aggregate.Inventories) { var iem = ParseInventory(field as MyObjectBuilder_Inventory, definition); if (iem != null) { inventoryEditors.Add(iem); } } } } } return(inventoryEditors); }
protected bool GeneratedBlockExists(Vector3I pos, MyBlockOrientation orientation, MyCubeBlockDefinition definition) { MySlimBlock cubeBlock = this.m_grid.GetCubeBlock(pos); if (cubeBlock != null) { MyCompoundCubeBlock fatBlock = cubeBlock.FatBlock as MyCompoundCubeBlock; if (!MyFakes.ENABLE_COMPOUND_BLOCKS || (fatBlock == null)) { return((cubeBlock.BlockDefinition.Id.SubtypeId == definition.Id.SubtypeId) && (cubeBlock.Orientation == orientation)); } using (List <MySlimBlock> .Enumerator enumerator = fatBlock.GetBlocks().GetEnumerator()) { while (true) { if (!enumerator.MoveNext()) { break; } MySlimBlock current = enumerator.Current; if ((current.BlockDefinition.Id.SubtypeId == definition.Id.SubtypeId) && (current.Orientation == orientation)) { return(true); } } } } return(false); }
public void SetBlockDefinition(MyCubeBlockDefinition definition) { SetTextFormatArguments( definition.Components[0].Definition.DisplayNameText.ToString(), definition.DisplayNameText.ToString()); }
public override void Init(MyObjectBuilder_CubeBlock builder, MyCubeGrid cubeGrid) { base.Init(builder, cubeGrid); base.CheckConnectionAllowed = true; MyObjectBuilder_FracturedBlock block = builder as MyObjectBuilder_FracturedBlock; if (block.Shapes.Count == 0) { if (!block.CreatingFracturedBlock) { throw new Exception("No relevant shape was found for fractured block. It was probably reexported and names changed."); } } else { this.OriginalBlocks = new List <MyDefinitionId>(); this.Orientations = new List <MyBlockOrientation>(); List <HkdShapeInstanceInfo> list = new List <HkdShapeInstanceInfo>(); foreach (SerializableDefinitionId id in block.BlockDefinitions) { MyCubeBlockDefinition cubeBlockDefinition = MyDefinitionManager.Static.GetCubeBlockDefinition(id); string model = cubeBlockDefinition.Model; if (MyModels.GetModelOnlyData(model).HavokBreakableShapes == null) { MyDestructionData.Static.LoadModelDestruction(model, cubeBlockDefinition, Vector3.One, true, false); } HkdBreakableShape shape = MyModels.GetModelOnlyData(model).HavokBreakableShapes[0]; Quaternion? rotation = null; Vector3? translation = null; HkdShapeInstanceInfo item = new HkdShapeInstanceInfo(shape, rotation, translation); list.Add(item); m_children.Add(item); shape.GetChildren(m_children); if (cubeBlockDefinition.BuildProgressModels != null) { MyCubeBlockDefinition.BuildProgressModel[] buildProgressModels = cubeBlockDefinition.BuildProgressModels; for (int j = 0; j < buildProgressModels.Length; j++) { model = buildProgressModels[j].File; if (MyModels.GetModelOnlyData(model).HavokBreakableShapes == null) { MyDestructionData.Static.LoadModelDestruction(model, cubeBlockDefinition, Vector3.One, true, false); } shape = MyModels.GetModelOnlyData(model).HavokBreakableShapes[0]; rotation = null; translation = null; item = new HkdShapeInstanceInfo(shape, rotation, translation); list.Add(item); m_children.Add(item); shape.GetChildren(m_children); } } this.OriginalBlocks.Add(id); } foreach (SerializableBlockOrientation orientation in block.BlockOrientations) { this.Orientations.Add((MyBlockOrientation)orientation); } if (block.MultiBlocks.Count > 0) { this.MultiBlocks = new List <MultiBlockPartInfo>(); foreach (MyObjectBuilder_FracturedBlock.MyMultiBlockPart part in block.MultiBlocks) { if (part == null) { this.MultiBlocks.Add(null); continue; } MultiBlockPartInfo item = new MultiBlockPartInfo(); item.MultiBlockDefinition = part.MultiBlockDefinition; item.MultiBlockId = part.MultiBlockId; this.MultiBlocks.Add(item); } } this.m_shapes.AddRange(block.Shapes); for (int i = 0; i < m_children.Count; i++) { HkdShapeInstanceInfo child = m_children[i]; Func <MyObjectBuilder_FracturedBlock.ShapeB, bool> predicate = s => s.Name == child.ShapeName; IEnumerable <MyObjectBuilder_FracturedBlock.ShapeB> source = this.m_shapes.Where <MyObjectBuilder_FracturedBlock.ShapeB>(predicate); if (source.Count <MyObjectBuilder_FracturedBlock.ShapeB>() <= 0) { child.GetChildren(m_children); } else { MyObjectBuilder_FracturedBlock.ShapeB item = source.First <MyObjectBuilder_FracturedBlock.ShapeB>(); Matrix transform = Matrix.CreateFromQuaternion((Quaternion)item.Orientation); transform.Translation = child.GetTransform().Translation; HkdShapeInstanceInfo info2 = new HkdShapeInstanceInfo(child.Shape.Clone(), transform); if (item.Fixed) { info2.Shape.SetFlagRecursively(HkdBreakableShape.Flags.IS_FIXED); } list.Add(info2); m_shapeInfos.Add(info2); this.m_shapes.Remove(item); } } if (m_shapeInfos.Count == 0) { m_children.Clear(); throw new Exception("No relevant shape was found for fractured block. It was probably reexported and names changed."); } foreach (HkdShapeInstanceInfo info3 in m_shapeInfos) { HkdBreakableShape shape = info3.Shape; if (!string.IsNullOrEmpty(shape.Name)) { this.Render.AddPiece(info3.Shape.Name, Matrix.CreateFromQuaternion(Quaternion.CreateFromRotationMatrix(info3.GetTransform().GetOrientation()))); } } if (base.CubeGrid.CreatePhysics) { HkdBreakableShape?oldParent = null; HkdBreakableShape shape3 = (HkdBreakableShape) new HkdCompoundBreakableShape(oldParent, m_shapeInfos); shape3.RecalcMassPropsFromChildren(); this.Shape = shape3; HkMassProperties massProperties = new HkMassProperties(); shape3.BuildMassProperties(ref massProperties); this.Shape = new HkdBreakableShape(shape3.GetShape(), ref massProperties); shape3.RemoveReference(); foreach (HkdShapeInstanceInfo info4 in m_shapeInfos) { this.Shape.AddShape(ref info4); } this.Shape.SetStrenght(MyDestructionConstants.STRENGTH); this.CreateMountPoints(); } m_children.Clear(); foreach (HkdShapeInstanceInfo info5 in m_shapeInfos) { info5.Shape.RemoveReference(); } foreach (HkdShapeInstanceInfo info6 in list) { info6.RemoveReference(); } m_shapeInfos.Clear(); } }
public override bool ConnectionAllowed(ref Vector3I otherBlockPos, ref Vector3I faceNormal, MyCubeBlockDefinition def) { if (this.MountPoints == null) { return(true); } Vector3I pos = (Vector3I)(base.Position + faceNormal); MySlimBlock cubeBlock = base.CubeGrid.GetCubeBlock(pos); MyBlockOrientation orientation = (cubeBlock == null) ? MyBlockOrientation.Identity : cubeBlock.Orientation; Vector3I position = base.Position; this.m_mpCache.Clear(); if ((cubeBlock != null) && (cubeBlock.FatBlock is MyFracturedBlock)) { this.m_mpCache.AddRange((cubeBlock.FatBlock as MyFracturedBlock).MountPoints); } else if ((cubeBlock != null) && (cubeBlock.FatBlock is MyCompoundCubeBlock)) { List <MyCubeBlockDefinition.MountPoint> outMountPoints = new List <MyCubeBlockDefinition.MountPoint>(); foreach (MySlimBlock block2 in (cubeBlock.FatBlock as MyCompoundCubeBlock).GetBlocks()) { MyCubeBlockDefinition.MountPoint[] buildProgressModelMountPoints = block2.BlockDefinition.GetBuildProgressModelMountPoints(block2.BuildLevelRatio); MyCubeGrid.TransformMountPoints(outMountPoints, block2.BlockDefinition, buildProgressModelMountPoints, ref block2.Orientation); this.m_mpCache.AddRange(outMountPoints); } } else if (cubeBlock != null) { MyCubeBlockDefinition.MountPoint[] buildProgressModelMountPoints = def.GetBuildProgressModelMountPoints(cubeBlock.BuildLevelRatio); MyCubeGrid.TransformMountPoints(this.m_mpCache, def, buildProgressModelMountPoints, ref orientation); } return(MyCubeGrid.CheckMountPointsForSide(this.MountPoints, ref base.SlimBlock.Orientation, ref position, base.BlockDefinition.Id, ref faceNormal, this.m_mpCache, ref orientation, ref pos, def.Id)); }
public CubeItemModel(MyObjectBuilder_CubeBlock cube, MyCubeBlockDefinition definition) { SetProperties(cube, definition); }
/// <summary> /// Returns true if this block can connect to another block (of the given type) in the given position. /// This is called only if CheckConnectionAllowed == true. /// If this method would return true for any position, set CheckConnectionAllowed to false to avoid /// unnecessary overhead. It is the block's responsibility to call CubeGrid.UpdateBlockNeighbors every time the /// conditions that are checked by this method change. /// </summary> public virtual bool ConnectionAllowed(ref Vector3I otherBlockPos, ref Vector3I faceNormal, MyCubeBlockDefinition def) { return(true); }
public static MyObjectBuilder_BlockNavigationDefinition GetDefaultObjectBuilder(MyCubeBlockDefinition blockDefinition) { MyObjectBuilder_BlockNavigationDefinition ob = m_tmpDefaultOb; m_tmpStringBuilder.Clear(); m_tmpStringBuilder.Append("Default_"); m_tmpStringBuilder.Append(blockDefinition.Size.X); m_tmpStringBuilder.Append("_"); m_tmpStringBuilder.Append(blockDefinition.Size.Y); m_tmpStringBuilder.Append("_"); m_tmpStringBuilder.Append(blockDefinition.Size.Z); ob.Id = new MyDefinitionId(typeof(MyObjectBuilder_BlockNavigationDefinition), m_tmpStringBuilder.ToString()); ob.Size = blockDefinition.Size; ob.Center = blockDefinition.Center; return(ob); }
public override void GetGridSpawnMaterials(MyCubeBlockDefinition definition, MatrixD worldMatrix, bool isStatic) { ClearRequiredMaterials(); GetMaterialsSimple(definition, m_materialList); }
public MyObjectBuilder_CubeBlock CreateCube(MyObjectBuilderType typeId, string subTypeId, MyCubeBlockDefinition definition) { return(_dataModel.CreateCube(typeId, subTypeId, definition)); }
public override void GetBlockAmountPlacementMaterials(MyCubeBlockDefinition definition, int amount) { ClearRequiredMaterials(); GetMaterialsSimple(definition, m_materialList, amount); }
protected static void AddFastBuildModelWithSubparts(ref MatrixD matrix, List <MatrixD> matrices, List <string> models, MyCubeBlockDefinition blockDefinition) { if (string.IsNullOrEmpty(blockDefinition.Model)) { return; } matrices.Add(matrix); models.Add(blockDefinition.Model); var data = new MyEntitySubpart.Data(); MyCubeBlockDefinition subBlockDefinition; MatrixD subBlockMatrix; Vector3 dummyPosition; MyModel modelData = MyModels.GetModelOnlyData(blockDefinition.Model); foreach (var dummy in modelData.Dummies) { if (MyEntitySubpart.GetSubpartFromDummy(blockDefinition.Model, dummy.Key, dummy.Value, ref data)) { MatrixD mCopy = MatrixD.Multiply(data.InitialTransform, matrix); matrices.Add(mCopy); models.Add(data.File); } else if (MyFakes.ENABLE_SUBBLOCKS && MyCubeBlock.GetSubBlockDataFromDummy(blockDefinition, dummy.Key, dummy.Value, false, out subBlockDefinition, out subBlockMatrix, out dummyPosition)) { if (!string.IsNullOrEmpty(subBlockDefinition.Model)) { // Repair subblock matrix to have int axes (because preview renderer does not allow such non integer rotation). Vector3I forward = Vector3I.Round(Vector3.DominantAxisProjection(subBlockMatrix.Forward)); Vector3I invForward = Vector3I.One - Vector3I.Abs(forward); Vector3I right = Vector3I.Round(Vector3.DominantAxisProjection((Vector3)subBlockMatrix.Right * invForward)); Vector3I up; Vector3I.Cross(ref right, ref forward, out up); subBlockMatrix.Forward = forward; subBlockMatrix.Right = right; subBlockMatrix.Up = up; MatrixD mCopy = MatrixD.Multiply(subBlockMatrix, matrix); matrices.Add(mCopy); models.Add(subBlockDefinition.Model); } } } }
public static float GetVolumeM3(this MyCubeBlockDefinition def) { return(def.Size.Size * def.CubeSize.GetVolumeM3()); }
public override void Init(MyObjectBuilder_EntityBase objectBuilder) { base.Init(objectBuilder); var ob = objectBuilder as MyObjectBuilder_FracturedPiece; if (ob.Shapes.Count == 0) { Debug.Fail("Invalid fracture piece! Dont call init without valid OB. Use pool/noinit."); throw new Exception("Fracture piece has no shapes."); //throwing exception, otherwise there is fp with null physics which can mess up somwhere else } foreach (var shape in ob.Shapes) { Render.AddPiece(shape.Name, Matrix.CreateFromQuaternion(shape.Orientation)); } OriginalBlocks.Clear(); foreach (var def in ob.BlockDefinitions) { string model = null; MyPhysicalModelDefinition mdef; if (MyDefinitionManager.Static.TryGetDefinition <MyPhysicalModelDefinition>(def, out mdef)) { model = mdef.Model; } MyCubeBlockDefinition blockDef = null; MyDefinitionManager.Static.TryGetDefinition <MyCubeBlockDefinition>(def, out blockDef); if (model == null) { Debug.Fail("Fracture piece Definition not found"); continue; } model = mdef.Model; if (VRage.Game.Models.MyModels.GetModelOnlyData(model).HavokBreakableShapes == null) { MyDestructionData.Static.LoadModelDestruction(model, mdef, Vector3.One); } var shape = VRage.Game.Models.MyModels.GetModelOnlyData(model).HavokBreakableShapes[0]; var si = new HkdShapeInstanceInfo(shape, null, null); m_children.Add(si); shape.GetChildren(m_children); if (blockDef != null && blockDef.BuildProgressModels != null) { foreach (var progress in blockDef.BuildProgressModels) { model = progress.File; if (VRage.Game.Models.MyModels.GetModelOnlyData(model).HavokBreakableShapes == null) { MyDestructionData.Static.LoadModelDestruction(model, blockDef, Vector3.One); } shape = VRage.Game.Models.MyModels.GetModelOnlyData(model).HavokBreakableShapes[0]; si = new HkdShapeInstanceInfo(shape, null, null); m_children.Add(si); shape.GetChildren(m_children); } } OriginalBlocks.Add(def); } m_shapes.AddRange(ob.Shapes); Vector3?offset = null; int shapeAtZero = 0; for (int i = 0; i < m_children.Count; i++) { var child = m_children[i]; Func <MyObjectBuilder_FracturedPiece.Shape, bool> x = s => s.Name == child.ShapeName; var result = m_shapes.Where(x); if (result.Count() > 0) { var found = result.First(); var m = Matrix.CreateFromQuaternion(found.Orientation); if (!offset.HasValue && found.Name == m_shapes[0].Name) { offset = child.GetTransform().Translation; shapeAtZero = m_shapeInfos.Count; } m.Translation = child.GetTransform().Translation; var si = new HkdShapeInstanceInfo(child.Shape.Clone(), m); if (found.Fixed) { si.Shape.SetFlagRecursively(HkdBreakableShape.Flags.IS_FIXED); } m_shapeInfos.Add(si); m_shapes.Remove(found); } else { child.GetChildren(m_children); } } if (m_shapeInfos.Count == 0) { List <string> shapesToLoad = new List <string>(); foreach (var obShape in ob.Shapes) { shapesToLoad.Add(obShape.Name); } var shapesStr = shapesToLoad.Aggregate((str1, str2) => str1 + ", " + str2); var blocksStr = OriginalBlocks.Aggregate("", (str, defId) => str + ", " + defId.ToString()); var failMsg = "No relevant shape was found for fractured piece. It was probably reexported and names changed. Shapes: " + shapesStr + ". Original blocks: " + shapesStr; Debug.Fail(failMsg); //HkdShapeInstanceInfo si = new HkdShapeInstanceInfo(new HkdBreakableShape((HkShape)new HkBoxShape(Vector3.One)), Matrix.Identity); //m_shapeInfos.Add(si); throw new Exception(failMsg); } if (offset.HasValue) { for (int i = 0; i < m_shapeInfos.Count; i++) { var m = m_shapeInfos[i].GetTransform(); m.Translation -= offset.Value; m_shapeInfos[i].SetTransform(ref m); } { var m = m_shapeInfos[shapeAtZero].GetTransform(); m.Translation = Vector3.Zero; m_shapeInfos[shapeAtZero].SetTransform(ref m); } } if (m_shapeInfos.Count > 0) { if (m_shapeInfos.Count == 1) { Shape = m_shapeInfos[0].Shape; } else { Shape = new HkdCompoundBreakableShape(null, m_shapeInfos); ((HkdCompoundBreakableShape)Shape).RecalcMassPropsFromChildren(); } Shape.SetStrenght(MyDestructionConstants.STRENGTH); var mp = new HkMassProperties(); Shape.BuildMassProperties(ref mp); Shape.SetChildrenParent(Shape); Physics = new MyPhysicsBody(this, RigidBodyFlag.RBF_DEBRIS); Physics.CanUpdateAccelerations = true; Physics.InitialSolverDeactivation = HkSolverDeactivation.High; Physics.CreateFromCollisionObject(Shape.GetShape(), Vector3.Zero, PositionComp.WorldMatrix, mp); Physics.BreakableBody = new HkdBreakableBody(Shape, Physics.RigidBody, MyPhysics.SingleWorld.DestructionWorld, (Matrix)PositionComp.WorldMatrix); Physics.BreakableBody.AfterReplaceBody += Physics.FracturedBody_AfterReplaceBody; if (OriginalBlocks.Count > 0) { MyPhysicalModelDefinition def; if (MyDefinitionManager.Static.TryGetDefinition <MyPhysicalModelDefinition>(OriginalBlocks[0], out def)) { Physics.MaterialType = def.PhysicalMaterial.Id.SubtypeId; } } var rigidBody = Physics.RigidBody; bool isFixed = MyDestructionHelper.IsFixed(Physics.BreakableBody.BreakableShape); if (isFixed) { rigidBody.UpdateMotionType(HkMotionType.Fixed); rigidBody.LinearVelocity = Vector3.Zero; rigidBody.AngularVelocity = Vector3.Zero; } Physics.Enabled = true; } m_children.Clear(); m_shapeInfos.Clear(); }
public static float GetDiameter(this MyCubeBlockDefinition def) { return(def.GetScaledSize().Dot(Vector3.Up)); }
public bool TryAdapt(MyDefinitionId itemDefinition) { this.m_physItem = null; this.m_blockDef = null; return(!MyDefinitionManager.Static.TryGetPhysicalItemDefinition(itemDefinition, out this.m_physItem) ? MyDefinitionManager.Static.TryGetCubeBlockDefinition(itemDefinition, out this.m_blockDef) : true); }
public override bool ConnectionAllowed(ref Vector3I otherBlockMinPos, ref Vector3I otherBlockMaxPos, ref Vector3I faceNormal, MyCubeBlockDefinition def) { return(ConnectionAllowedInternal(ref faceNormal, def)); }
private Dictionary <Type, Type> GetParentsAsDict(MyCubeBlockDefinition id) { return(GetParentsAsDict(GetParentsByType(id.GetType()))); }