コード例 #1
0
        public override void RecreatePhysics()
        {
            m_shapes.Clear();

            BoundingBox aabb = new BoundingBox(-Vector3.One / 2, Vector3.One / 2);
            var         positionComponent = Container.Get <MyPositionComponentBase>();

            foreach (var pair in m_detectorInteractiveObjects)
            {
                unsafe
                {
                    fixed(Vector3 *corner = m_detectorVertices)
                    aabb.GetCornersUnsafe(corner);
                }
                for (int i = 0; i < BoundingBox.CornerCount; i++)
                {
                    m_detectorVertices[i] = Vector3.Transform(m_detectorVertices[i], pair.Value.Matrix);
                }

                m_shapes.Add(new HkConvexVerticesShape(m_detectorVertices, BoundingBox.CornerCount, false, 0));
            }

            if (m_shapes.Count > 0)
            {
                var listShape = new HkListShape(m_shapes.GetInternalArray(), m_shapes.Count, HkReferencePolicy.TakeOwnership);
                m_detectorPhysics = new MyPhysicsBody(Container.Entity, RigidBodyFlag.RBF_DISABLE_COLLISION_RESPONSE);
                m_detectorPhysics.CreateFromCollisionObject((HkShape)listShape, Vector3.Zero, positionComponent.WorldMatrix);
                m_detectorPhysics.Enabled = true;
                listShape.Base.RemoveReference();
            }
        }
コード例 #2
0
        void CreateBreakableShapeFromCollisionShapes(MyModel model, Vector3 defaultSize, MyPhysicalModelDefinition modelDef)
        {
            // Make box half edge length of the grid so fractured block is smaller than not fractured, also good for compounds
            HkShape shape;

            if (model.HavokCollisionShapes != null && model.HavokCollisionShapes.Length > 0)
            {
                if (model.HavokCollisionShapes.Length > 1)
                {
                    shape = HkListShape.Create(model.HavokCollisionShapes, model.HavokCollisionShapes.Length, HkReferencePolicy.None);
                }
                else
                {
                    shape = model.HavokCollisionShapes[0];
                    shape.AddReference();
                }
            }
            else
            {
                //modelDef.Size * (modelDef.CubeSize == MyCubeSize.Large ? 2.5f : 0.25f)
                shape = new HkBoxShape(defaultSize * 0.5f, MyPerGameSettings.PhysicsConvexRadius);
            }

            var boxBreakable = new HkdBreakableShape(shape);

            boxBreakable.Name = model.AssetName;
            boxBreakable.SetMass(modelDef.Mass);
            model.HavokBreakableShapes = new HkdBreakableShape[] { boxBreakable };
            shape.RemoveReference();
        }
コード例 #3
0
        public override unsafe void RecreatePhysics()
        {
            if (this.m_detectorPhysics != null)
            {
                this.m_detectorPhysics.Close();
                this.m_detectorPhysics = null;
            }
            if (m_shapes == null)
            {
                m_shapes = new List <HkShape>();
            }
            if (m_detectorVertices == null)
            {
                m_detectorVertices = new Vector3[8];
            }
            m_shapes.Clear();
            BoundingBox             box   = new BoundingBox(-Vector3.One / 2f, Vector3.One / 2f);
            MyPositionComponentBase base2 = base.Container.Get <MyPositionComponentBase>();

            foreach (KeyValuePair <uint, DetectorData> pair in this.m_detectorInteractiveObjects)
            {
                Vector3[] pinned vectorArray;
                try
                {
                    Vector3 *vectorPtr;
                    if (((vectorArray = m_detectorVertices) == null) || (vectorArray.Length == 0))
                    {
                        vectorPtr = null;
                    }
                    else
                    {
                        vectorPtr = vectorArray;
                    }
                    box.GetCornersUnsafe(vectorPtr);
                }
                finally
                {
                    vectorArray = null;
                }
                int index = 0;
                while (true)
                {
                    if (index >= 8)
                    {
                        m_shapes.Add((HkShape) new HkConvexVerticesShape(m_detectorVertices, 8, false, 0f));
                        break;
                    }
                    m_detectorVertices[index] = Vector3.Transform(m_detectorVertices[index], pair.Value.Matrix);
                    index++;
                }
            }
            if (m_shapes.Count > 0)
            {
                HkListShape shape = new HkListShape(m_shapes.GetInternalArray <HkShape>(), m_shapes.Count, HkReferencePolicy.TakeOwnership);
                this.m_detectorPhysics = new MyPhysicsBody(base.Container.Entity, RigidBodyFlag.RBF_DISABLE_COLLISION_RESPONSE);
                HkMassProperties?massProperties = null;
                this.m_detectorPhysics.CreateFromCollisionObject((HkShape)shape, Vector3.Zero, base2.WorldMatrix, massProperties, 15);
                shape.Base.RemoveReference();
            }
        }
コード例 #4
0
        HkShape CreateShape(MyModel model, HkShapeType shapeType)
        {
            if (model.HavokCollisionShapes != null && model.HavokCollisionShapes.Length > 0)
            {
                HkShape sh;
                if (model.HavokCollisionShapes.Length == 1)
                {
                    sh = model.HavokCollisionShapes[0];
                    sh.AddReference();
                }
                else
                {
                    sh = new HkListShape(model.HavokCollisionShapes, HkReferencePolicy.None);
                }
                return(sh);
            }

            switch (shapeType)
            {
            case HkShapeType.Box:
                Vector3 halfExtents = (model.BoundingBox.Max - model.BoundingBox.Min) / 2;
                return(new HkBoxShape(Vector3.Max(halfExtents - 0.1f, new Vector3(0.05f)), 0.02f));

                break;

            case HkShapeType.Sphere:
                return(new HkSphereShape(model.BoundingSphere.Radius));

                break;

            case HkShapeType.ConvexVertices:
                m_tmpVerts.Clear();
                for (int i = 0; i < model.GetVerticesCount(); i++)
                {
                    m_tmpVerts.Add(model.GetVertex(i));
                }

                return(new HkConvexVerticesShape(m_tmpVerts.GetInternalArray(), m_tmpVerts.Count, true, 0.1f));

                break;
            }
            throw new InvalidOperationException("This shape is not supported");
        }
コード例 #5
0
        public static bool InitModelPhysics(this IMyEntity entity, RigidBodyFlag rbFlags = 2, int collisionLayers = 0x11)
        {
            MyEntity entity2 = entity as MyEntity;

            if (entity2.Closed)
            {
                return(false);
            }
            if ((entity2.ModelCollision.HavokCollisionShapes == null) || (entity2.ModelCollision.HavokCollisionShapes.Length == 0))
            {
                return(false);
            }
            List <HkShape> list  = entity2.ModelCollision.HavokCollisionShapes.ToList <HkShape>();
            HkListShape    shape = new HkListShape(list.GetInternalArray <HkShape>(), list.Count, HkReferencePolicy.None);

            entity2.Physics           = new MyPhysicsBody(entity2, rbFlags);
            entity2.Physics.IsPhantom = false;
            HkMassProperties?massProperties = null;

            (entity2.Physics as MyPhysicsBody).CreateFromCollisionObject((HkShape)shape, (Vector3)Vector3D.Zero, entity2.WorldMatrix, massProperties, collisionLayers);
            entity2.Physics.Enabled = true;
            shape.Base.RemoveReference();
            return(true);
        }
コード例 #6
0
 private void InitSubparts()
 {
     if (base.CubeGrid.CreatePhysics)
     {
         this.m_subparts.Clear();
         this.m_subpartIDs.Clear();
         this.m_currentOpening.Clear();
         this.m_currentSpeed.Clear();
         this.m_emitter.Clear();
         this.m_hingePosition.Clear();
         this.m_openingSequence.Clear();
         for (int i = 0; i < this.BlockDefinition.Subparts.Length; i++)
         {
             MyEntitySubpart item = this.LoadSubpartFromName(this.BlockDefinition.Subparts[i].Name);
             if (item != null)
             {
                 this.m_subparts.Add(item);
                 if (this.BlockDefinition.Subparts[i].PivotPosition != null)
                 {
                     this.m_hingePosition.Add(this.BlockDefinition.Subparts[i].PivotPosition.Value);
                 }
                 else
                 {
                     MyModelBone bone = item.Model.Bones.First <MyModelBone>(b => !b.Name.Contains("Root"));
                     if (bone != null)
                     {
                         this.m_hingePosition.Add(bone.Transform.Translation);
                     }
                 }
             }
         }
         int length = this.BlockDefinition.OpeningSequence.Length;
         for (int j = 0; j < length; j++)
         {
             if (string.IsNullOrEmpty(this.BlockDefinition.OpeningSequence[j].IDs))
             {
                 this.m_openingSequence.Add(this.BlockDefinition.OpeningSequence[j]);
                 this.m_subpartIDs.Add(this.BlockDefinition.OpeningSequence[j].ID);
             }
             else
             {
                 char[]   separator = new char[] { ',' };
                 string[] strArray  = this.BlockDefinition.OpeningSequence[j].IDs.Split(separator);
                 for (int m = 0; m < strArray.Length; m++)
                 {
                     char[]   chArray2  = new char[] { '-' };
                     string[] strArray2 = strArray[m].Split(chArray2);
                     if (strArray2.Length != 2)
                     {
                         this.m_openingSequence.Add(this.BlockDefinition.OpeningSequence[j]);
                         this.m_subpartIDs.Add(Convert.ToInt32(strArray[m]));
                     }
                     else
                     {
                         for (int n = Convert.ToInt32(strArray2[0]); n <= Convert.ToInt32(strArray2[1]); n++)
                         {
                             this.m_openingSequence.Add(this.BlockDefinition.OpeningSequence[j]);
                             this.m_subpartIDs.Add(n);
                         }
                     }
                 }
             }
         }
         for (int k = 0; k < this.m_openingSequence.Count; k++)
         {
             this.m_currentOpening.Add(0f);
             this.m_currentSpeed.Add(0f);
             this.m_emitter.Add(new MyEntity3DSoundEmitter(this, true, 1f));
             if (this.m_openingSequence[k].MaxOpen < 0f)
             {
                 MyObjectBuilder_AdvancedDoorDefinition.Opening local2 = this.m_openingSequence[k];
                 local2.MaxOpen *= -1f;
                 this.m_openingSequence[k].InvertRotation = !this.m_openingSequence[k].InvertRotation;
             }
         }
         this.m_sequenceCount = this.m_openingSequence.Count;
         this.m_subpartCount  = this.m_subparts.Count;
         Array.Resize <Matrix>(ref this.transMat, this.m_subpartCount);
         Array.Resize <Matrix>(ref this.rotMat, this.m_subpartCount);
         this.UpdateDoorPosition();
         if (base.CubeGrid.Projector == null)
         {
             foreach (MyEntitySubpart subpart2 in this.m_subparts)
             {
                 if (subpart2.Physics != null)
                 {
                     subpart2.Physics.Close();
                     subpart2.Physics = null;
                 }
                 if (((subpart2 != null) && ((subpart2.Physics == null) && (subpart2.ModelCollision.HavokCollisionShapes != null))) && (subpart2.ModelCollision.HavokCollisionShapes.Length != 0))
                 {
                     List <HkShape> list  = subpart2.ModelCollision.HavokCollisionShapes.ToList <HkShape>();
                     HkListShape    shape = new HkListShape(list.GetInternalArray <HkShape>(), list.Count, HkReferencePolicy.None);
                     subpart2.Physics           = new MyPhysicsBody(subpart2, RigidBodyFlag.RBF_UNLOCKED_SPEEDS | RigidBodyFlag.RBF_KINEMATIC);
                     subpart2.Physics.IsPhantom = false;
                     HkMassProperties?massProperties = null;
                     (subpart2.Physics as MyPhysicsBody).CreateFromCollisionObject((HkShape)shape, Vector3.Zero, base.WorldMatrix, massProperties, 15);
                     subpart2.Physics.Enabled = true;
                     shape.Base.RemoveReference();
                 }
             }
             base.CubeGrid.OnHavokSystemIDChanged -= new Action <int>(this.CubeGrid_HavokSystemIDChanged);
             base.CubeGrid.OnHavokSystemIDChanged += new Action <int>(this.CubeGrid_HavokSystemIDChanged);
             base.CubeGrid.OnPhysicsChanged       -= new Action <VRage.Game.Entity.MyEntity>(this.CubeGrid_OnPhysicsChanged);
             base.CubeGrid.OnPhysicsChanged       += new Action <VRage.Game.Entity.MyEntity>(this.CubeGrid_OnPhysicsChanged);
             if (base.CubeGrid.Physics != null)
             {
                 this.UpdateHavokCollisionSystemID(base.CubeGrid.GetPhysicsBody().HavokCollisionSystemID);
             }
         }
     }
 }
コード例 #7
0
ファイル: MyCubeBlock.cs プロジェクト: caomw/SpaceEngineers
        public void ReloadDetectors(bool refreshNetworks = true)
        {
            m_detectors.Clear();
            m_detectorInteractiveObjects.Clear();

            if (DetectorPhysics != null)
            {
                DetectorPhysics.Close();
            }

            List <HkShape> shapes = new List <HkShape>();
            BoundingBox    aabb   = new BoundingBox(-Vector3.One / 2, Vector3.One / 2);

            if (Render.GetModel() != null)
            {
                foreach (var dummy in Render.GetModel().Dummies)
                {
                    var          dummyLowerCaseKey = dummy.Key.ToLower();
                    const string DETECTOR_PREFIX   = "detector_";
                    if (dummyLowerCaseKey.StartsWith(DETECTOR_PREFIX) && dummyLowerCaseKey.Length > DETECTOR_PREFIX.Length)
                    {
                        String[] parts = dummyLowerCaseKey.Split('_');
                        if (parts.Length < 2)
                        {
                            continue;
                        }

                        var           dummyData = dummy.Value;
                        List <Matrix> matrices;
                        if (!m_detectors.TryGetValue(parts[1], out matrices))
                        {
                            matrices = new List <Matrix>();
                            m_detectors[parts[1]] = matrices;
                        }
                        matrices.Add(Matrix.Invert(dummyData.Matrix));

                        // TODO: this should be nicer
                        int shapeKey          = shapes.Count;
                        var interactiveObject = CreateInteractiveObject(parts[1], dummyLowerCaseKey, dummyData, shapeKey);
                        if (interactiveObject != null)
                        {
                            unsafe
                            {
                                fixed(Vector3 *corner = m_detectorVertices)
                                aabb.GetCornersUnsafe(corner);
                            }
                            for (int i = 0; i < BoundingBox.CornerCount; i++)
                            {
                                m_detectorVertices[i] = Vector3.Transform(m_detectorVertices[i], dummyData.Matrix);
                            }

                            shapes.Add(new HkConvexVerticesShape(m_detectorVertices, BoundingBox.CornerCount, false, 0));
                            m_detectorInteractiveObjects.Add(shapeKey, interactiveObject);
                        }
                    }
                }
            }

            if (shapes.Count > 0)
            {
                var listShape = new HkListShape(shapes.GetInternalArray(), shapes.Count, HkReferencePolicy.TakeOwnership);
                DetectorPhysics = new MyPhysicsBody(this, RigidBodyFlag.RBF_DISABLE_COLLISION_RESPONSE);
                DetectorPhysics.CreateFromCollisionObject((HkShape)listShape, Vector3.Zero, WorldMatrix);
                DetectorPhysics.Enabled = true;
                listShape.Base.RemoveReference();
            }

            /*
             * var inventoryBlock = this as IMyInventoryOwner;
             * if (refreshNetworks && inventoryBlock != null)
             * {
             *  CubeGrid.ConveyorSystem.Remove(inventoryBlock);
             *  CubeGrid.ConveyorSystem.Add(inventoryBlock);
             * }*/
        }
コード例 #8
0
        private void InitSubparts()
        {
            if (!CubeGrid.CreatePhysics)
            {
                return;
            }

            m_subparts.Clear();
            m_subpartIDs.Clear();
            m_currentOpening.Clear();
            m_currentSpeed.Clear();
            m_emitter.Clear();
            m_hingePosition.Clear();
            m_openingSequence.Clear();

            for (int i = 0; i < ((MyAdvancedDoorDefinition)BlockDefinition).Subparts.Length; i++)
            {
                MyEntitySubpart foundPart = LoadSubpartFromName(((MyAdvancedDoorDefinition)BlockDefinition).Subparts[i].Name);

                if (foundPart != null)
                {
                    m_subparts.Add(foundPart);

                    // save the Subparts hinge (pivot)
                    // if not defined...
                    if (((MyAdvancedDoorDefinition)BlockDefinition).Subparts[i].PivotPosition == null)
                    {
                        // ...try to get pivot from Model...
                        VRage.Import.MyModelBone bone = foundPart.Model.Bones.First(b => !b.Name.Contains("Root"));

                        if (bone != null)
                        {
                            m_hingePosition.Add(bone.Transform.Translation);
                        }
                    }
                    else // ...otherwise get from definition
                    {
                        m_hingePosition.Add((Vector3)((MyAdvancedDoorDefinition)BlockDefinition).Subparts[i].PivotPosition);
                    }
                }
            }

            // get the sequence count from definition
            int openSequenzCount = ((MyAdvancedDoorDefinition)BlockDefinition).OpeningSequence.Length;

            for (int i = 0; i < openSequenzCount; i++)
            {
                if (!String.IsNullOrEmpty(((MyAdvancedDoorDefinition)BlockDefinition).OpeningSequence[i].IDs))
                {
                    // if one sequence should be applied for multiple subparts (i.e. <IDs>1-3,4,6,8,9</IDs>
                    // add copies to m_openingSequence List

                    // split by comma
                    string[] tmp1 = ((MyAdvancedDoorDefinition)BlockDefinition).OpeningSequence[i].IDs.Split(',');

                    for (int j = 0; j < tmp1.Length; j++)
                    {
                        // split by minus
                        string[] tmp2 = tmp1[j].Split('-');

                        if (tmp2.Length == 2)
                        {
                            for (int k = Convert.ToInt32(tmp2[0]); k <= Convert.ToInt32(tmp2[1]); k++)
                            {
                                m_openingSequence.Add(((MyAdvancedDoorDefinition)BlockDefinition).OpeningSequence[i]);
                                m_subpartIDs.Add(k);
                            }
                        }
                        else
                        {
                            m_openingSequence.Add(((MyAdvancedDoorDefinition)BlockDefinition).OpeningSequence[i]);
                            m_subpartIDs.Add(Convert.ToInt32(tmp1[j]));
                        }
                    }
                }
                else
                {
                    m_openingSequence.Add(((MyAdvancedDoorDefinition)BlockDefinition).OpeningSequence[i]);
                    m_subpartIDs.Add(((MyAdvancedDoorDefinition)BlockDefinition).OpeningSequence[i].ID);
                }
            }

            for (int i = 0; i < m_openingSequence.Count; i++)
            {
                m_currentOpening.Add(0f);
                m_currentSpeed.Add(0f);
                m_emitter.Add(new MyEntity3DSoundEmitter(this, true));

                // make sure maxOpen is always positive and invert accordingly
                if (m_openingSequence[i].MaxOpen < 0f)
                {
                    m_openingSequence[i].MaxOpen       *= -1;
                    m_openingSequence[i].InvertRotation = !m_openingSequence[i].InvertRotation;
                }
            }

            m_sequenceCount = m_openingSequence.Count;
            m_subpartCount  = m_subparts.Count;

            Array.Resize(ref transMat, m_subpartCount);
            Array.Resize(ref rotMat, m_subpartCount);

            UpdateDoorPosition();

            if (CubeGrid.Projector != null)
            {
                //This is a projected grid, don't add collisions for subparts
                return;
            }

            foreach (MyEntitySubpart subpart in m_subparts)
            {
                subpart.Physics = null;
                if (subpart != null && subpart.Physics == null)
                {
                    if ((subpart.ModelCollision.HavokCollisionShapes != null) && (subpart.ModelCollision.HavokCollisionShapes.Length > 0))
                    {
                        List <HkShape> shapes    = subpart.ModelCollision.HavokCollisionShapes.ToList();
                        var            listShape = new HkListShape(shapes.GetInternalArray(), shapes.Count, HkReferencePolicy.None);
                        subpart.Physics           = new Engine.Physics.MyPhysicsBody(subpart, RigidBodyFlag.RBF_DOUBLED_KINEMATIC | RigidBodyFlag.RBF_KINEMATIC);
                        subpart.Physics.IsPhantom = false;
                        (subpart.Physics as MyPhysicsBody).CreateFromCollisionObject((HkShape)listShape, Vector3.Zero, WorldMatrix, null, MyPhysics.CollisionLayers.KinematicDoubledCollisionLayer);
                        subpart.Physics.Enabled = true;
                        listShape.Base.RemoveReference();
                    }
                }
            }

            CubeGrid.OnHavokSystemIDChanged -= CubeGrid_HavokSystemIDChanged;
            CubeGrid.OnHavokSystemIDChanged += CubeGrid_HavokSystemIDChanged;
            CubeGrid.OnPhysicsChanged       -= CubeGrid_OnPhysicsChanged;
            CubeGrid.OnPhysicsChanged       += CubeGrid_OnPhysicsChanged;
            if (CubeGrid.Physics != null)
            {
                UpdateHavokCollisionSystemID(CubeGrid.GetPhysicsBody().HavokCollisionSystemID);
            }
        }
コード例 #9
0
        public static bool TestBlockPlacementArea(
            MyCubeGrid targetGrid,
            ref MyGridPlacementSettings settings,
            MyBlockOrientation blockOrientation,
            MyCubeBlockDefinition blockDefinition,
            ref Vector3D translation,
            ref Quaternion rotation,
            ref Vector3 halfExtents,
            ref BoundingBoxD localAabb,
            out MyCubeGrid touchingGrid,
            MyEntity ignoredEntity = null,
            bool ignoreFracturedPieces = false)
        {
            touchingGrid = null;

            ProfilerShort.Begin("UseModelIntersection");
            if (blockDefinition != null && blockDefinition.UseModelIntersection)
            {
                var model = VRage.Game.Models.MyModels.GetModelOnlyData(blockDefinition.Model);
                if (model != null)
                {
                    bool newErrorFound;
                    model.CheckLoadingErrors(blockDefinition.Context, out newErrorFound);
                    if (newErrorFound)
                        MyDefinitionErrors.Add(blockDefinition.Context,
                            "There was error during loading of model, please check log file.", TErrorSeverity.Error);
                }

                if (model != null && model.HavokCollisionShapes != null)
                {
                    int shapeCount = model.HavokCollisionShapes.Length;
                    HkShape[] shapes = new HkShape[shapeCount];
                    for (int q = 0; q < shapeCount; ++q)
                    {
                        shapes[q] = model.HavokCollisionShapes[q];
                    }

                    var shape = new HkListShape(shapes, shapeCount, HkReferencePolicy.None);

                    Quaternion q2 = Quaternion.CreateFromForwardUp(Base6Directions.GetVector(blockOrientation.Forward), Base6Directions.GetVector(blockOrientation.Up));
                    rotation = rotation * q2;
                    MyPhysics.GetPenetrationsShape(shape, ref translation, ref rotation, m_physicsBoxQueryList, MyPhysics.CollisionLayers.CharacterCollisionLayer);

                    shape.Base.RemoveReference();
                }
                else
                {
                    Debug.Assert(m_physicsBoxQueryList.Count == 0, "List not cleared");
                    MyPhysics.GetPenetrationsBox(ref halfExtents, ref translation, ref rotation, m_physicsBoxQueryList, MyPhysics.CollisionLayers.CharacterCollisionLayer);
                }
            }
            else
            {
                Debug.Assert(m_physicsBoxQueryList.Count == 0, "List not cleared");
                MyPhysics.GetPenetrationsBox(ref halfExtents, ref translation, ref rotation, m_physicsBoxQueryList, MyPhysics.CollisionLayers.CharacterCollisionLayer);
            }
            m_lastQueryBox.HalfExtents = halfExtents;
            m_lastQueryTransform = MatrixD.CreateFromQuaternion(rotation);
            m_lastQueryTransform.Translation = translation;

            var worldMatrix = targetGrid != null ? targetGrid.WorldMatrix : MatrixD.Identity;
            ProfilerShort.BeginNextBlock("TestPlacementAreaInternal");
            bool result = TestPlacementAreaInternal(targetGrid, ref settings, blockDefinition, blockOrientation, ref localAabb, ignoredEntity, ref worldMatrix, out touchingGrid, ignoreFracturedPieces: ignoreFracturedPieces);
            ProfilerShort.End();
            return result;
        }
コード例 #10
0
        HkShape CreateShape(MyModel model, HkShapeType shapeType)
        {
            if (model.HavokCollisionShapes != null && model.HavokCollisionShapes.Length > 0)
            {
                HkShape sh;
                if (model.HavokCollisionShapes.Length == 1)
                {
                    sh = model.HavokCollisionShapes[0];
                    sh.AddReference();
                }
                else
                {
                    sh = new HkListShape(model.HavokCollisionShapes,HkReferencePolicy.None);
                }
                return sh;          
            }

            switch(shapeType)
            {
                case HkShapeType.Box:
                    Vector3 halfExtents = (model.BoundingBox.Max - model.BoundingBox.Min) / 2;
                    return new HkBoxShape(Vector3.Max(halfExtents - 0.1f, new Vector3(0.05f)), 0.02f);
                    break;

                case HkShapeType.Sphere:
                    return new HkSphereShape(model.BoundingSphere.Radius);
                    break;

                case HkShapeType.ConvexVertices:
                    m_tmpVerts.Clear();
                    for (int i = 0; i < model.GetVerticesCount(); i++)
                    {
                        m_tmpVerts.Add(model.GetVertex(i));
                    }

                    return new HkConvexVerticesShape(m_tmpVerts.GetInternalArray(), m_tmpVerts.Count, true, 0.1f);
                    break;
            }
            throw new InvalidOperationException("This shape is not supported");
        }
コード例 #11
0
        private void RecreateWeldedShape(HkShape thisShape)
        {
            m_tmpShapeList.Add(thisShape);

            if (WeldInfo.Children.Count == 0)
            {
                RigidBody.SetShape(thisShape);
                if (RigidBody2 != null)
                    RigidBody2.SetShape(thisShape);
            }
            else
            {
                foreach (var child in WeldInfo.Children)
                {
                    var transformShape = new HkTransformShape(child.WeldedRigidBody.GetShape(), ref child.WeldInfo.Transform);
                    HkShape.SetUserData(transformShape, child.WeldedRigidBody);
                    m_tmpShapeList.Add(transformShape);
                }
                var list = new HkListShape(m_tmpShapeList.ToArray(), HkReferencePolicy.None);
                RigidBody.SetShape(list);
                if (RigidBody2 != null)
                    RigidBody2.SetShape(list);
                list.Base.RemoveReference();
                m_tmpShapeList.Clear();
            }
        }
コード例 #12
0
        public override bool HandleInput()
        {
            bool handled = false;

            if (m_gridDebugInfo)
            {
                LineD      line = new LineD(MySector.MainCamera.Position, MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 1000);
                MyCubeGrid grid;
                Vector3I   cubePos;
                double     distance;
                if (MyCubeGrid.GetLineIntersection(ref line, out grid, out cubePos, out distance))
                {
                    var gridMatrix = grid.WorldMatrix;
                    var boxMatrix  = Matrix.CreateTranslation(cubePos * grid.GridSize) * gridMatrix;
                    var block      = grid.GetCubeBlock(cubePos);

                    MyRenderProxy.DebugDrawText2D(new Vector2(), cubePos.ToString(), Color.White, 0.7f);
                    MyRenderProxy.DebugDrawOBB(Matrix.CreateScale(new Vector3(grid.GridSize) + new Vector3(0.15f)) * boxMatrix, Color.Red.ToVector3(), 0.2f, true, true);

                    //int[, ,] bones = grid.Skeleton.AddCubeBones(cubePos);

                    //Vector3 closestBone = Vector3.Zero;
                    //Vector3I closestPoint = Vector3I.Zero;
                    //float closestPointDist = float.MaxValue;
                    //int closestBoneIndex = 0;

                    //for (int x = -1; x <= 1; x += 1)
                    //{
                    //    for (int y = -1; y <= 1; y += 1)
                    //    {
                    //        for (int z = -1; z <= 1; z += 1)
                    //        {
                    //            int boneIndex = bones[x + 1, y + 1, z + 1];
                    //            Vector3 bone = grid.Skeleton[boneIndex];

                    //            var pos = boxMatrix.Translation + new Vector3(grid.GridSize / 2) * new Vector3(x, y, z);
                    //            //MyRenderProxy.DebugDrawSphere(pos, 0.2f, Color.Blue.ToVector3(), 1.0f, false);
                    //            MyRenderProxy.DebugDrawText3D(pos, String.Format("{0:G2}, {1:G2}, {2:G2}", bone.X, bone.Y, bone.Z), Color.White, 0.5f, false);

                    //            var dist = MyUtils.GetPointLineDistance(ref line, ref pos);
                    //            if (dist < closestPointDist)
                    //            {
                    //                closestPointDist = dist;
                    //                closestPoint = new Vector3I(x, y, z);
                    //                closestBoneIndex = boneIndex;
                    //                closestBone = bone;

                    //            }
                    //        }
                    //    }
                    //}

                    //MyRenderProxy.DebugDrawText3D(boxMatrix.Translation + new Vector3(grid.GridSize / 2) * closestPoint * 1.0f, String.Format("{0:G2}, {1:G2}, {2:G2}", closestBone.X, closestBone.Y, closestBone.Z), Color.Red, 0.5f, false);
                    //var bonePos = grid.Skeleton[bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1]];
                    //MyRenderProxy.DebugDrawSphere(boxMatrix.Translation + new Vector3(grid.GridSize / 2) * closestPoint * 1.0f + bonePos, 0.5f, Color.Red.ToVector3(), 0.4f, true, true);

                    //if (input.IsNewKeyPressed(Keys.P) && block != null)
                    //{
                    //    if (input.IsAnyShiftKeyPressed())
                    //    {
                    //        grid.ResetBlockSkeleton(block);
                    //    }
                    //    else
                    //    {
                    //        grid.Skeleton[bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1]] = Vector3.Zero;
                    //        grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One);
                    //        //grid.SetBlockDirty(block);
                    //    }
                    //    handled = true;
                    //}

                    //// Move bones to center by 0.1f
                    //if (input.IsNewKeyPressed(Keys.OemOpenBrackets))
                    //{
                    //    int index = bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1];
                    //    grid.Skeleton[index] -= Vector3.Sign(grid.Skeleton[index]) * 0.1f;
                    //    grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One);
                    //    //grid.SetBlockDirty(block);
                    //    handled = true;
                    //}

                    //// Reduce max offset by 0.1f
                    //if (input.IsNewKeyPressed(Keys.OemCloseBrackets))
                    //{
                    //    int index = bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1];
                    //    var old = Vector3.Abs(grid.Skeleton[index]);
                    //    var max = new Vector3(Math.Max(Math.Max(old.X, old.Y), old.Z));
                    //    if (max.X > 0.1f)
                    //    {
                    //        grid.Skeleton[index] = Vector3.Clamp(grid.Skeleton[index], -max + 0.1f, max - 0.1f);
                    //    }
                    //    else
                    //    {
                    //        grid.Skeleton[index] = Vector3.Zero;
                    //    }
                    //    grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One);
                    //    //grid.SetBlockDirty(block);
                    //    handled = true;
                    //}
                }
            }

            if (MyInput.Static.IsAnyAltKeyPressed())
            {
                return(handled);
            }

            bool shift = MyInput.Static.IsAnyShiftKeyPressed();
            bool ctrl  = MyInput.Static.IsAnyCtrlKeyPressed();

            //if (input.IsNewKeyPressed(Keys.I))
            //{
            //    foreach (var grid in MyEntities.GetEntities().OfType<MyCubeGrid>())
            //    {
            //        foreach (var block in grid.GetBlocks().ToArray())
            //        {
            //            grid.DetectMerge(block.Min, block.Max);
            //        }
            //    }
            //    handled = true;
            //}

            // Disabled since it is common to have normal control bound to O key.
            // If you ever need this again, bind it to something more complicated, like key combination.
            //if (input.IsNewKeyPressed(Keys.O))
            //{
            //    m_gridDebugInfo = !m_gridDebugInfo;
            //    handled = true;
            //}

            //for (int i = 0; i <= 9; i++)
            //{
            //    if (MyInput.Static.IsNewKeyPressed((Keys)(((int)Keys.D0) + i)))
            //    {
            //        string name = "Slot" + i.ToString();
            //        if (ctrl)
            //        {
            //            MySession.Static.Name = name;
            //            MySession.Static.WorldID = MySession.Static.GetNewWorldId();
            //            MySession.Static.Save(name);
            //        }
            //        else if (shift)
            //        {
            //            var path = MyLocalCache.GetSessionSavesPath(name, false, false);
            //            if (System.IO.Directory.Exists(path))
            //            {
            //                MySession.Static.Unload();
            //                MySession.Static.Load(path);
            //            }
            //        }
            //        handled = true;
            //    }
            //}

            //if (MyInput.Static.IsNewKeyPressed(Keys.End))
            //{
            //    MyMeteorShower.MeteorWave(null);
            //}

            // Disabled for god sake!
            //if (MyInput.Static.IsNewKeyPressed(Keys.PageUp) && MyInput.Static.IsAnyCtrlKeyPressed())
            //{
            //    MyReloadTestComponent.Enabled = true;
            //}
            //if (MyInput.Static.IsNewKeyPressed(Keys.PageDown) && MyInput.Static.IsAnyCtrlKeyPressed())
            //{
            //    MyReloadTestComponent.Enabled = false;
            //}

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad6))
            {
                var view = MySession.Static.CameraController.GetViewMatrix();
                var inv  = Matrix.Invert(view);

                //MyPhysicalInventoryItem item = new MyPhysicalInventoryItem(100,
                var oreBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>("Stone");
                var item       = new MyPhysicalInventoryItem(1, oreBuilder);
                var obj        = MyFloatingObjects.Spawn(item, inv.Translation + inv.Forward * 1.0f, inv.Forward, inv.Up);
                obj.Physics.LinearVelocity = inv.Forward * 50;
            }

            if (false && MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9))
            {
                List <HkShape>       trShapes = new List <HkShape>();
                List <HkConvexShape> shapes   = new List <HkConvexShape>();
                List <Matrix>        matrices = new List <Matrix>();

                var         grid = new HkGridShape(2.5f, HkReferencePolicy.None);
                const short size = 50;
                for (short x = 0; x < size; x++)
                {
                    for (short y = 0; y < size; y++)
                    {
                        for (short z = 0; z < size; z++)
                        {
                            var box = new HkBoxShape(Vector3.One);
                            grid.AddShapes(new System.Collections.Generic.List <HkShape>()
                            {
                                box
                            }, new Vector3S(x, y, z), new Vector3S(x, y, z));
                            trShapes.Add(new HkConvexTranslateShape(box, new Vector3(x, y, z), HkReferencePolicy.None));
                            shapes.Add(box);
                            matrices.Add(Matrix.CreateTranslation(new Vector3(x, y, z)));
                        }
                    }
                }

                var emptyGeom = new HkGeometry(new List <Vector3>(), new List <int>());

                var list         = new HkListShape(trShapes.ToArray(), trShapes.Count, HkReferencePolicy.None);
                var compressedBv = new HkBvCompressedMeshShape(emptyGeom, shapes, matrices, HkWeldingType.None);
                var mopp         = new HkMoppBvTreeShape(list, HkReferencePolicy.None);

                HkShapeBuffer buf = new HkShapeBuffer();

                //HkShapeContainerIterator i = compressedBv.GetIterator(buf);
                //int count = 0; // will be 125000
                //while (i.IsValid)
                //{
                //    count++;
                //    i.Next();
                //}

                buf.Dispose();
                var info = new HkRigidBodyCinfo();
                info.Mass = 10;
                info.CalculateBoxInertiaTensor(Vector3.One, 10);
                info.MotionType  = HkMotionType.Dynamic;
                info.QualityType = HkCollidableQualityType.Moving;
                info.Shape       = compressedBv;
                var body = new HkRigidBody(info);

                //MyPhysics.HavokWorld.AddRigidBody(body);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad7))
            {
                foreach (var g in MyEntities.GetEntities().OfType <MyCubeGrid>())
                {
                    foreach (var s in g.CubeBlocks.Select(s => s.FatBlock).Where(s => s != null).OfType <MyMotorStator>())
                    {
                        if (s.Rotor != null)
                        {
                            var q = Quaternion.CreateFromAxisAngle(s.Rotor.WorldMatrix.Up, MathHelper.ToRadians(45));
                            s.Rotor.CubeGrid.WorldMatrix = MatrixD.CreateFromQuaternion(q) * s.Rotor.CubeGrid.WorldMatrix;
                        }
                    }
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad8))
            {
                var view = MySession.Static.CameraController.GetViewMatrix();
                var inv  = Matrix.Invert(view);

                var oreBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>("Stone");
                var obj        = new MyObjectBuilder_FloatingObject()
                {
                    Item = new MyObjectBuilder_InventoryItem()
                    {
                        PhysicalContent = oreBuilder, Amount = 1000
                    }
                };
                obj.PositionAndOrientation = new MyPositionAndOrientation(inv.Translation + 2.0f * inv.Forward, inv.Forward, inv.Up);
                obj.PersistentFlags        = MyPersistentEntityFlags2.InScene;
                var e = MyEntities.CreateFromObjectBuilderAndAdd(obj);
                e.Physics.LinearVelocity = Vector3.Normalize(inv.Forward) * 50.0f;
            }


            if (MyInput.Static.IsNewKeyPressed(MyKeys.Divide))
            {
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.Multiply))
            {
                MyDebugDrawSettings.ENABLE_DEBUG_DRAW = !MyDebugDrawSettings.ENABLE_DEBUG_DRAW;
                MyDebugDrawSettings.DEBUG_DRAW_STRUCTURAL_INTEGRITY = true;

                var grids = MyEntities.GetEntities().OfType <MyCubeGrid>();
                foreach (var g in grids)
                {
                    if (!g.IsStatic)// || g.GetBlocks().Count < 800) //to compute only castle
                    {
                        continue;
                    }

                    g.CreateStructuralIntegrity();
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad1))
            {
                var e = MyEntities.GetEntities().OfType <MyCubeGrid>().FirstOrDefault();
                if (e != null)
                {
                    e.Physics.RigidBody.MaxLinearVelocity = 1000;
                    if (e.Physics.RigidBody2 != null)
                    {
                        e.Physics.RigidBody2.MaxLinearVelocity = 1000;
                    }

                    e.Physics.LinearVelocity = new Vector3(1000, 0, 0);
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.Decimal))
            {
                MyPrefabManager.Static.SpawnPrefab("respawnship", MySector.MainCamera.Position, MySector.MainCamera.ForwardVector, MySector.MainCamera.UpVector);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.Multiply) && MyInput.Static.IsAnyShiftKeyPressed())
            {
                GC.Collect(2);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad5))
            {
                Thread.Sleep(250);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9))
            {
                var obj = MySession.Static.ControlledEntity != null ? MySession.Static.ControlledEntity.Entity : null;
                if (obj != null)
                {
                    const float dist = 5.0f;
                    obj.PositionComp.SetPosition(obj.PositionComp.GetPosition() + obj.WorldMatrix.Forward * dist);
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad4))
            {
                MyEntity invObject = MySession.Static.ControlledEntity as MyEntity;
                if (invObject != null && invObject.HasInventory)
                {
                    MyFixedPoint amount = 20000;

                    var         oreBuilder = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Ore>("Stone");
                    MyInventory inventory  = invObject.GetInventory(0) as MyInventory;
                    System.Diagnostics.Debug.Assert(inventory != null, "Null or unexpected type returned!");
                    inventory.AddItems(amount, oreBuilder);
                }

                handled = true;
            }

            //if (MyInput.Static.IsNewKeyPressed(Keys.NumPad8))
            //{
            //    var pos = MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 2;
            //    var grid = (MyObjectBuilder_CubeGrid)MyObjectBuilderSerializer.CreateNewObject(MyObjectBuilderTypeEnum.CubeGrid);
            //    grid.PositionAndOrientation = new MyPositionAndOrientation(pos, Vector3.Forward, Vector3.Up);
            //    grid.CubeBlocks = new List<MyObjectBuilder_CubeBlock>();
            //    grid.GridSizeEnum = MyCubeSize.Large;

            //    var block = new MyObjectBuilder_CubeBlock();
            //    block.BlockOrientation = MyBlockOrientation.Identity;
            //    block.Min = Vector3I.Zero;
            //    //var blockDefinition = Sandbox.Game.Managers.MyDefinitionManager.Static.GetCubeBlockDefinition(new CommonLib.ObjectBuilders.Definitions.MyDefinitionId(typeof(MyObjectBuilder_CubeBlock), "LargeBlockArmorBlock"));
            //    block.SubtypeName = "LargeBlockArmorBlock";
            //    grid.CubeBlocks.Add(block);
            //    grid.LinearVelocity = MySector.MainCamera.ForwardVector * 20;
            //    grid.PersistentFlags = MyPersistentEntityFlags2.Enabled | MyPersistentEntityFlags2.InScene;

            //    var x = MyEntities.CreateFromObjectBuilderAndAdd(grid);
            //}

            //if (MyInput.Static.IsNewKeyPressed(Keys.NumPad9))
            //{
            //    var pos = MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 2;
            //    var grid =  (MyObjectBuilder_CubeGrid)MyObjectBuilderSerializer.CreateNewObject(MyObjectBuilderTypeEnum.CubeGrid);
            //    grid.PositionAndOrientation = new MyPositionAndOrientation(pos, Vector3.Forward, Vector3.Up);
            //    grid.CubeBlocks = new List<MyObjectBuilder_CubeBlock>();
            //    grid.GridSizeEnum = MyCubeSize.Large;

            //    var block = new MyObjectBuilder_CubeBlock();
            //    block.BlockOrientation = MyBlockOrientation.Identity;
            //    block.Min = Vector3I.Zero;
            //    //var blockDefinition = Sandbox.Game.Managers.MyDefinitionManager.Static.GetCubeBlockDefinition(new CommonLib.ObjectBuilders.Definitions.MyDefinitionId(typeof(MyObjectBuilder_CubeBlock), "LargeBlockArmorBlock"));
            //    block.SubtypeName = "LargeBlockGyro";
            //    grid.CubeBlocks.Add(block);
            //    grid.LinearVelocity = MySector.MainCamera.ForwardVector * 20;
            //    grid.PersistentFlags = MyPersistentEntityFlags2.Enabled | MyPersistentEntityFlags2.InScene;

            //    var x = MyEntities.CreateFromObjectBuilderAndAdd(grid);
            //}

            if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.Delete))
            {
                int count = MyEntities.GetEntities().OfType <MyFloatingObject>().Count();
                foreach (var obj in MyEntities.GetEntities().OfType <MyFloatingObject>())
                {
                    if (obj == MySession.Static.ControlledEntity)
                    {
                        MySession.Static.SetCameraController(MyCameraControllerEnum.Spectator);
                    }
                    obj.Close();
                }
                handled = true;
            }

            if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.Decimal))
            {
                foreach (var obj in MyEntities.GetEntities())
                {
                    if (obj != MySession.Static.ControlledEntity && (MySession.Static.ControlledEntity == null || obj != MySession.Static.ControlledEntity.Entity.Parent) && obj != MyCubeBuilder.Static.FindClosestGrid())
                    {
                        obj.Close();
                    }
                }
                handled = true;
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9) || MyInput.Static.IsNewKeyPressed(MyKeys.NumPad5))
            {
                //MyCubeGrid.UserCollisions = input.IsNewKeyPressed(Keys.NumPad9);

                var body = MySession.Static.ControlledEntity.Entity.GetTopMostParent().Physics;
                if (body.RigidBody != null)
                {
                    //body.AddForce(Engine.Physics.MyPhysicsForceType.ADD_BODY_FORCE_AND_BODY_TORQUE, new Vector3(0, 0, 10 * body.Mass), null, null);
                    body.RigidBody.ApplyLinearImpulse(body.Entity.WorldMatrix.Forward * body.Mass * 2);
                }
                handled = true;
            }

            //if (input.IsNewKeyPressed(Keys.J) && input.IsAnyCtrlKeyPressed())
            //{
            //    MyGlobalInputComponent.CopyCurrentGridToClipboard();

            //    MyEntity addedEntity = MyGlobalInputComponent.PasteEntityFromClipboard();

            //    if (addedEntity != null)
            //    {
            //        Vector3 pos = addedEntity.GetPosition();
            //        pos.Z += addedEntity.WorldVolume.Radius * 1.5f;
            //        addedEntity.SetPosition(pos);
            //    }
            //    handled = true;
            //}

            if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.OemComma))
            {
                foreach (var e in MyEntities.GetEntities().OfType <MyFloatingObject>().ToArray())
                {
                    e.Close();
                }
            }

            return(handled);
        }
コード例 #13
0
        public override bool HandleInput()
        {
            bool handled = false;

            if (m_gridDebugInfo)
            {
                LineD line = new LineD(MySector.MainCamera.Position, MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 1000);
                MyCubeGrid grid;
                Vector3I cubePos;
                double distance;
                if (MyCubeGrid.GetLineIntersection(ref line, out grid, out cubePos, out distance))
                {
                    var gridMatrix = grid.WorldMatrix;
                    var boxMatrix = Matrix.CreateTranslation(cubePos * grid.GridSize) * gridMatrix;
                    var block = grid.GetCubeBlock(cubePos);

                    MyRenderProxy.DebugDrawText2D(new Vector2(), cubePos.ToString(), Color.White, 0.7f);
                    MyRenderProxy.DebugDrawOBB(Matrix.CreateScale(new Vector3(grid.GridSize) + new Vector3(0.15f)) * boxMatrix, Color.Red.ToVector3(), 0.2f, true, true);

                    //int[, ,] bones = grid.Skeleton.AddCubeBones(cubePos);

                    //Vector3 closestBone = Vector3.Zero;
                    //Vector3I closestPoint = Vector3I.Zero;
                    //float closestPointDist = float.MaxValue;
                    //int closestBoneIndex = 0;

                    //for (int x = -1; x <= 1; x += 1)
                    //{
                    //    for (int y = -1; y <= 1; y += 1)
                    //    {
                    //        for (int z = -1; z <= 1; z += 1)
                    //        {
                    //            int boneIndex = bones[x + 1, y + 1, z + 1];
                    //            Vector3 bone = grid.Skeleton[boneIndex];

                    //            var pos = boxMatrix.Translation + new Vector3(grid.GridSize / 2) * new Vector3(x, y, z);
                    //            //MyRenderProxy.DebugDrawSphere(pos, 0.2f, Color.Blue.ToVector3(), 1.0f, false);
                    //            MyRenderProxy.DebugDrawText3D(pos, String.Format("{0:G2}, {1:G2}, {2:G2}", bone.X, bone.Y, bone.Z), Color.White, 0.5f, false);

                    //            var dist = MyUtils.GetPointLineDistance(ref line, ref pos);
                    //            if (dist < closestPointDist)
                    //            {
                    //                closestPointDist = dist;
                    //                closestPoint = new Vector3I(x, y, z);
                    //                closestBoneIndex = boneIndex;
                    //                closestBone = bone;

                    //            }
                    //        }
                    //    }
                    //}

                    //MyRenderProxy.DebugDrawText3D(boxMatrix.Translation + new Vector3(grid.GridSize / 2) * closestPoint * 1.0f, String.Format("{0:G2}, {1:G2}, {2:G2}", closestBone.X, closestBone.Y, closestBone.Z), Color.Red, 0.5f, false);
                    //var bonePos = grid.Skeleton[bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1]];
                    //MyRenderProxy.DebugDrawSphere(boxMatrix.Translation + new Vector3(grid.GridSize / 2) * closestPoint * 1.0f + bonePos, 0.5f, Color.Red.ToVector3(), 0.4f, true, true);

                    //if (input.IsNewKeyPressed(Keys.P) && block != null)
                    //{
                    //    if (input.IsAnyShiftKeyPressed())
                    //    {
                    //        grid.ResetBlockSkeleton(block);
                    //    }
                    //    else
                    //    {
                    //        grid.Skeleton[bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1]] = Vector3.Zero;
                    //        grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One);
                    //        //grid.SetBlockDirty(block);
                    //    }
                    //    handled = true;
                    //}

                    //// Move bones to center by 0.1f
                    //if (input.IsNewKeyPressed(Keys.OemOpenBrackets))
                    //{
                    //    int index = bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1];
                    //    grid.Skeleton[index] -= Vector3.Sign(grid.Skeleton[index]) * 0.1f;
                    //    grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One);
                    //    //grid.SetBlockDirty(block);
                    //    handled = true;
                    //}

                    //// Reduce max offset by 0.1f
                    //if (input.IsNewKeyPressed(Keys.OemCloseBrackets))
                    //{
                    //    int index = bones[closestPoint.X + 1, closestPoint.Y + 1, closestPoint.Z + 1];
                    //    var old = Vector3.Abs(grid.Skeleton[index]);
                    //    var max = new Vector3(Math.Max(Math.Max(old.X, old.Y), old.Z));
                    //    if (max.X > 0.1f)
                    //    {
                    //        grid.Skeleton[index] = Vector3.Clamp(grid.Skeleton[index], -max + 0.1f, max - 0.1f);
                    //    }
                    //    else
                    //    {
                    //        grid.Skeleton[index] = Vector3.Zero;
                    //    }
                    //    grid.AddDirtyBone(cubePos, closestPoint + Vector3I.One);
                    //    //grid.SetBlockDirty(block);
                    //    handled = true;
                    //}
                }
            }

            if (MyInput.Static.IsAnyAltKeyPressed())
                return handled;

            bool shift = MyInput.Static.IsAnyShiftKeyPressed();
            bool ctrl = MyInput.Static.IsAnyCtrlKeyPressed();

            //if (input.IsNewKeyPressed(Keys.I))
            //{
            //    foreach (var grid in MyEntities.GetEntities().OfType<MyCubeGrid>())
            //    {
            //        foreach (var block in grid.GetBlocks().ToArray())
            //        {
            //            grid.DetectMerge(block.Min, block.Max);
            //        }
            //    }
            //    handled = true;
            //}

            // Disabled since it is common to have normal control bound to O key.
            // If you ever need this again, bind it to something more complicated, like key combination.
            //if (input.IsNewKeyPressed(Keys.O))
            //{
            //    m_gridDebugInfo = !m_gridDebugInfo;
            //    handled = true;
            //}

            //for (int i = 0; i <= 9; i++)
            //{
            //    if (MyInput.Static.IsNewKeyPressed((Keys)(((int)Keys.D0) + i)))
            //    {
            //        string name = "Slot" + i.ToString();
            //        if (ctrl)
            //        {
            //            MySession.Static.Name = name;
            //            MySession.Static.WorldID = MySession.GetNewWorldId();
            //            MySession.Static.Save(name);
            //        }
            //        else if (shift)
            //        {
            //            var path = MyLocalCache.GetSessionSavesPath(name, false, false);
            //            if (System.IO.Directory.Exists(path))
            //            {
            //                MySession.Static.Unload();
            //                MySession.Load(path);
            //            }
            //        }
            //        handled = true;
            //    }
            //}

            //if (MyInput.Static.IsNewKeyPressed(Keys.End))
            //{
            //    MyMeteorShower.MeteorWave(null);
            //}

            // Disabled for god sake!
            //if (MyInput.Static.IsNewKeyPressed(Keys.PageUp) && MyInput.Static.IsAnyCtrlKeyPressed())
            //{
            //    MyReloadTestComponent.Enabled = true;
            //}
            //if (MyInput.Static.IsNewKeyPressed(Keys.PageDown) && MyInput.Static.IsAnyCtrlKeyPressed())
            //{
            //    MyReloadTestComponent.Enabled = false;
            //}

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad6))
            {
                var view = MySession.Static.CameraController.GetViewMatrix();
                var inv = Matrix.Invert(view);

                //MyPhysicalInventoryItem item = new MyPhysicalInventoryItem(100, 
                var oreBuilder = MyObjectBuilderSerializer.CreateNewObject<MyObjectBuilder_Ore>("Stone");
                var item = new MyPhysicalInventoryItem(1, oreBuilder);
                var obj = MyFloatingObjects.Spawn(item, inv.Translation + inv.Forward * 1.0f, inv.Forward, inv.Up);
                obj.Physics.LinearVelocity = inv.Forward * 50;
            }

            if (false && MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9))
            {
                List<HkShape> trShapes = new List<HkShape>();
                List<HkConvexShape> shapes = new List<HkConvexShape>();
                List<Matrix> matrices = new List<Matrix>();

                var grid = new HkGridShape(2.5f, HkReferencePolicy.None);
                const short size = 50;
                for (short x = 0; x < size; x++)
                {
                    for (short y = 0; y < size; y++)
                    {
                        for (short z = 0; z < size; z++)
                        {
                            var box = new HkBoxShape(Vector3.One);
                            grid.AddShapes(new System.Collections.Generic.List<HkShape>() { box }, new Vector3S(x, y, z), new Vector3S(x, y, z));
                            trShapes.Add(new HkConvexTranslateShape(box, new Vector3(x, y, z), HkReferencePolicy.None));
                            shapes.Add(box);
                            matrices.Add(Matrix.CreateTranslation(new Vector3(x, y, z)));
                        }
                    }
                }

                var emptyGeom = new HkGeometry(new List<Vector3>(), new List<int>());

                var list = new HkListShape(trShapes.ToArray(), trShapes.Count, HkReferencePolicy.None);
                var compressedBv = new HkBvCompressedMeshShape(emptyGeom, shapes, matrices, HkWeldingType.None);
                var mopp = new HkMoppBvTreeShape(list, HkReferencePolicy.None);

                HkShapeBuffer buf = new HkShapeBuffer();

                //HkShapeContainerIterator i = compressedBv.GetIterator(buf);
                //int count = 0; // will be 125000
                //while (i.IsValid)
                //{
                //    count++;
                //    i.Next();
                //}                

                buf.Dispose();
                var info = new HkRigidBodyCinfo();
                info.Mass = 10;
                info.CalculateBoxInertiaTensor(Vector3.One, 10);
                info.MotionType = HkMotionType.Dynamic;
                info.QualityType = HkCollidableQualityType.Moving;
                info.Shape = compressedBv;
                var body = new HkRigidBody(info);

                //MyPhysics.HavokWorld.AddRigidBody(body);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad7))
            {
                foreach (var g in MyEntities.GetEntities().OfType<MyCubeGrid>())
                {
                    foreach (var s in g.CubeBlocks.Select(s => s.FatBlock).Where(s => s != null).OfType<MyMotorStator>())
                    {
                        if (s.Rotor != null)
                        {
                            var q = Quaternion.CreateFromAxisAngle(s.Rotor.WorldMatrix.Up, MathHelper.ToRadians(45));
                            s.Rotor.CubeGrid.WorldMatrix = MatrixD.CreateFromQuaternion(q) * s.Rotor.CubeGrid.WorldMatrix;
                        }
                    }
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad8))
            {
                var view = MySession.Static.CameraController.GetViewMatrix();
                var inv = Matrix.Invert(view);

                var oreBuilder = MyObjectBuilderSerializer.CreateNewObject<MyObjectBuilder_Ore>("Stone");
                var obj = new MyObjectBuilder_FloatingObject() { Item = new MyObjectBuilder_InventoryItem() { Content = oreBuilder, Amount = 1000 } };
                obj.PositionAndOrientation = new MyPositionAndOrientation(inv.Translation + 2.0f * inv.Forward, inv.Forward, inv.Up);
                obj.PersistentFlags = MyPersistentEntityFlags2.InScene;
                var e = MyEntities.CreateFromObjectBuilderAndAdd(obj);
                e.Physics.LinearVelocity = Vector3.Normalize(inv.Forward) * 50.0f;
            }


            if (MyInput.Static.IsNewKeyPressed(MyKeys.Divide))
            {
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.Multiply))
            {
                MyDebugDrawSettings.ENABLE_DEBUG_DRAW = !MyDebugDrawSettings.ENABLE_DEBUG_DRAW;
                MyStructuralIntegrity.Enabled = true;
                MyDebugDrawSettings.DEBUG_DRAW_STRUCTURAL_INTEGRITY = true;

                var grids = MyEntities.GetEntities().OfType<MyCubeGrid>();
                foreach (var g in grids)
                {
                    if (!g.IsStatic)// || g.GetBlocks().Count < 800) //to compute only castle
                        continue;

                    g.CreateStructuralIntegrity();
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad1))
            {
                var e = MyEntities.GetEntities().OfType<MyCubeGrid>().FirstOrDefault();
                if (e != null)
                {
                    e.Physics.RigidBody.MaxLinearVelocity = 1000;
                    if (e.Physics.RigidBody2 != null)
                        e.Physics.RigidBody2.MaxLinearVelocity = 1000;

                    e.Physics.LinearVelocity = new Vector3(1000, 0, 0);
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.Decimal))
            {
                MyPrefabManager.Static.SpawnPrefab("respawnship", MySector.MainCamera.Position, MySector.MainCamera.ForwardVector, MySector.MainCamera.UpVector);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.Multiply) && MyInput.Static.IsAnyShiftKeyPressed())
            {
                GC.Collect(2);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad5))
            {
                Thread.Sleep(250);
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9))
            {
                var obj = MySession.ControlledEntity != null ? MySession.ControlledEntity.Entity : null;
                if (obj != null)
                {
                    const float dist = 5.0f;
                    obj.PositionComp.SetPosition(obj.PositionComp.GetPosition() + obj.WorldMatrix.Forward * dist);
                }
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad4))
            {
                IMyInventoryOwner invObject = MySession.ControlledEntity as IMyInventoryOwner;
                if (invObject != null)
                {
                    MyFixedPoint amount = 20000;

                    var oreBuilder = MyObjectBuilderSerializer.CreateNewObject<MyObjectBuilder_Ore>("Stone");
                    MyInventory inventory = invObject.GetInventory(0);
                    inventory.AddItems(amount, oreBuilder);
                }

                handled = true;
            }

            //if (MyInput.Static.IsNewKeyPressed(Keys.NumPad8))
            //{
            //    var pos = MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 2;
            //    var grid = (MyObjectBuilder_CubeGrid)MyObjectBuilderSerializer.CreateNewObject(MyObjectBuilderTypeEnum.CubeGrid);
            //    grid.PositionAndOrientation = new MyPositionAndOrientation(pos, Vector3.Forward, Vector3.Up);
            //    grid.CubeBlocks = new List<MyObjectBuilder_CubeBlock>();
            //    grid.GridSizeEnum = MyCubeSize.Large;

            //    var block = new MyObjectBuilder_CubeBlock();
            //    block.BlockOrientation = MyBlockOrientation.Identity;
            //    block.Min = Vector3I.Zero;
            //    //var blockDefinition = Sandbox.Game.Managers.MyDefinitionManager.Static.GetCubeBlockDefinition(new CommonLib.ObjectBuilders.Definitions.MyDefinitionId(typeof(MyObjectBuilder_CubeBlock), "LargeBlockArmorBlock"));
            //    block.SubtypeName = "LargeBlockArmorBlock";
            //    grid.CubeBlocks.Add(block);
            //    grid.LinearVelocity = MySector.MainCamera.ForwardVector * 20;
            //    grid.PersistentFlags = MyPersistentEntityFlags2.Enabled | MyPersistentEntityFlags2.InScene;

            //    var x = MyEntities.CreateFromObjectBuilderAndAdd(grid);
            //}

            //if (MyInput.Static.IsNewKeyPressed(Keys.NumPad9))
            //{
            //    var pos = MySector.MainCamera.Position + MySector.MainCamera.ForwardVector * 2;
            //    var grid =  (MyObjectBuilder_CubeGrid)MyObjectBuilderSerializer.CreateNewObject(MyObjectBuilderTypeEnum.CubeGrid);
            //    grid.PositionAndOrientation = new MyPositionAndOrientation(pos, Vector3.Forward, Vector3.Up);
            //    grid.CubeBlocks = new List<MyObjectBuilder_CubeBlock>();
            //    grid.GridSizeEnum = MyCubeSize.Large;

            //    var block = new MyObjectBuilder_CubeBlock();
            //    block.BlockOrientation = MyBlockOrientation.Identity;
            //    block.Min = Vector3I.Zero;
            //    //var blockDefinition = Sandbox.Game.Managers.MyDefinitionManager.Static.GetCubeBlockDefinition(new CommonLib.ObjectBuilders.Definitions.MyDefinitionId(typeof(MyObjectBuilder_CubeBlock), "LargeBlockArmorBlock"));
            //    block.SubtypeName = "LargeBlockGyro";
            //    grid.CubeBlocks.Add(block);
            //    grid.LinearVelocity = MySector.MainCamera.ForwardVector * 20;
            //    grid.PersistentFlags = MyPersistentEntityFlags2.Enabled | MyPersistentEntityFlags2.InScene;

            //    var x = MyEntities.CreateFromObjectBuilderAndAdd(grid);
            //}

            if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.Delete))
            {
                int count = MyEntities.GetEntities().OfType<MyFloatingObject>().Count();
                foreach (var obj in MyEntities.GetEntities().OfType<MyFloatingObject>())
                {
                    if (obj == MySession.ControlledEntity)
                    {
                        MySession.SetCameraController(MyCameraControllerEnum.Spectator);
                    }
                    obj.Close();
                }
                handled = true;
            }

            if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.Decimal))
            {
                foreach (var obj in MyEntities.GetEntities())
                {
                    if (obj != MySession.ControlledEntity && (MySession.ControlledEntity == null || obj != MySession.ControlledEntity.Entity.Parent) && obj != MyCubeBuilder.Static.FindClosestGrid())
                        obj.Close();
                }
                handled = true;
            }

            if (MyInput.Static.IsNewKeyPressed(MyKeys.NumPad9) || MyInput.Static.IsNewKeyPressed(MyKeys.NumPad5))
            {
                //MyCubeGrid.UserCollisions = input.IsNewKeyPressed(Keys.NumPad9);

                var body = MySession.ControlledEntity.Entity.GetTopMostParent().Physics;
                if (body.RigidBody != null)
                {
                    //body.AddForce(Engine.Physics.MyPhysicsForceType.ADD_BODY_FORCE_AND_BODY_TORQUE, new Vector3(0, 0, 10 * body.Mass), null, null);
                    body.RigidBody.ApplyLinearImpulse(body.Entity.WorldMatrix.Forward * body.Mass * 2);
                }
                handled = true;
            }

            //if (input.IsNewKeyPressed(Keys.J) && input.IsAnyCtrlKeyPressed())
            //{
            //    MyGlobalInputComponent.CopyCurrentGridToClipboard();

            //    MyEntity addedEntity = MyGlobalInputComponent.PasteEntityFromClipboard();

            //    if (addedEntity != null)
            //    {
            //        Vector3 pos = addedEntity.GetPosition();
            //        pos.Z += addedEntity.WorldVolume.Radius * 1.5f;
            //        addedEntity.SetPosition(pos);
            //    }
            //    handled = true;
            //}

            if (MyInput.Static.IsAnyCtrlKeyPressed() && MyInput.Static.IsNewKeyPressed(MyKeys.OemComma))
            {
                foreach (var e in MyEntities.GetEntities().OfType<MyFloatingObject>().ToArray())
                    e.Close();
            }
            
            return handled;
        }
コード例 #14
0
        public static bool TestBlockPlacementArea(
            MyCubeGrid targetGrid,
            ref MyGridPlacementSettings settings,
            MyBlockOrientation blockOrientation,
            MyCubeBlockDefinition blockDefinition,
            ref Vector3D translation,
            ref Quaternion rotation,
            ref Vector3 halfExtents,
            ref BoundingBoxD localAabb,
            out MyCubeGrid touchingGrid,
            MyEntity ignoredEntity = null)
        {
            touchingGrid = null;

            if (blockDefinition != null && blockDefinition.UseModelIntersection)
            {
                var model = MyModels.GetModelOnlyData(blockDefinition.Model);
                if(model != null)
                    model.CheckLoadingErrors(blockDefinition.Context);

                if (model != null && model.HavokCollisionShapes != null)
                {
                    int shapeCount = model.HavokCollisionShapes.Length;
                    HkShape[] shapes = new HkShape[shapeCount];
                    for (int q = 0; q < shapeCount; ++q)
                    {
                        shapes[q] = model.HavokCollisionShapes[q];
                    }

                    var shape = new HkListShape(shapes, shapeCount, HkReferencePolicy.None);

                    Quaternion q2 = Quaternion.CreateFromForwardUp(Base6Directions.GetVector(blockOrientation.Forward), Base6Directions.GetVector(blockOrientation.Up));
                    rotation = rotation * q2;
                    MyPhysics.GetPenetrationsShape(shape, ref translation, ref rotation, m_physicsBoxQueryList, MyPhysics.CharacterCollisionLayer);

                    shape.Base.RemoveReference();
                }
                else
                {
                    Debug.Assert(m_physicsBoxQueryList.Count == 0, "List not cleared");
                    MyPhysics.GetPenetrationsBox(ref halfExtents, ref translation, ref rotation, m_physicsBoxQueryList, MyPhysics.CharacterCollisionLayer);
                }
            }
            else
            {
                Debug.Assert(m_physicsBoxQueryList.Count == 0, "List not cleared");
                MyPhysics.GetPenetrationsBox(ref halfExtents, ref translation, ref rotation, m_physicsBoxQueryList, MyPhysics.CharacterCollisionLayer);
            }
            m_lastQueryBox.HalfExtents = halfExtents;
            m_lastQueryTransform = MatrixD.CreateFromQuaternion(rotation);
            m_lastQueryTransform.Translation = translation;

            var worldMatrix = targetGrid != null ? targetGrid.WorldMatrix : MatrixD.Identity;
            return TestPlacementAreaInternal(targetGrid, ref settings, blockDefinition, blockOrientation, ref localAabb, ignoredEntity, ref worldMatrix, out touchingGrid);
        }
コード例 #15
0
        void CollectBlock(MySlimBlock block, MyPhysicsOption physicsOption, IDictionary <Vector3I, HkMassElement> massResults, bool allowSegmentation = true)
        {
            if (!block.HasPhysics)
            {
                return;
            }

            if (massResults != null)
            {
                AddMass(block, massResults);
            }

            if (block.BlockDefinition.BlockTopology == MyBlockTopology.Cube)
            {
                Debug.Assert(block.Min == block.Max, "Calculation assume that cube blocks have size 1x1x1");
                var cubeTopology = block.BlockDefinition.CubeDefinition.CubeTopology;
                if (MyFakes.ENABLE_SIMPLE_GRID_PHYSICS)
                {
                    physicsOption = MyPhysicsOption.Box;
                }
                else if ((cubeTopology == MyCubeTopology.Box) && block.CubeGrid.Skeleton.IsDeformed(block.Min, 0.05f, block.CubeGrid, false))
                {
                    physicsOption = MyPhysicsOption.Convex;
                }

                switch (physicsOption)
                {
                case MyPhysicsOption.Box:
                    AddBoxes(block);
                    break;

                case MyPhysicsOption.Convex:
                    AddConvexShape(block, true);
                    break;
                }
            }
            else
            {
                if (physicsOption != MyPhysicsOption.None)
                {
                    var havokShapes = block.FatBlock.ModelCollision.HavokCollisionShapes;

                    if ((havokShapes != null && havokShapes.Length > 0) && !MyFakes.ENABLE_SIMPLE_GRID_PHYSICS)
                    {
                        // first set of shapes goes into block.Position
                        Vector3 blockPos;
                        if (block.FatBlock.ModelCollision.ExportedWrong)
                        {
                            blockPos = block.Position * block.CubeGrid.GridSize;
                        }
                        else
                        {
                            blockPos = block.FatBlock.PositionComp.LocalMatrix.Translation;
                        }
                        HkShape[]  shapes = block.FatBlock.ModelCollision.HavokCollisionShapes;
                        Quaternion blockOrientation;
                        block.Orientation.GetQuaternion(out blockOrientation);

                        if (shapes.Length == 1 && shapes[0].ShapeType == HkShapeType.List)
                        {
                            HkListShape list = (HkListShape)shapes[0];
                            for (int i = 0; i < list.TotalChildrenCount; i++)
                            {
                                HkShape child = list.GetChildByIndex(i);
                                System.Diagnostics.Debug.Assert(child.IsConvex, "Children in the list must be convex!");
                                Shapes.Add(new HkConvexTransformShape((HkConvexShape)child, ref blockPos, ref blockOrientation, ref Vector3.One, HkReferencePolicy.None));
                            }
                        }
                        else
                        if (shapes.Length == 1 && shapes[0].ShapeType == HkShapeType.Mopp)
                        {
                            HkMoppBvTreeShape list = (HkMoppBvTreeShape)shapes[0];
                            for (int i = 0; i < list.ShapeCollection.ShapeCount; i++)
                            {
                                HkShape child = list.ShapeCollection.GetShape((uint)i, null);
                                System.Diagnostics.Debug.Assert(child.IsConvex, "Children in the list must be convex!");
                                Shapes.Add(new HkConvexTransformShape((HkConvexShape)child, ref blockPos, ref blockOrientation, ref Vector3.One, HkReferencePolicy.None));
                            }
                        }
                        else
                        {
                            for (int i = 0; i < shapes.Length; i++)
                            {
                                Shapes.Add(new HkConvexTransformShape((HkConvexShape)shapes[i], ref blockPos, ref blockOrientation, ref Vector3.One, HkReferencePolicy.None));
                            }
                        }
                        ShapeInfos.Add(new ShapeInfo()
                        {
                            Count = shapes.Length, Min = block.Min, Max = block.Max
                        });
                    }
                    else
                    {
                        // This will add boxes
                        for (int x = block.Min.X; x <= block.Max.X; x++)
                        {
                            for (int y = block.Min.Y; y <= block.Max.Y; y++)
                            {
                                for (int z = block.Min.Z; z <= block.Max.Z; z++)
                                {
                                    var pos = new Vector3I(x, y, z);
                                    // NOTE: Disabled because it's not visually represented
                                    //if (block.CubeGrid.Skeleton.IsDeformed(pos, 0.05f) && !MyFakes.ENABLE_SIMPLE_GRID_PHYSICS)
                                    //{
                                    //    AddConvexShape(pos, block.CubeGrid.Skeleton, false);
                                    //}
                                    //else

                                    if (allowSegmentation)
                                    {
                                        m_tmpCubes.Add(pos);
                                    }
                                    else
                                    {
                                        Vector3 min = pos * block.CubeGrid.GridSize - new Vector3(block.CubeGrid.GridSize / 2.0f);
                                        Vector3 max = pos * block.CubeGrid.GridSize + new Vector3(block.CubeGrid.GridSize / 2.0f);
                                        AddBox(pos, pos, ref min, ref max);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
コード例 #16
0
        private void InitSubparts()
        {
            if (!CubeGrid.CreatePhysics)
                return;

            m_subparts.Clear();
            m_subpartIDs.Clear();
            m_currentOpening.Clear();
            m_currentSpeed.Clear();
            m_emitter.Clear();
            m_hingePosition.Clear();
            m_openingSequence.Clear();

            for (int i = 0; i < ((MyAdvancedDoorDefinition)BlockDefinition).Subparts.Length; i++)
            {
                MyEntitySubpart foundPart = LoadSubpartFromName(((MyAdvancedDoorDefinition)BlockDefinition).Subparts[i].Name);

                if (foundPart != null)
                {
                    m_subparts.Add(foundPart);

                    // save the Subparts hinge (pivot)
                    // if not defined...
                    if (((MyAdvancedDoorDefinition)BlockDefinition).Subparts[i].PivotPosition == null)
                    {
                        // ...try to get pivot from Model...
                        VRage.Import.MyModelBone bone = foundPart.Model.Bones.First(b => !b.Name.Contains("Root"));

                        if (bone != null)
                            m_hingePosition.Add(bone.Transform.Translation);
                    }
                    else // ...otherwise get from definition
                    {
                        m_hingePosition.Add((Vector3)((MyAdvancedDoorDefinition)BlockDefinition).Subparts[i].PivotPosition);
                    }
                }
            }

            // get the sequence count from definition
            int openSequenzCount = ((MyAdvancedDoorDefinition)BlockDefinition).OpeningSequence.Length;
            
            for (int i = 0; i < openSequenzCount; i++)
            {
                if(!String.IsNullOrEmpty(((MyAdvancedDoorDefinition)BlockDefinition).OpeningSequence[i].IDs))
                {
                    // if one sequence should be applied for multiple subparts (i.e. <IDs>1-3,4,6,8,9</IDs>
                    // add copies to m_openingSequence List

                    // split by comma
                    string[] tmp1 = ((MyAdvancedDoorDefinition)BlockDefinition).OpeningSequence[i].IDs.Split(',');
                    
                    for (int j = 0; j < tmp1.Length; j++)
                    {
                        // split by minus
                        string[] tmp2 = tmp1[j].Split('-');

                        if (tmp2.Length == 2)
                        {
                            for(int k = Convert.ToInt32(tmp2[0]); k <= Convert.ToInt32(tmp2[1]); k++)
                            {
                                m_openingSequence.Add(((MyAdvancedDoorDefinition)BlockDefinition).OpeningSequence[i]);
                                m_subpartIDs.Add(k);
                            }
                        }
                        else
                        {
                            m_openingSequence.Add(((MyAdvancedDoorDefinition)BlockDefinition).OpeningSequence[i]);
                            m_subpartIDs.Add(Convert.ToInt32(tmp1[j]));
                        }
                    }
                }
                else
                {
                    m_openingSequence.Add(((MyAdvancedDoorDefinition)BlockDefinition).OpeningSequence[i]);
                    m_subpartIDs.Add(((MyAdvancedDoorDefinition)BlockDefinition).OpeningSequence[i].ID);
                }
            }

            for (int i = 0; i < m_openingSequence.Count; i++)
            {
                m_currentOpening.Add(0f);
                m_currentSpeed.Add(0f);
                m_emitter.Add(new MyEntity3DSoundEmitter(this, true));

                // make sure maxOpen is always positive and invert accordingly
                if (m_openingSequence[i].MaxOpen < 0f)
                {
                    m_openingSequence[i].MaxOpen *= -1;
                    m_openingSequence[i].InvertRotation = !m_openingSequence[i].InvertRotation;
                }
            }

            m_sequenceCount = m_openingSequence.Count;
            m_subpartCount = m_subparts.Count;

            Array.Resize(ref transMat, m_subpartCount);
            Array.Resize(ref rotMat, m_subpartCount);

            UpdateDoorPosition();

            if (CubeGrid.Projector != null)
            {
                //This is a projected grid, don't add collisions for subparts
                return;
            }

            foreach (MyEntitySubpart subpart in m_subparts)
            {
                subpart.Physics = null;
                if (subpart != null && subpart.Physics == null)
                {
                    if ((subpart.ModelCollision.HavokCollisionShapes != null) && (subpart.ModelCollision.HavokCollisionShapes.Length > 0))
                    {
                        List<HkShape> shapes = subpart.ModelCollision.HavokCollisionShapes.ToList();
                        var listShape = new HkListShape(shapes.GetInternalArray(), shapes.Count, HkReferencePolicy.None);
                        subpart.Physics = new Engine.Physics.MyPhysicsBody(subpart, RigidBodyFlag.RBF_DOUBLED_KINEMATIC | RigidBodyFlag.RBF_KINEMATIC);
                        subpart.Physics.IsPhantom = false;
                        (subpart.Physics as MyPhysicsBody).CreateFromCollisionObject((HkShape)listShape, Vector3.Zero, WorldMatrix, null, MyPhysics.CollisionLayers.KinematicDoubledCollisionLayer);
                        subpart.Physics.Enabled = true;
                        listShape.Base.RemoveReference();
                    }
                }
            }

            CubeGrid.OnHavokSystemIDChanged -= CubeGrid_HavokSystemIDChanged;
            CubeGrid.OnHavokSystemIDChanged += CubeGrid_HavokSystemIDChanged;
            CubeGrid.OnPhysicsChanged -= CubeGrid_OnPhysicsChanged;
            CubeGrid.OnPhysicsChanged += CubeGrid_OnPhysicsChanged;
            if (CubeGrid.Physics != null)
                UpdateHavokCollisionSystemID(CubeGrid.GetPhysicsBody().HavokCollisionSystemID);
        }
コード例 #17
0
 private void CollectBlock(MySlimBlock block, MyPhysicsOption physicsOption, IDictionary <Vector3I, HkMassElement> massResults, bool allowSegmentation = true)
 {
     if (block.BlockDefinition.HasPhysics && (block.CubeGrid != null))
     {
         if (massResults != null)
         {
             this.AddMass(block, massResults);
         }
         if (block.BlockDefinition.BlockTopology == MyBlockTopology.Cube)
         {
             MyCubeTopology topology = (block.BlockDefinition.CubeDefinition != null) ? block.BlockDefinition.CubeDefinition.CubeTopology : MyCubeTopology.Box;
             if (MyFakes.ENABLE_SIMPLE_GRID_PHYSICS)
             {
                 physicsOption = MyPhysicsOption.Box;
             }
             else if (topology == MyCubeTopology.Box)
             {
                 if (!block.ShowParts)
                 {
                     physicsOption = MyPhysicsOption.Box;
                 }
                 else if ((block.BlockDefinition.CubeDefinition != null) && block.CubeGrid.Skeleton.IsDeformed(block.Min, 0.05f, block.CubeGrid, false))
                 {
                     physicsOption = MyPhysicsOption.Convex;
                 }
             }
             if (physicsOption == MyPhysicsOption.Box)
             {
                 this.AddBoxes(block);
             }
             else if (physicsOption == MyPhysicsOption.Convex)
             {
                 this.AddConvexShape(block, block.ShowParts);
             }
         }
         else if (physicsOption != MyPhysicsOption.None)
         {
             HkShape[] havokCollisionShapes = null;
             if (block.FatBlock != null)
             {
                 havokCollisionShapes = block.FatBlock.ModelCollision.HavokCollisionShapes;
             }
             if (((havokCollisionShapes != null) && (havokCollisionShapes.Length != 0)) && !MyFakes.ENABLE_SIMPLE_GRID_PHYSICS)
             {
                 Vector3    translation;
                 Quaternion quaternion;
                 if (block.FatBlock.ModelCollision.ExportedWrong)
                 {
                     translation = (Vector3)(block.Position * block.CubeGrid.GridSize);
                 }
                 else
                 {
                     translation = block.FatBlock.PositionComp.LocalMatrix.Translation;
                 }
                 HkShape[] havokCollisionShapes = block.FatBlock.ModelCollision.HavokCollisionShapes;
                 block.Orientation.GetQuaternion(out quaternion);
                 Vector3 scale = Vector3.One * block.FatBlock.ModelCollision.ScaleFactor;
                 if ((havokCollisionShapes.Length == 1) && (havokCollisionShapes[0].ShapeType == HkShapeType.List))
                 {
                     HkListShape shape = (HkListShape)havokCollisionShapes[0];
                     for (int i = 0; i < shape.TotalChildrenCount; i++)
                     {
                         HkShape childByIndex = shape.GetChildByIndex(i);
                         this.Shapes.Add((HkShape) new HkConvexTransformShape((HkConvexShape)childByIndex, ref translation, ref quaternion, ref scale, HkReferencePolicy.None));
                     }
                 }
                 else if ((havokCollisionShapes.Length != 1) || (havokCollisionShapes[0].ShapeType != HkShapeType.Mopp))
                 {
                     for (int i = 0; i < havokCollisionShapes.Length; i++)
                     {
                         this.Shapes.Add((HkShape) new HkConvexTransformShape((HkConvexShape)havokCollisionShapes[i], ref translation, ref quaternion, ref scale, HkReferencePolicy.None));
                     }
                 }
                 else
                 {
                     HkMoppBvTreeShape shape3 = (HkMoppBvTreeShape)havokCollisionShapes[0];
                     int num2 = 0;
                     while (true)
                     {
                         HkShapeCollection shapeCollection = shape3.ShapeCollection;
                         if (num2 >= shapeCollection.ShapeCount)
                         {
                             break;
                         }
                         HkShape shape = shape3.ShapeCollection.GetShape((uint)num2, null);
                         this.Shapes.Add((HkShape) new HkConvexTransformShape((HkConvexShape)shape, ref translation, ref quaternion, ref scale, HkReferencePolicy.None));
                         num2++;
                     }
                 }
                 ShapeInfo item = new ShapeInfo {
                     Count = havokCollisionShapes.Length,
                     Min   = block.Min,
                     Max   = block.Max
                 };
                 this.ShapeInfos.Add(item);
             }
             else
             {
                 int x = block.Min.X;
                 while (x <= block.Max.X)
                 {
                     int y = block.Min.Y;
                     while (true)
                     {
                         if (y > block.Max.Y)
                         {
                             x++;
                             break;
                         }
                         int z = block.Min.Z;
                         while (true)
                         {
                             if (z > block.Max.Z)
                             {
                                 y++;
                                 break;
                             }
                             Vector3I item = new Vector3I(x, y, z);
                             if (allowSegmentation)
                             {
                                 this.m_tmpCubes.Add(item);
                             }
                             else
                             {
                                 Vector3 min = ((Vector3)(item * block.CubeGrid.GridSize)) - new Vector3(block.CubeGrid.GridSize / 2f);
                                 Vector3 max = (item * block.CubeGrid.GridSize) + new Vector3(block.CubeGrid.GridSize / 2f);
                                 this.AddBox(item, item, ref min, ref max);
                             }
                             z++;
                         }
                     }
                 }
             }
         }
     }
 }