public static void DrawCollisionShape(HkShape shape, MatrixD worldMatrix, float alpha, ref int shapeIndex, string customText = null, bool isPhantom = false)
        {
            var color = GetShapeColor(shape.ShapeType, ref shapeIndex, isPhantom);
            if (isPhantom) alpha *= alpha;
            color.A = (byte)(alpha * 255);

            bool shaded = true;

            float expandSize = 0.02f;
            float expandRatio = 1.035f;

            bool drawCustomText = false;

            switch (shape.ShapeType)
            {
                case HkShapeType.Sphere:
                    {
                        var sphere = (HkSphereShape)shape;
                        float radius = sphere.Radius;

                        VRageRender.MyRenderProxy.DebugDrawSphere(worldMatrix.Translation, radius, color, alpha, true, shaded);

                        if (isPhantom)
                        {
                            VRageRender.MyRenderProxy.DebugDrawSphere(worldMatrix.Translation, radius, color, 1.0f, true, false);
                            VRageRender.MyRenderProxy.DebugDrawSphere(worldMatrix.Translation, radius, color, 1.0f, true, false, false);
                        }

                        drawCustomText = true;
                        break;
                    }

                case HkShapeType.Capsule:
                    {
                        // Sphere and OBB to show cylinder space
                        var capsule = (HkCapsuleShape)shape;
                        Vector3D vertexA = Vector3.Transform(capsule.VertexA, worldMatrix);
                        Vector3D vertexB = Vector3.Transform(capsule.VertexB, worldMatrix);
                        VRageRender.MyRenderProxy.DebugDrawCapsule(vertexA, vertexB, capsule.Radius, color, true, shaded);
                        drawCustomText = true;
                        break;
                    }

                case HkShapeType.Cylinder:
                    {
                        // Sphere and OBB to show cylinder space
                        var cylinder = (HkCylinderShape)shape;
                        VRageRender.MyRenderProxy.DebugDrawCylinder(worldMatrix, cylinder.VertexA, cylinder.VertexB, cylinder.Radius, color, alpha, true, shaded);
                        drawCustomText = true;
                        break;
                    }


                case HkShapeType.Box:
                    {
                        var box = (HkBoxShape)shape;

                        VRageRender.MyRenderProxy.DebugDrawOBB(MatrixD.CreateScale(box.HalfExtents * 2 + new Vector3(expandSize)) * worldMatrix, color, alpha, true, shaded);
                        if (isPhantom)
                        {
                            VRageRender.MyRenderProxy.DebugDrawOBB(Matrix.CreateScale(box.HalfExtents * 2 + new Vector3(expandSize)) * worldMatrix, color, 1.0f, true, false);
                            VRageRender.MyRenderProxy.DebugDrawOBB(Matrix.CreateScale(box.HalfExtents * 2 + new Vector3(expandSize)) * worldMatrix, color, 1.0f, true, false, false);
                        }
                        drawCustomText = true;
                        break;
                    }

                case HkShapeType.ConvexVertices:
                    {
                        var convexShape = (HkConvexVerticesShape)shape;
                        Vector3 center;
                        convexShape.GetGeometry(DebugGeometry, out center);
                        Vector3D transformedCenter = Vector3D.Transform(center, worldMatrix.GetOrientation());

                        var matrix = worldMatrix;
                        matrix = MatrixD.CreateScale(expandRatio) * matrix;
                        matrix.Translation -= transformedCenter * (expandRatio - 1);

                        //matrix.Translation += transformedCenter;
                        DrawGeometry(DebugGeometry, matrix, color, true, true);

                        drawCustomText = true;
                        break;
                    }

                case HkShapeType.ConvexTranslate:
                    {
                        var translateShape = (HkConvexTranslateShape)shape;
                        DrawCollisionShape((HkShape)translateShape.ChildShape, Matrix.CreateTranslation(translateShape.Translation) * worldMatrix, alpha, ref shapeIndex, customText);
                        break;
                    }

                case HkShapeType.ConvexTransform:
                    {
                        var transformShape = (HkConvexTransformShape)shape;
                        DrawCollisionShape(transformShape.ChildShape, transformShape.Transform * worldMatrix, alpha, ref shapeIndex, customText);
                        break;
                    }

                case HkShapeType.Mopp:
                    {
                        var compoundShape = (HkMoppBvTreeShape)shape;
                        DrawCollisionShape(compoundShape.ShapeCollection, worldMatrix, alpha, ref shapeIndex, customText);
                        break;
                    }

                case HkShapeType.List:
                    {
                        var listShape = (HkListShape)shape;
                        var iterator = listShape.GetIterator();
                        while (iterator.IsValid)
                        {
                            //string text = (customText ?? string.Empty) + "[" + iterator.CurrentShapeKey + "]";
                            DrawCollisionShape(iterator.CurrentValue, worldMatrix, alpha, ref shapeIndex, customText);
                            iterator.Next();
                        }
                        break;
                    }

                case HkShapeType.StaticCompound:
                    {
                        var compoundShape = (HkStaticCompoundShape)shape;

                        if (DebugDrawFlattenHierarchy)
                        {
                            var it = compoundShape.GetIterator();
                            while (it.IsValid)
                            {
                                if (compoundShape.IsShapeKeyEnabled(it.CurrentShapeKey))
                                {
                                    string text = (customText ?? string.Empty) + "-" + it.CurrentShapeKey + "-";
                                    DrawCollisionShape(it.CurrentValue, worldMatrix, alpha, ref shapeIndex, text);
                                }
                                it.Next();
                            }
                        }
                        else
                        {
                            for (int i = 0; i < compoundShape.InstanceCount; i++)
                            {
                                bool enabled = compoundShape.IsInstanceEnabled(i);
                                string text;
                                if (enabled)
                                    text = (customText ?? string.Empty) + "<" + i + ">";
                                else
                                    text = (customText ?? string.Empty) + "(" + i + ")";

                                if (enabled)
                                    DrawCollisionShape(compoundShape.GetInstance(i), compoundShape.GetInstanceTransform(i) * worldMatrix, alpha, ref shapeIndex, text);
                            }
                        }

                        break;
                    }

                case HkShapeType.Triangle:
                    {
                        HkTriangleShape tri = (HkTriangleShape)shape;
                        VRageRender.MyRenderProxy.DebugDrawTriangle(tri.Pt0, tri.Pt1, tri.Pt2, Color.Green, false, false);
                        break;
                    }

                case HkShapeType.BvTree:
                    {
                        var gridShape = (HkGridShape)shape;
                        if (HkGridShapeCellDebugDraw && !gridShape.Base.IsZero)
                        {
                            Vector3S min, max;
                            var cellSize = gridShape.CellSize;

                            int count = gridShape.GetShapeInfoCount();
                            for (int i = 0; i < count; i++)
                            {
                                try
                                {
                                    gridShape.GetShapeInfo(i, out min, out max, m_tmpShapeList);
                                    Vector3 size = max * cellSize - min * cellSize;
                                    Vector3 center = (max * cellSize + min * cellSize) / 2.0f;
                                    size += Vector3.One * cellSize;
                                    var clr = color;
                                    if (min == max)
                                    {
                                        clr = new Color(1.0f, 0.2f, 0.1f);
                                    }
                                    VRageRender.MyRenderProxy.DebugDrawOBB(Matrix.CreateScale(size + new Vector3(expandSize)) * Matrix.CreateTranslation(center) * worldMatrix, clr, alpha, true, shaded);
                                }
                                finally
                                {
                                    m_tmpShapeList.Clear();
                                }
                            }
                        }
                        else
                        {
                            var msg = MyRenderProxy.PrepareDebugDrawTriangles();

                            try
                            {
                                using (HkShapeBuffer buf = new HkShapeBuffer())
                                {
                                    var treeShape = (HkBvTreeShape)shape;
                                    for (var i = treeShape.GetIterator(buf); i.IsValid; i.Next())
                                    {
                                        var child = i.CurrentValue;
                                        if (child.ShapeType == HkShapeType.Triangle)
                                        {
                                            var tri = (HkTriangleShape)child;
                                            msg.AddTriangle(tri.Pt0, tri.Pt1, tri.Pt2);
                                        }
                                        else
                                        {
                                            DrawCollisionShape(child, worldMatrix, alpha, ref shapeIndex);
                                        }
                                    }
                                }
                            }
                            finally
                            {
                                MyRenderProxy.DebugDrawTriangles(msg, worldMatrix, color, false, false);
                            }
                        }
                        break;
                    }

                case HkShapeType.BvCompressedMesh:
                    {
                        if (MyDebugDrawSettings.DEBUG_DRAW_TRIANGLE_PHYSICS)
                        {
                            var meshShape = (HkBvCompressedMeshShape)shape;
                            meshShape.GetGeometry(DebugGeometry);
                            DrawGeometry(DebugGeometry, worldMatrix, Color.Green, false, false);
                            drawCustomText = true;
                        }
                        break;
                    }

                case HkShapeType.Bv:
                    {
                        var bvShape = (HkBvShape)shape;
                        DrawCollisionShape(bvShape.BoundingVolumeShape, worldMatrix, alpha, ref shapeIndex, null, true);
                        DrawCollisionShape(bvShape.ChildShape, worldMatrix, alpha, ref shapeIndex);
                        break;
                    }

                case HkShapeType.PhantomCallback:
                    {
                        // Nothing to draw, it's just shape with events
                        MyRenderProxy.DebugDrawText3D(worldMatrix.Translation, "Phantom", Color.Green, 0.75f, false);
                        break;
                    }

                default:
                    break;
            }

            if (drawCustomText && customText != null)
            {
                color.A = 255;
                MyRenderProxy.DebugDrawText3D(worldMatrix.Translation, customText, color, 0.8f, false);
            }
        }
        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);
        }
        public static void DrawCollisionShape(HkShape shape, MatrixD worldMatrix, float alpha, ref int shapeIndex, string customText = null, bool isPhantom = false)
        {
            var color = GetShapeColor(shape.ShapeType, ref shapeIndex, isPhantom);

            if (isPhantom)
            {
                alpha *= alpha;
            }
            color.A = (byte)(alpha * 255);

            bool shaded = true;

            float expandSize  = 0.02f;
            float expandRatio = 1.035f;

            bool drawCustomText = false;

            switch (shape.ShapeType)
            {
            case HkShapeType.Sphere:
            {
                var   sphere = (HkSphereShape)shape;
                float radius = sphere.Radius;

                VRageRender.MyRenderProxy.DebugDrawSphere(worldMatrix.Translation, radius, color, alpha, true, shaded);

                if (isPhantom)
                {
                    VRageRender.MyRenderProxy.DebugDrawSphere(worldMatrix.Translation, radius, color, 1.0f, true, false);
                    VRageRender.MyRenderProxy.DebugDrawSphere(worldMatrix.Translation, radius, color, 1.0f, true, false, false);
                }

                drawCustomText = true;
                break;
            }

            case HkShapeType.Capsule:
            {
                // Sphere and OBB to show cylinder space
                var      capsule = (HkCapsuleShape)shape;
                Vector3D vertexA = Vector3.Transform(capsule.VertexA, worldMatrix);
                Vector3D vertexB = Vector3.Transform(capsule.VertexB, worldMatrix);
                VRageRender.MyRenderProxy.DebugDrawCapsule(vertexA, vertexB, capsule.Radius, color, true, shaded);
                drawCustomText = true;
                break;
            }

            case HkShapeType.Cylinder:
            {
                // Sphere and OBB to show cylinder space
                var cylinder = (HkCylinderShape)shape;
                VRageRender.MyRenderProxy.DebugDrawCylinder(worldMatrix, cylinder.VertexA, cylinder.VertexB, cylinder.Radius, color, alpha, true, shaded);
                drawCustomText = true;
                break;
            }


            case HkShapeType.Box:
            {
                var box = (HkBoxShape)shape;

                VRageRender.MyRenderProxy.DebugDrawOBB(MatrixD.CreateScale(box.HalfExtents * 2 + new Vector3(expandSize)) * worldMatrix, color, alpha, true, shaded);
                if (isPhantom)
                {
                    VRageRender.MyRenderProxy.DebugDrawOBB(Matrix.CreateScale(box.HalfExtents * 2 + new Vector3(expandSize)) * worldMatrix, color, 1.0f, true, false);
                    VRageRender.MyRenderProxy.DebugDrawOBB(Matrix.CreateScale(box.HalfExtents * 2 + new Vector3(expandSize)) * worldMatrix, color, 1.0f, true, false, false);
                }
                drawCustomText = true;
                break;
            }

            case HkShapeType.ConvexVertices:
            {
                var     convexShape = (HkConvexVerticesShape)shape;
                Vector3 center;
                convexShape.GetGeometry(DebugGeometry, out center);
                Vector3D transformedCenter = Vector3D.Transform(center, worldMatrix.GetOrientation());

                var matrix = worldMatrix;
                matrix              = MatrixD.CreateScale(expandRatio) * matrix;
                matrix.Translation -= transformedCenter * (expandRatio - 1);

                //matrix.Translation += transformedCenter;
                DrawGeometry(DebugGeometry, matrix, color, true, true);

                drawCustomText = true;
                break;
            }

            case HkShapeType.ConvexTranslate:
            {
                var translateShape = (HkConvexTranslateShape)shape;
                DrawCollisionShape((HkShape)translateShape.ChildShape, Matrix.CreateTranslation(translateShape.Translation) * worldMatrix, alpha, ref shapeIndex, customText);
                break;
            }

            case HkShapeType.ConvexTransform:
            {
                var transformShape = (HkConvexTransformShape)shape;
                DrawCollisionShape(transformShape.ChildShape, transformShape.Transform * worldMatrix, alpha, ref shapeIndex, customText);
                break;
            }

            case HkShapeType.Mopp:
            {
                var compoundShape = (HkMoppBvTreeShape)shape;
                DrawCollisionShape(compoundShape.ShapeCollection, worldMatrix, alpha, ref shapeIndex, customText);
                break;
            }

            case HkShapeType.List:
            {
                var listShape = (HkListShape)shape;
                var iterator  = listShape.GetIterator();
                while (iterator.IsValid)
                {
                    //string text = (customText ?? string.Empty) + "[" + iterator.CurrentShapeKey + "]";
                    DrawCollisionShape(iterator.CurrentValue, worldMatrix, alpha, ref shapeIndex, customText);
                    iterator.Next();
                }
                break;
            }

            case HkShapeType.StaticCompound:
            {
                var compoundShape = (HkStaticCompoundShape)shape;

                if (DebugDrawFlattenHierarchy)
                {
                    var it = compoundShape.GetIterator();
                    while (it.IsValid)
                    {
                        if (compoundShape.IsShapeKeyEnabled(it.CurrentShapeKey))
                        {
                            string text = (customText ?? string.Empty) + "-" + it.CurrentShapeKey + "-";
                            DrawCollisionShape(it.CurrentValue, worldMatrix, alpha, ref shapeIndex, text);
                        }
                        it.Next();
                    }
                }
                else
                {
                    for (int i = 0; i < compoundShape.InstanceCount; i++)
                    {
                        bool   enabled = compoundShape.IsInstanceEnabled(i);
                        string text;
                        if (enabled)
                        {
                            text = (customText ?? string.Empty) + "<" + i + ">";
                        }
                        else
                        {
                            text = (customText ?? string.Empty) + "(" + i + ")";
                        }

                        if (enabled)
                        {
                            DrawCollisionShape(compoundShape.GetInstance(i), compoundShape.GetInstanceTransform(i) * worldMatrix, alpha, ref shapeIndex, text);
                        }
                    }
                }

                break;
            }

            case HkShapeType.Triangle:
            {
                HkTriangleShape tri = (HkTriangleShape)shape;
                VRageRender.MyRenderProxy.DebugDrawTriangle(tri.Pt0, tri.Pt1, tri.Pt2, Color.Green, false, false);
                break;
            }

            case HkShapeType.BvTree:
            {
                var gridShape = (HkGridShape)shape;
                if (HkGridShapeCellDebugDraw && !gridShape.Base.IsZero)
                {
                    Vector3S min, max;
                    var      cellSize = gridShape.CellSize;

                    int count = gridShape.GetShapeInfoCount();
                    for (int i = 0; i < count; i++)
                    {
                        try
                        {
                            gridShape.GetShapeInfo(i, out min, out max, m_tmpShapeList);
                            Vector3 size   = max * cellSize - min * cellSize;
                            Vector3 center = (max * cellSize + min * cellSize) / 2.0f;
                            size += Vector3.One * cellSize;
                            var clr = color;
                            if (min == max)
                            {
                                clr = new Color(1.0f, 0.2f, 0.1f);
                            }
                            VRageRender.MyRenderProxy.DebugDrawOBB(Matrix.CreateScale(size + new Vector3(expandSize)) * Matrix.CreateTranslation(center) * worldMatrix, clr, alpha, true, shaded);
                        }
                        finally
                        {
                            m_tmpShapeList.Clear();
                        }
                    }
                }
                else
                {
                    var msg = MyRenderProxy.PrepareDebugDrawTriangles();

                    try
                    {
                        using (HkShapeBuffer buf = new HkShapeBuffer())
                        {
                            var treeShape = (HkBvTreeShape)shape;
                            for (var i = treeShape.GetIterator(buf); i.IsValid; i.Next())
                            {
                                var child = i.CurrentValue;
                                if (child.ShapeType == HkShapeType.Triangle)
                                {
                                    var tri = (HkTriangleShape)child;
                                    msg.AddTriangle(tri.Pt0, tri.Pt1, tri.Pt2);
                                }
                                else
                                {
                                    DrawCollisionShape(child, worldMatrix, alpha, ref shapeIndex);
                                }
                            }
                        }
                    }
                    finally
                    {
                        MyRenderProxy.DebugDrawTriangles(msg, worldMatrix, color, false, false);
                    }
                }
                break;
            }

            case HkShapeType.BvCompressedMesh:
            {
                if (MyDebugDrawSettings.DEBUG_DRAW_TRIANGLE_PHYSICS)
                {
                    var meshShape = (HkBvCompressedMeshShape)shape;
                    meshShape.GetGeometry(DebugGeometry);
                    DrawGeometry(DebugGeometry, worldMatrix, Color.Green, false, false);
                    drawCustomText = true;
                }
                break;
            }

            case HkShapeType.Bv:
            {
                var bvShape = (HkBvShape)shape;
                DrawCollisionShape(bvShape.BoundingVolumeShape, worldMatrix, alpha, ref shapeIndex, null, true);
                DrawCollisionShape(bvShape.ChildShape, worldMatrix, alpha, ref shapeIndex);
                break;
            }

            case HkShapeType.PhantomCallback:
            {
                // Nothing to draw, it's just shape with events
                MyRenderProxy.DebugDrawText3D(worldMatrix.Translation, "Phantom", Color.Green, 0.75f, false);
                break;
            }

            default:
                break;
            }

            if (drawCustomText && customText != null)
            {
                color.A = 255;
                MyRenderProxy.DebugDrawText3D(worldMatrix.Translation, customText, color, 0.8f, false);
            }
        }
        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;
        }
Beispiel #5
0
        public static unsafe void DrawCollisionShape(HkShape shape, MatrixD worldMatrix, float alpha, ref int shapeIndex, string customText = null, bool isPhantom = false)
        {
            Color color = GetShapeColor(shape.ShapeType, ref shapeIndex, isPhantom);

            if (isPhantom)
            {
                alpha *= alpha;
            }
            color.A = (byte)(alpha * 255f);
            bool        smooth    = true;
            float       num       = 0.02f;
            float       num2      = 1.035f;
            bool        flag2     = false;
            HkShapeType shapeType = shape.ShapeType;

            switch (shapeType)
            {
            case HkShapeType.Sphere:
            {
                float radius = ((HkSphereShape)shape).Radius;
                MyRenderProxy.DebugDrawSphere(worldMatrix.Translation, radius, color, alpha, true, smooth, true, false);
                if (isPhantom)
                {
                    MyRenderProxy.DebugDrawSphere(worldMatrix.Translation, radius, color, 1f, true, false, true, false);
                    MyRenderProxy.DebugDrawSphere(worldMatrix.Translation, radius, color, 1f, true, false, false, false);
                }
                flag2 = true;
                goto TR_0003;
            }

            case HkShapeType.Cylinder:
            {
                HkCylinderShape shape4 = (HkCylinderShape)shape;
                MyRenderProxy.DebugDrawCylinder(worldMatrix, shape4.VertexA, shape4.VertexB, shape4.Radius, color, alpha, true, smooth, false);
                flag2 = true;
                goto TR_0003;
            }

            case HkShapeType.Triangle:
            {
                HkTriangleShape shape12 = (HkTriangleShape)shape;
                MyRenderProxy.DebugDrawTriangle(shape12.Pt0, shape12.Pt1, shape12.Pt2, Color.Green, false, false, false);
                goto TR_0003;
            }

            case HkShapeType.Box:
            {
                HkBoxShape shape5 = (HkBoxShape)shape;
                MyRenderProxy.DebugDrawOBB(MatrixD.CreateScale((shape5.HalfExtents * 2f) + new Vector3(num)) * worldMatrix, color, alpha, true, smooth, true, false);
                if (isPhantom)
                {
                    MyRenderProxy.DebugDrawOBB(Matrix.CreateScale((shape5.HalfExtents * 2f) + new Vector3(num)) * worldMatrix, color, 1f, true, false, true, false);
                    MyRenderProxy.DebugDrawOBB(Matrix.CreateScale((shape5.HalfExtents * 2f) + new Vector3(num)) * worldMatrix, color, 1f, true, false, false, false);
                }
                flag2 = true;
                goto TR_0003;
            }

            case HkShapeType.Capsule:
            {
                HkCapsuleShape shape3 = (HkCapsuleShape)shape;
                MyRenderProxy.DebugDrawCapsule(Vector3.Transform(shape3.VertexA, worldMatrix), Vector3.Transform(shape3.VertexB, worldMatrix), shape3.Radius, color, true, smooth, false);
                flag2 = true;
                goto TR_0003;
            }

            case HkShapeType.ConvexVertices:
            {
                Vector3 vector;
                ((HkConvexVerticesShape)shape).GetGeometry(DebugGeometry, out vector);
                Vector3D vectord2 = Vector3D.Transform(vector, worldMatrix.GetOrientation());
                MatrixD  xd       = worldMatrix;
                xd = MatrixD.CreateScale((double)num2) * xd;
                MatrixD *xdPtr1 = (MatrixD *)ref xd;
                xdPtr1.Translation -= vectord2 * (num2 - 1f);
                DrawGeometry(DebugGeometry, xd, color, true, true);
                flag2 = true;
                goto TR_0003;
            }

            case HkShapeType.TriSampledHeightFieldCollection:
            case HkShapeType.TriSampledHeightFieldBvTree:
            case HkShapeType.SampledHeightField:
            case HkShapeType.ExtendedMesh:
            case HkShapeType.Transform:
            case HkShapeType.CompressedMesh:
            case HkShapeType.Collection:
            case HkShapeType.User0:
            case HkShapeType.User1:
            case HkShapeType.User2:
                goto TR_0003;

            case HkShapeType.List:
            {
                HkShapeContainerIterator iterator = ((HkListShape)shape).GetIterator();
                while (iterator.IsValid)
                {
                    DrawCollisionShape(iterator.CurrentValue, worldMatrix, alpha, ref shapeIndex, customText, false);
                    iterator.Next();
                }
                goto TR_0003;
            }

            case HkShapeType.Mopp:
                DrawCollisionShape((HkShape)((HkMoppBvTreeShape)shape).ShapeCollection, worldMatrix, alpha, ref shapeIndex, customText, false);
                goto TR_0003;

            case HkShapeType.ConvexTranslate:
            {
                HkConvexTranslateShape shape7 = (HkConvexTranslateShape)shape;
                DrawCollisionShape((HkShape)shape7.ChildShape, Matrix.CreateTranslation(shape7.Translation) * worldMatrix, alpha, ref shapeIndex, customText, false);
                goto TR_0003;
            }

            case HkShapeType.ConvexTransform:
            {
                HkConvexTransformShape shape8 = (HkConvexTransformShape)shape;
                DrawCollisionShape((HkShape)shape8.ChildShape, shape8.Transform * worldMatrix, alpha, ref shapeIndex, customText, false);
                goto TR_0003;
            }

            case HkShapeType.StaticCompound:
            {
                HkStaticCompoundShape shape11 = (HkStaticCompoundShape)shape;
                if (DebugDrawFlattenHierarchy)
                {
                    HkShapeContainerIterator iterator2 = shape11.GetIterator();
                    while (iterator2.IsValid)
                    {
                        if (shape11.IsShapeKeyEnabled(iterator2.CurrentShapeKey))
                        {
                            object[] objArray1 = new object[4];
                            object[] objArray2 = new object[4];
                            objArray2[0] = customText ?? string.Empty;
                            object[] local2 = objArray2;
                            local2[1] = "-";
                            local2[2] = iterator2.CurrentShapeKey;
                            local2[3] = "-";
                            string str = string.Concat(local2);
                            DrawCollisionShape(iterator2.CurrentValue, worldMatrix, alpha, ref shapeIndex, str, false);
                        }
                        iterator2.Next();
                    }
                }
                else
                {
                    for (int i = 0; i < shape11.InstanceCount; i++)
                    {
                        string str2;
                        bool   flag3 = shape11.IsInstanceEnabled(i);
                        if (flag3)
                        {
                            object[] objArray3 = new object[4];
                            object[] objArray4 = new object[4];
                            objArray4[0] = customText ?? string.Empty;
                            object[] local4 = objArray4;
                            local4[1] = "<";
                            local4[2] = i;
                            local4[3] = ">";
                            str2      = string.Concat(local4);
                        }
                        else
                        {
                            object[] objArray5 = new object[4];
                            object[] objArray6 = new object[4];
                            objArray6[0] = customText ?? string.Empty;
                            object[] local6 = objArray6;
                            local6[1] = "(";
                            local6[2] = i;
                            local6[3] = ")";
                            str2      = string.Concat(local6);
                        }
                        if (flag3)
                        {
                            DrawCollisionShape(shape11.GetInstance(i), shape11.GetInstanceTransform(i) * worldMatrix, alpha, ref shapeIndex, str2, false);
                        }
                    }
                }
                goto TR_0003;
            }

            case HkShapeType.BvCompressedMesh:
                break;

            case HkShapeType.BvTree:
            {
                HkGridShape shape13 = (HkGridShape)shape;
                if (HkGridShapeCellDebugDraw && !shape13.Base.IsZero)
                {
                    float cellSize       = shape13.CellSize;
                    int   shapeInfoCount = shape13.GetShapeInfoCount();
                    for (int i = 0; i < shapeInfoCount; i++)
                    {
                        try
                        {
                            Vector3S vectors;
                            Vector3S vectors2;
                            shape13.GetShapeInfo(i, out vectors, out vectors2, m_tmpShapeList);
                            Vector3 position = (Vector3)(((vectors2 * cellSize) + (vectors * cellSize)) / 2f);
                            Color   color2   = color;
                            if (vectors == vectors2)
                            {
                                color2 = new Color(1f, 0.2f, 0.1f);
                            }
                            MyRenderProxy.DebugDrawOBB((Matrix.CreateScale((((vectors2 * cellSize) - (vectors * cellSize)) + (Vector3.One * cellSize)) + new Vector3(num)) * Matrix.CreateTranslation(position)) * worldMatrix, color2, alpha, true, smooth, true, false);
                        }
                        finally
                        {
                            m_tmpShapeList.Clear();
                        }
                    }
                }
                else
                {
                    MyRenderMessageDebugDrawTriangles msgInterface = MyRenderProxy.PrepareDebugDrawTriangles();
                    try
                    {
                        using (HkShapeBuffer buffer = new HkShapeBuffer())
                        {
                            HkShapeContainerIterator iterator3 = ((HkBvTreeShape)shape).GetIterator(buffer);
                            while (iterator3.IsValid)
                            {
                                HkShape currentValue = iterator3.CurrentValue;
                                if (currentValue.ShapeType != HkShapeType.Triangle)
                                {
                                    DrawCollisionShape(currentValue, worldMatrix, alpha, ref shapeIndex, null, false);
                                }
                                else
                                {
                                    HkTriangleShape shape17 = (HkTriangleShape)currentValue;
                                    msgInterface.AddTriangle(shape17.Pt0, shape17.Pt1, shape17.Pt2);
                                }
                                iterator3.Next();
                            }
                            goto TR_0003;
                        }
                    }
                    finally
                    {
                        msgInterface.Color = color;
                        MyRenderProxy.DebugDrawTriangles(msgInterface, new MatrixD?(worldMatrix), false, false, false, false);
                    }
                    break;
                }
                goto TR_0003;
            }

            default:
                if (shapeType == HkShapeType.Bv)
                {
                    HkBvShape shape19 = (HkBvShape)shape;
                    DrawCollisionShape(shape19.BoundingVolumeShape, worldMatrix, alpha, ref shapeIndex, null, true);
                    DrawCollisionShape(shape19.ChildShape, worldMatrix, alpha, ref shapeIndex, null, false);
                }
                else if (shapeType == HkShapeType.PhantomCallback)
                {
                    MyRenderProxy.DebugDrawText3D(worldMatrix.Translation, "Phantom", Color.Green, 0.75f, false, MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_TOP, -1, false);
                }
                goto TR_0003;
            }
            if (MyDebugDrawSettings.DEBUG_DRAW_TRIANGLE_PHYSICS)
            {
                ((HkBvCompressedMeshShape)shape).GetGeometry(DebugGeometry);
                DrawGeometry(DebugGeometry, worldMatrix, Color.Green, false, false);
                flag2 = true;
            }
TR_0003:
            if (flag2 && (customText != null))
            {
                color.A = 0xff;
                MyRenderProxy.DebugDrawText3D(worldMatrix.Translation, customText, color, 0.8f, false, MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_TOP, -1, false);
            }
        }