Esempio n. 1
0
        public static void DrawRay(RayD ray, Vector4 color, float width, float length = float.MaxValue)
        {
            var c = color;

            MyTransparentGeometry.AddLineBillboard(_square, c, ray.Position, ray.Direction, length, width);
        }
Esempio n. 2
0
        public static void DrawHighlightBox(MatrixD matrix, float scale, float lineWidth, MyStringId material, Color colorFace, Color colorWire, BlendTypeEnum blendType)
        {
            // optimized box draw compared to MySimpleObjectDraw.DrawTransparentBox; also allows consistent edge thickness
            MyQuadD     quad;
            Vector3D    p;
            MatrixD     m;
            var         halfScale     = (scale * 0.5f);
            float       lineLength    = scale;
            const float ROTATE_90_RAD = (90f / 180f * MathHelper.Pi); // 90deg in radians

            p = matrix.Translation + matrix.Forward * halfScale;
            if (IsFaceVisible(p, matrix.Forward))
            {
                MyUtils.GenerateQuad(out quad, ref p, halfScale, halfScale, ref matrix);
                MyTransparentGeometry.AddQuad(material, ref quad, colorFace, ref p, blendType: blendType);
            }

            p = matrix.Translation + matrix.Backward * halfScale;
            if (IsFaceVisible(p, matrix.Backward))
            {
                MyUtils.GenerateQuad(out quad, ref p, halfScale, halfScale, ref matrix);
                MyTransparentGeometry.AddQuad(material, ref quad, colorFace, ref p, blendType: blendType);
            }

            p = matrix.Translation + matrix.Left * halfScale;
            m = matrix * MatrixD.CreateFromAxisAngle(matrix.Up, ROTATE_90_RAD);
            if (IsFaceVisible(p, matrix.Left))
            {
                MyUtils.GenerateQuad(out quad, ref p, halfScale, halfScale, ref m);
                MyTransparentGeometry.AddQuad(material, ref quad, colorFace, ref p, blendType: blendType);
            }

            p = matrix.Translation + matrix.Right * halfScale;
            if (IsFaceVisible(p, matrix.Right))
            {
                MyUtils.GenerateQuad(out quad, ref p, halfScale, halfScale, ref m);
                MyTransparentGeometry.AddQuad(material, ref quad, colorFace, ref p, blendType: blendType);
            }

            m = matrix * MatrixD.CreateFromAxisAngle(matrix.Left, ROTATE_90_RAD);
            p = matrix.Translation + matrix.Up * halfScale;
            if (IsFaceVisible(p, matrix.Up))
            {
                MyUtils.GenerateQuad(out quad, ref p, halfScale, halfScale, ref m);
                MyTransparentGeometry.AddQuad(material, ref quad, colorFace, ref p, blendType: blendType);
            }

            p = matrix.Translation + matrix.Down * halfScale;
            if (IsFaceVisible(p, matrix.Down))
            {
                MyUtils.GenerateQuad(out quad, ref p, halfScale, halfScale, ref m);
                MyTransparentGeometry.AddQuad(material, ref quad, colorFace, ref p, blendType: blendType);
            }

            var upHalf      = (matrix.Up * halfScale);
            var rightHalf   = (matrix.Right * halfScale);
            var forwardHalf = (matrix.Forward * halfScale);

            MyTransparentGeometry.AddLineBillboard(material, colorWire, matrix.Translation + upHalf + -rightHalf + matrix.Forward * halfScale, matrix.Backward, lineLength, lineWidth, blendType: blendType);
            MyTransparentGeometry.AddLineBillboard(material, colorWire, matrix.Translation + upHalf + rightHalf + matrix.Forward * halfScale, matrix.Backward, lineLength, lineWidth, blendType: blendType);
            MyTransparentGeometry.AddLineBillboard(material, colorWire, matrix.Translation + -upHalf + -rightHalf + matrix.Forward * halfScale, matrix.Backward, lineLength, lineWidth, blendType: blendType);
            MyTransparentGeometry.AddLineBillboard(material, colorWire, matrix.Translation + -upHalf + rightHalf + matrix.Forward * halfScale, matrix.Backward, lineLength, lineWidth, blendType: blendType);

            MyTransparentGeometry.AddLineBillboard(material, colorWire, matrix.Translation + forwardHalf + -rightHalf + matrix.Up * halfScale, matrix.Down, lineLength, lineWidth, blendType: blendType);
            MyTransparentGeometry.AddLineBillboard(material, colorWire, matrix.Translation + forwardHalf + rightHalf + matrix.Up * halfScale, matrix.Down, lineLength, lineWidth, blendType: blendType);
            MyTransparentGeometry.AddLineBillboard(material, colorWire, matrix.Translation + -forwardHalf + -rightHalf + matrix.Up * halfScale, matrix.Down, lineLength, lineWidth, blendType: blendType);
            MyTransparentGeometry.AddLineBillboard(material, colorWire, matrix.Translation + -forwardHalf + rightHalf + matrix.Up * halfScale, matrix.Down, lineLength, lineWidth, blendType: blendType);

            MyTransparentGeometry.AddLineBillboard(material, colorWire, matrix.Translation + forwardHalf + -upHalf + matrix.Right * halfScale, matrix.Left, lineLength, lineWidth, blendType: blendType);
            MyTransparentGeometry.AddLineBillboard(material, colorWire, matrix.Translation + forwardHalf + upHalf + matrix.Right * halfScale, matrix.Left, lineLength, lineWidth, blendType: blendType);
            MyTransparentGeometry.AddLineBillboard(material, colorWire, matrix.Translation + -forwardHalf + -upHalf + matrix.Right * halfScale, matrix.Left, lineLength, lineWidth, blendType: blendType);
            MyTransparentGeometry.AddLineBillboard(material, colorWire, matrix.Translation + -forwardHalf + upHalf + matrix.Right * halfScale, matrix.Left, lineLength, lineWidth, blendType: blendType);
        }
        public void CalculateRotationHints(MatrixD drawMatrix, BoundingBoxD worldBox, bool draw, bool fixedAxes = false, bool hideForwardAndUpArrows = false)
        {
            drawMatrix.Translation = Vector3D.Zero;
            MatrixD drawInverse = MatrixD.Invert(drawMatrix);

            drawInverse *= drawMatrix.GetOrientation();
            drawInverse *= MySector.MainCamera.ViewMatrixAtZero;

            MatrixD camWorld = MatrixD.Invert(drawInverse);

            m_viewProjection.ViewAtZero             = MatrixD.CreateLookAt(Vector3D.Zero, camWorld.Forward, camWorld.Up);
            m_viewProjection.ViewAtZero.Translation = new Vector3D(0, 0, -6);
            m_viewProjection.View              = drawInverse;
            m_viewProjection.View.Translation += new Vector3D(0, 0, -10);
            m_viewProjection.CameraPosition    = camWorld.Translation;

            Vector2 screenSize = MyGuiManager.GetScreenSizeFromNormalizedSize(Vector2.One);
            float   previewRatio = 2.5f;
            int     hintsWidth = (int)(screenSize.X / previewRatio), hintsHeight = (int)(screenSize.Y / previewRatio), hintsXOffset = 0, hintsYOffset = 0;

            m_viewProjection.Viewport = new MyViewport(
                (int)MySector.MainCamera.Viewport.Width - hintsWidth - hintsXOffset,
                hintsYOffset,
                hintsWidth,
                hintsHeight);

            m_viewProjection.DepthRead  = false;
            m_viewProjection.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, (float)hintsHeight / hintsWidth, 0.1f, 10);



            worldBox = new BoundingBoxD(-new Vector3(MyDefinitionManager.Static.GetCubeSize(MyCubeSize.Large) * 0.5f), new Vector3(MyDefinitionManager.Static.GetCubeSize(MyCubeSize.Large)) * 0.5f);


            //m_rotationHintsViewProjection.Projection = MySector.MainCamera.ProjectionMatrix;



            int projectionId = 0;

            VRageRender.MyRenderProxy.AddBillboardViewProjection(projectionId, m_viewProjection);

            //MySimpleObjectDraw.DrawTransparentBox(ref drawMatrix,
            //                ref worldBox, ref Vector4.One, MySimpleObjectRasterizer.Wireframe, 1, 0.04f, null, null, false, 0);
            if (draw)
            {
                var white = Color.White;
                MySimpleObjectDraw.DrawTransparentBox(ref drawMatrix,
                                                      ref worldBox, ref white, MySimpleObjectRasterizer.Solid, 1, 0.04f, "SquareFullColor", null, false, projectionId, 100);
            }

            MyOrientedBoundingBoxD rotateHintsBox = new MyOrientedBoundingBoxD(Vector3D.Transform(worldBox.Center, drawMatrix), worldBox.HalfExtents, Quaternion.CreateFromRotationMatrix(drawMatrix));

            //VRageRender.MyRenderProxy.DebugDrawOBB(rotateHintsBox, Vector3.One, 1, false, false);


            rotateHintsBox.GetCorners(m_cubeVertices, 0);

            //for (int vi = 0; vi < 8; vi++)
            //{
            //    VRageRender.MyRenderProxy.DebugDrawText3D(m_cubeVertices[vi], vi.ToString(), Color.White, 0.7f, false);
            //}

            //for (int vi = 0; vi < 4; vi++)
            //{
            //    VRageRender.MyRenderProxy.DebugDrawText3D((m_cubeVertices[MyOrientedBoundingBox.StartXVertices[vi]] + m_cubeVertices[MyOrientedBoundingBox.EndXVertices[vi]]) * 0.5f, vi.ToString(), Color.Red, 0.7f, false);
            //    VRageRender.MyRenderProxy.DebugDrawText3D((m_cubeVertices[MyOrientedBoundingBox.StartYVertices[vi]] + m_cubeVertices[MyOrientedBoundingBox.EndYVertices[vi]]) * 0.5f, vi.ToString(), Color.Green, 0.7f, false);
            //    VRageRender.MyRenderProxy.DebugDrawText3D((m_cubeVertices[MyOrientedBoundingBox.StartZVertices[vi]] + m_cubeVertices[MyOrientedBoundingBox.EndZVertices[vi]]) * 0.5f, vi.ToString(), Color.Blue, 0.7f, false);
            //}

            int closestXAxis, closestXAxis2;

            GetClosestCubeEdge(m_cubeVertices, MyOrientedBoundingBox.StartXVertices, MyOrientedBoundingBox.EndXVertices, out closestXAxis, out closestXAxis2);
            Vector3D startXVertex  = m_cubeVertices[MyOrientedBoundingBox.StartXVertices[closestXAxis]];
            Vector3D endXVertex    = m_cubeVertices[MyOrientedBoundingBox.EndXVertices[closestXAxis]];
            Vector3D startXVertex2 = m_cubeVertices[MyOrientedBoundingBox.StartXVertices[closestXAxis2]];
            Vector3D endXVertex2   = m_cubeVertices[MyOrientedBoundingBox.EndXVertices[closestXAxis2]];

            int closestYAxis, closestYAxis2;

            GetClosestCubeEdge(m_cubeVertices, MyOrientedBoundingBox.StartYVertices, MyOrientedBoundingBox.EndYVertices, out closestYAxis, out closestYAxis2);
            Vector3D startYVertex  = m_cubeVertices[MyOrientedBoundingBox.StartYVertices[closestYAxis]];
            Vector3D endYVertex    = m_cubeVertices[MyOrientedBoundingBox.EndYVertices[closestYAxis]];
            Vector3D startYVertex2 = m_cubeVertices[MyOrientedBoundingBox.StartYVertices[closestYAxis2]];
            Vector3D endYVertex2   = m_cubeVertices[MyOrientedBoundingBox.EndYVertices[closestYAxis2]];

            int closestZAxis, closestZAxis2;

            GetClosestCubeEdge(m_cubeVertices, MyOrientedBoundingBox.StartZVertices, MyOrientedBoundingBox.EndZVertices, out closestZAxis, out closestZAxis2);
            Vector3D startZVertex  = m_cubeVertices[MyOrientedBoundingBox.StartZVertices[closestZAxis]];
            Vector3D endZVertex    = m_cubeVertices[MyOrientedBoundingBox.EndZVertices[closestZAxis]];
            Vector3D startZVertex2 = m_cubeVertices[MyOrientedBoundingBox.StartZVertices[closestZAxis2]];
            Vector3D endZVertex2   = m_cubeVertices[MyOrientedBoundingBox.EndZVertices[closestZAxis2]];

            m_cubeEdges.Clear();
            m_cubeEdges.Add(new BoxEdge()
            {
                Axis = 0, Edge = new LineD(startXVertex, endXVertex)
            });
            m_cubeEdges.Add(new BoxEdge()
            {
                Axis = 1, Edge = new LineD(startYVertex, endYVertex)
            });
            m_cubeEdges.Add(new BoxEdge()
            {
                Axis = 2, Edge = new LineD(startZVertex, endZVertex)
            });

            if (!fixedAxes)
            {
                int rotDirection;

                RotationRightAxis      = GetBestAxis(m_cubeEdges, MySector.MainCamera.WorldMatrix.Right, out rotDirection);
                RotationRightDirection = rotDirection;

                RotationUpAxis      = GetBestAxis(m_cubeEdges, MySector.MainCamera.WorldMatrix.Up, out rotDirection);
                RotationUpDirection = rotDirection;

                RotationForwardAxis      = GetBestAxis(m_cubeEdges, MySector.MainCamera.WorldMatrix.Forward, out rotDirection);
                RotationForwardDirection = rotDirection;
            }

            string rightControlName1 = MyInput.Static.GetGameControl(MyControlsSpace.CUBE_ROTATE_HORISONTAL_POSITIVE).GetControlButtonName(MyGuiInputDeviceEnum.Keyboard).ToString();
            string rightControlName2 = MyInput.Static.GetGameControl(MyControlsSpace.CUBE_ROTATE_HORISONTAL_NEGATIVE).GetControlButtonName(MyGuiInputDeviceEnum.Keyboard).ToString();
            string upControlName1    = MyInput.Static.GetGameControl(MyControlsSpace.CUBE_ROTATE_VERTICAL_POSITIVE).GetControlButtonName(MyGuiInputDeviceEnum.Keyboard).ToString();
            string upControlName2    = MyInput.Static.GetGameControl(MyControlsSpace.CUBE_ROTATE_VERTICAL_NEGATIVE).GetControlButtonName(MyGuiInputDeviceEnum.Keyboard).ToString();
            string forwControlName1  = MyInput.Static.GetGameControl(MyControlsSpace.CUBE_ROTATE_ROLL_POSITIVE).GetControlButtonName(MyGuiInputDeviceEnum.Keyboard).ToString();
            string forwControlName2  = MyInput.Static.GetGameControl(MyControlsSpace.CUBE_ROTATE_ROLL_NEGATIVE).GetControlButtonName(MyGuiInputDeviceEnum.Keyboard).ToString();

            if (MyInput.Static.IsJoystickConnected())
            {
                rightControlName1 = MyControllerHelper.GetCodeForControl(MySpaceBindingCreator.CX_BUILD_MODE, MyControlsSpace.CUBE_ROTATE_HORISONTAL_POSITIVE).ToString();
                rightControlName2 = MyControllerHelper.GetCodeForControl(MySpaceBindingCreator.CX_BUILD_MODE, MyControlsSpace.CUBE_ROTATE_HORISONTAL_NEGATIVE).ToString();
                upControlName1    = MyControllerHelper.GetCodeForControl(MySpaceBindingCreator.CX_BUILD_MODE, MyControlsSpace.CUBE_ROTATE_VERTICAL_POSITIVE).ToString();
                upControlName2    = MyControllerHelper.GetCodeForControl(MySpaceBindingCreator.CX_BUILD_MODE, MyControlsSpace.CUBE_ROTATE_VERTICAL_NEGATIVE).ToString();
                forwControlName1  = MyControllerHelper.GetCodeForControl(MySpaceBindingCreator.CX_BUILD_MODE, MyControlsSpace.CUBE_ROTATE_ROLL_POSITIVE).ToString();
                forwControlName2  = MyControllerHelper.GetCodeForControl(MySpaceBindingCreator.CX_BUILD_MODE, MyControlsSpace.CUBE_ROTATE_ROLL_NEGATIVE).ToString();
            }

            Vector3D rightStart = Vector3D.Zero;
            Vector3D rightEnd = Vector3D.Zero;
            Vector3D upStart = Vector3D.Zero;
            Vector3D upEnd = Vector3D.Zero;
            Vector3D forwStart = Vector3D.Zero;
            Vector3D forwEnd = Vector3D.Zero;
            Vector3D rightStart2 = Vector3D.Zero;
            Vector3D rightEnd2 = Vector3D.Zero;
            Vector3D upStart2 = Vector3D.Zero;
            Vector3D upEnd2 = Vector3D.Zero;
            Vector3D forwStart2 = Vector3D.Zero;
            Vector3D forwEnd2 = Vector3D.Zero;
            int      rightAxis = -1, upAxis = -1, forwAxis = -1;
            int      closestRightEdge = -1, closestUpEdge = -1, closestForwEdge = -1;
            int      closestRightEdge2 = -1, closestUpEdge2 = -1, closestForwEdge2 = -1;

            if (RotationRightAxis == 0)
            {
                rightStart        = startXVertex;
                rightEnd          = endXVertex;
                rightStart2       = startXVertex2;
                rightEnd2         = endXVertex2;
                rightAxis         = 0;
                closestRightEdge  = closestXAxis;
                closestRightEdge2 = closestXAxis2;
            }
            else
            if (RotationRightAxis == 1)
            {
                rightStart        = startYVertex;
                rightEnd          = endYVertex;
                rightStart2       = startYVertex2;
                rightEnd2         = endYVertex2;
                rightAxis         = 1;
                closestRightEdge  = closestYAxis;
                closestRightEdge2 = closestYAxis2;
            }
            else
            if (RotationRightAxis == 2)
            {
                rightStart        = startZVertex;
                rightEnd          = endZVertex;
                rightStart2       = startZVertex2;
                rightEnd2         = endZVertex2;
                rightAxis         = 2;
                closestRightEdge  = closestZAxis;
                closestRightEdge2 = closestZAxis2;
            }
            else
            {
                System.Diagnostics.Debug.Assert(false, "Not defined axis");
            }

            if (RotationUpAxis == 0)
            {
                upStart        = startXVertex;
                upEnd          = endXVertex;
                upStart2       = startXVertex2;
                upEnd2         = endXVertex2;
                upAxis         = 0;
                closestUpEdge  = closestXAxis;
                closestUpEdge2 = closestXAxis2;
            }
            else
            if (RotationUpAxis == 1)
            {
                upStart        = startYVertex;
                upEnd          = endYVertex;
                upStart2       = startYVertex2;
                upEnd2         = endYVertex2;
                upAxis         = 1;
                closestUpEdge  = closestYAxis;
                closestUpEdge2 = closestYAxis2;
            }
            else
            if (RotationUpAxis == 2)
            {
                upStart        = startZVertex;
                upEnd          = endZVertex;
                upStart2       = startZVertex2;
                upEnd2         = endZVertex2;
                upAxis         = 2;
                closestUpEdge  = closestZAxis;
                closestUpEdge2 = closestZAxis2;
            }

            if (RotationForwardAxis == 0)
            {
                forwStart        = startXVertex;
                forwEnd          = endXVertex;
                forwStart2       = startXVertex2;
                forwEnd2         = endXVertex2;
                forwAxis         = 0;
                closestForwEdge  = closestXAxis;
                closestForwEdge2 = closestXAxis2;
            }
            else
            if (RotationForwardAxis == 1)
            {
                forwStart        = startYVertex;
                forwEnd          = endYVertex;
                forwStart2       = startYVertex2;
                forwEnd2         = endYVertex2;
                forwAxis         = 1;
                closestForwEdge  = closestYAxis;
                closestForwEdge2 = closestYAxis2;
            }
            else
            if (RotationForwardAxis == 2)
            {
                forwStart        = startZVertex;
                forwEnd          = endZVertex;
                forwStart2       = startZVertex2;
                forwEnd2         = endZVertex2;
                forwAxis         = 2;
                closestForwEdge  = closestZAxis;
                closestForwEdge2 = closestZAxis2;
            }

            float textScale = 0.7f;

            //Closest axis
            //VRageRender.MyRenderProxy.DebugDrawLine3D(rightStart, rightEnd, Color.Red, Color.Red, false);
            //VRageRender.MyRenderProxy.DebugDrawLine3D(upStart, upEnd, Color.Green, Color.Green, false);
            //VRageRender.MyRenderProxy.DebugDrawLine3D(forwStart, forwEnd, Color.Blue, Color.Blue, false);


            if (draw)
            {
                //if all axis are visible, all are shown on edges
                //if 1 axis is not visible, other 2 must be shown on faces
                //if 2 are not visible, they are shown on faces and the one is shown on face center
                //Vector3 camVector = Vector3.Normalize(rotateHintsBox.Center - MySector.MainCamera.Position);
                Vector3D camVector      = MySector.MainCamera.ForwardVector;
                Vector3D rightDirection = Vector3.Normalize(rightEnd - rightStart);
                Vector3D upDirection    = Vector3.Normalize(upEnd - upStart);
                Vector3D forwDirection  = Vector3.Normalize(forwEnd - forwStart);
                float    dotRight       = Math.Abs(Vector3.Dot(camVector, rightDirection));
                float    dotUp          = Math.Abs(Vector3.Dot(camVector, upDirection));
                float    dotForw        = Math.Abs(Vector3.Dot(camVector, forwDirection));

                bool drawRightOnFace = false, drawUpOnFace = false, drawForwOnFace = false;
                bool drawRightOnFaceCenter = false, drawUpOnFaceCenter = false, drawForwOnFaceCenter = false;

                float dotAngle = 0.4f;

                if (dotRight < dotAngle)
                {
                    if (dotUp < dotAngle)
                    {
                        drawForwOnFaceCenter = true;
                        drawRightOnFace      = true;
                        drawUpOnFace         = true;

                        System.Diagnostics.Debug.Assert(dotForw >= dotAngle);
                    }
                    else if (dotForw < dotAngle)
                    {
                        drawUpOnFaceCenter = true;
                        drawRightOnFace    = true;
                        drawForwOnFace     = true;

                        System.Diagnostics.Debug.Assert(dotUp >= dotAngle);
                    }
                    else
                    {
                        drawUpOnFace   = true;
                        drawForwOnFace = true;
                    }
                }
                else
                if (dotUp < dotAngle)
                {
                    if (dotRight < dotAngle)
                    {
                        drawForwOnFaceCenter = true;
                        drawRightOnFace      = true;
                        drawUpOnFace         = true;

                        System.Diagnostics.Debug.Assert(dotForw >= dotAngle);
                    }
                    else if (dotForw < dotAngle)
                    {
                        drawRightOnFaceCenter = true;
                        drawUpOnFace          = true;
                        drawForwOnFace        = true;

                        System.Diagnostics.Debug.Assert(dotRight >= dotAngle);
                    }
                    else
                    {
                        drawRightOnFace = true;
                        drawForwOnFace  = true;
                    }
                }
                else
                if (dotForw < dotAngle)
                {
                    if (dotRight < dotAngle)
                    {
                        drawUpOnFaceCenter = true;
                        drawRightOnFace    = true;
                        drawForwOnFace     = true;

                        System.Diagnostics.Debug.Assert(dotUp >= dotAngle);
                    }
                    else if (dotUp < dotAngle)
                    {
                        drawUpOnFaceCenter = true;
                        drawRightOnFace    = true;
                        drawForwOnFace     = true;

                        System.Diagnostics.Debug.Assert(dotRight >= dotAngle);
                    }
                    else
                    {
                        drawUpOnFace    = true;
                        drawRightOnFace = true;
                    }
                }

                //Draw according to cube visual appearance

                if (!(hideForwardAndUpArrows && RotationRightAxis != 1))
                {
                    if (drawRightOnFaceCenter)
                    {
                        //                VRageRender.MyRenderProxy.DebugDrawSphere((forwStart + forwEnd + forwStart2 + forwEnd2) * 0.25f, 0.2f, Vector3.Right, 1.0f, false, false);
                        Vector3D faceCenter = (forwStart + forwEnd + forwStart2 + forwEnd2) * 0.25f;

                        MyTransparentGeometry.AddBillboardOriented(
                            "ArrowLeftGreen",
                            Vector4.One,
                            faceCenter - RotationForwardDirection * forwDirection * 0.2f - RotationRightDirection * rightDirection * 0.01f,
                            -RotationForwardDirection * forwDirection,
                            -RotationUpDirection * upDirection,
                            0.2f,
                            110, false, projectionId);

                        MyTransparentGeometry.AddBillboardOriented(
                            "ArrowRightGreen",
                            Vector4.One,
                            faceCenter + RotationForwardDirection * forwDirection * 0.2f - RotationRightDirection * rightDirection * 0.01f,
                            RotationForwardDirection * forwDirection,
                            RotationUpDirection * upDirection,
                            0.2f,
                            110, false, projectionId);

                        VRageRender.MyRenderProxy.DebugDrawText3D(faceCenter - RotationForwardDirection * forwDirection * 0.2f - RotationRightDirection * rightDirection * 0.01f, rightControlName2, Color.White, textScale, false, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, projectionId);
                        VRageRender.MyRenderProxy.DebugDrawText3D(faceCenter + RotationForwardDirection * forwDirection * 0.2f - RotationRightDirection * rightDirection * 0.01f, rightControlName1, Color.White, textScale, false, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, projectionId);
                    }
                    else
                    if (drawRightOnFace)
                    {
                        //VRageRender.MyRenderProxy.DebugDrawLine3D(rightStart2, rightEnd2, Color.Red, Color.Red, false);

                        Vector3 normalRightBack, normalRightForw;
                        MyOrientedBoundingBox.GetNormalBetweenEdges(rightAxis, closestRightEdge, closestRightEdge2, out normalRightForw);
                        Vector3D rightCenter          = (rightStart + rightEnd) * 0.5f;
                        Vector3D rightNormalForwWorld = Vector3D.TransformNormal(normalRightForw, drawMatrix);

                        MyOrientedBoundingBox.GetNormalBetweenEdges(rightAxis, closestRightEdge2, closestRightEdge, out normalRightBack);
                        Vector3D rightCenter2         = (rightStart2 + rightEnd2) * 0.5f;
                        Vector3D rightNormalBackWorld = Vector3D.TransformNormal(normalRightBack, drawMatrix);

                        //VRageRender.MyRenderProxy.DebugDrawLine3D(rightCenter, rightCenter + rightNormalForwWorld, Color.Red, Color.Red, false);
                        //VRageRender.MyRenderProxy.DebugDrawLine3D(rightCenter2, rightCenter2 + rightNormalBackWorld, Color.Red, Color.Red, false);

                        int  normalEdge = -1;
                        bool opposite   = false;
                        if (closestRightEdge == 0 && closestRightEdge2 == 3)
                        {
                            normalEdge = closestRightEdge + 1;
                        }
                        else
                        if ((closestRightEdge < closestRightEdge2) || (closestRightEdge == 3 && closestRightEdge2 == 0))
                        {
                            normalEdge = closestRightEdge - 1;
                            opposite   = true;
                        }
                        else
                        {
                            normalEdge = closestRightEdge + 1;
                        }

                        if (RotationRightDirection < 0)
                        {
                            opposite = !opposite;
                        }

                        Vector3 rightOffset;
                        MyOrientedBoundingBox.GetNormalBetweenEdges(rightAxis, closestRightEdge, normalEdge, out rightOffset);
                        Vector3D rightOffsetWorld = Vector3D.TransformNormal(rightOffset, drawMatrix);

                        //VRageRender.MyRenderProxy.DebugDrawText3D(rightCenter + rightNormalForwWorld * 0.6f - rightOffsetWorld * 0.01f, opposite ? rightControlName2 : rightControlName1, Color.White, textScale, false);
                        //VRageRender.MyRenderProxy.DebugDrawText3D(rightCenter2 + rightNormalBackWorld * 0.6f - rightOffsetWorld * 0.01f, opposite ? rightControlName1 : rightControlName2, Color.White, textScale, false);

                        MyTransparentGeometry.AddBillboardOriented(
                            "ArrowGreen",
                            Vector4.One,
                            rightCenter + rightNormalForwWorld * 0.4f - rightOffsetWorld * 0.01f,
                            rightNormalBackWorld,
                            rightDirection,
                            0.5f,
                            110, false, projectionId);

                        MyTransparentGeometry.AddBillboardOriented(
                            "ArrowGreen",
                            Vector4.One,
                            rightCenter2 + rightNormalBackWorld * 0.4f - rightOffsetWorld * 0.01f,
                            rightNormalForwWorld,
                            rightDirection,
                            0.5f,
                            110, false, projectionId);

                        VRageRender.MyRenderProxy.DebugDrawText3D(rightCenter + rightNormalForwWorld * 0.3f - rightOffsetWorld * 0.01f, opposite ? rightControlName1 : rightControlName2, Color.White, textScale, false, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, projectionId);
                        VRageRender.MyRenderProxy.DebugDrawText3D(rightCenter2 + rightNormalBackWorld * 0.3f - rightOffsetWorld * 0.01f, opposite ? rightControlName2 : rightControlName1, Color.White, textScale, false, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, projectionId);
                    }
                    else     //draw on edge
                    {
                        Vector3 normalRightBack, normalRightForw;
                        MyOrientedBoundingBox.GetNormalBetweenEdges(rightAxis, closestRightEdge, closestRightEdge + 1, out normalRightForw);
                        MyOrientedBoundingBox.GetNormalBetweenEdges(rightAxis, closestRightEdge, closestRightEdge - 1, out normalRightBack);
                        Vector3D rightCenter          = (rightStart + rightEnd) * 0.5f;
                        Vector3D rightNormalForwWorld = Vector3D.TransformNormal(normalRightForw, drawMatrix);
                        Vector3D rightNormalBackWorld = Vector3D.TransformNormal(normalRightBack, drawMatrix);
                        //VRageRender.MyRenderProxy.DebugDrawLine3D(rightCenter, rightCenter + rightNormalForwWorld, Color.Red, Color.Red, false);
                        //VRageRender.MyRenderProxy.DebugDrawLine3D(rightCenter, rightCenter + rightNormalBackWorld, Color.Red, Color.Red, false);

                        MyTransparentGeometry.AddBillboardOriented(
                            "ArrowGreen",
                            Vector4.One,
                            rightCenter + rightNormalForwWorld * 0.3f - rightNormalBackWorld * 0.01f,
                            rightNormalForwWorld,
                            rightDirection,
                            0.5f,
                            110, false, projectionId);

                        MyTransparentGeometry.AddBillboardOriented(
                            "ArrowGreen",
                            Vector4.One,
                            rightCenter + rightNormalBackWorld * 0.3f - rightNormalForwWorld * 0.01f,
                            rightNormalBackWorld,
                            rightDirection,
                            0.5f,
                            110, false, projectionId);

                        VRageRender.MyRenderProxy.DebugDrawText3D(rightCenter + rightNormalForwWorld * 0.3f - rightNormalBackWorld * 0.01f, RotationRightDirection < 0 ? rightControlName1 : rightControlName2, Color.White, textScale, false, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, projectionId);
                        VRageRender.MyRenderProxy.DebugDrawText3D(rightCenter + rightNormalBackWorld * 0.3f - rightNormalForwWorld * 0.01f, RotationRightDirection < 0 ? rightControlName2 : rightControlName1, Color.White, textScale, false, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, projectionId);
                    }
                }

                if (!(hideForwardAndUpArrows && RotationUpAxis != 1))
                {
                    if (drawUpOnFaceCenter)
                    {
                        //VRageRender.MyRenderProxy.DebugDrawSphere((forwStart + forwEnd + forwStart2 + forwEnd2) * 0.25f, 0.2f, Vector3.Up, 1.0f, false, false);

                        Vector3D faceCenter = (forwStart + forwEnd + forwStart2 + forwEnd2) * 0.25f;

                        MyTransparentGeometry.AddBillboardOriented(
                            "ArrowLeftRed",
                            Vector4.One,
                            faceCenter - RotationRightDirection * rightDirection * 0.2f - RotationUpDirection * upDirection * 0.01f,
                            -RotationRightDirection * rightDirection,
                            -RotationForwardDirection * forwDirection,
                            0.2f,
                            110, false, projectionId);

                        MyTransparentGeometry.AddBillboardOriented(
                            "ArrowRightRed",
                            Vector4.One,
                            faceCenter + RotationRightDirection * rightDirection * 0.2f - RotationUpDirection * upDirection * 0.01f,
                            RotationRightDirection * rightDirection,
                            RotationForwardDirection * forwDirection,
                            0.2f,
                            110, false, projectionId);

                        VRageRender.MyRenderProxy.DebugDrawText3D(faceCenter - RotationRightDirection * rightDirection * 0.2f - RotationUpDirection * upDirection * 0.01f, upControlName1, Color.White, textScale, false, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, projectionId);
                        VRageRender.MyRenderProxy.DebugDrawText3D(faceCenter + RotationRightDirection * rightDirection * 0.2f - RotationUpDirection * upDirection * 0.01f, upControlName2, Color.White, textScale, false, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, projectionId);
                    }
                    else
                    if (drawUpOnFace)
                    {
                        //VRageRender.MyRenderProxy.DebugDrawLine3D(upStart2, upEnd2, Color.Green, Color.Green, false);

                        Vector3 normalUpBack, normalUpForw;
                        MyOrientedBoundingBox.GetNormalBetweenEdges(upAxis, closestUpEdge, closestUpEdge2, out normalUpForw);
                        Vector3D upCenter          = (upStart + upEnd) * 0.5f;
                        Vector3  upNormalForwWorld = Vector3.TransformNormal(normalUpForw, drawMatrix);

                        MyOrientedBoundingBox.GetNormalBetweenEdges(upAxis, closestUpEdge2, closestUpEdge, out normalUpBack);
                        Vector3D upCenter2         = (upStart2 + upEnd2) * 0.5f;
                        Vector3  upNormalBackWorld = Vector3.TransformNormal(normalUpBack, drawMatrix);

                        //VRageRender.MyRenderProxy.DebugDrawLine3D(upCenter, upCenter + upNormalForwWorld, Color.Green, Color.Green, false);
                        //VRageRender.MyRenderProxy.DebugDrawLine3D(upCenter2, upCenter2 + upNormalBackWorld, Color.Green, Color.Green, false);

                        int  normalEdge = -1;
                        bool opposite   = false;
                        if (closestUpEdge == 0 && closestUpEdge2 == 3)
                        {
                            normalEdge = closestUpEdge + 1;
                        }
                        else
                        if ((closestUpEdge < closestUpEdge2) || (closestUpEdge == 3 && closestUpEdge2 == 0))
                        {
                            normalEdge = closestUpEdge - 1;
                            opposite   = true;
                        }
                        else
                        {
                            normalEdge = closestUpEdge + 1;
                        }

                        if (RotationUpDirection < 0)
                        {
                            opposite = !opposite;
                        }

                        Vector3 upOffset;
                        MyOrientedBoundingBox.GetNormalBetweenEdges(upAxis, closestUpEdge, normalEdge, out upOffset);
                        Vector3 upOffsetWorld = Vector3.TransformNormal(upOffset, drawMatrix);

                        //VRageRender.MyRenderProxy.DebugDrawText3D(upCenter + upNormalForwWorld * 0.6f - upOffsetWorld * 0.01f, opposite ? upControlName1 : upControlName2, Color.White, textScale, false);
                        //VRageRender.MyRenderProxy.DebugDrawText3D(upCenter2 + upNormalBackWorld * 0.6f - upOffsetWorld * 0.01f, opposite ? upControlName2 : upControlName1, Color.White, textScale, false);

                        MyTransparentGeometry.AddBillboardOriented(
                            "ArrowRed",
                            Vector4.One,
                            upCenter + upNormalForwWorld * 0.4f - upOffsetWorld * 0.01f,
                            upNormalBackWorld,
                            upDirection,
                            0.5f,
                            110, false, projectionId);

                        MyTransparentGeometry.AddBillboardOriented(
                            "ArrowRed",
                            Vector4.One,
                            upCenter2 + upNormalBackWorld * 0.4f - upOffsetWorld * 0.01f,
                            upNormalForwWorld,
                            upDirection,
                            0.5f,
                            110, false, projectionId);

                        VRageRender.MyRenderProxy.DebugDrawText3D(upCenter + upNormalForwWorld * 0.3f - upOffsetWorld * 0.01f, opposite ? upControlName2 : upControlName1, Color.White, textScale, false, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, projectionId);
                        VRageRender.MyRenderProxy.DebugDrawText3D(upCenter2 + upNormalBackWorld * 0.3f - upOffsetWorld * 0.01f, opposite ? upControlName1 : upControlName2, Color.White, textScale, false, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, projectionId);
                    }
                    else     //draw on edge
                    {
                        Vector3 normalUpBack, normalUpForw;
                        MyOrientedBoundingBox.GetNormalBetweenEdges(upAxis, closestUpEdge, closestUpEdge + 1, out normalUpForw);
                        MyOrientedBoundingBox.GetNormalBetweenEdges(upAxis, closestUpEdge, closestUpEdge - 1, out normalUpBack);
                        Vector3D upCenter          = (upStart + upEnd) * 0.5f;
                        Vector3  upNormalForwWorld = Vector3.TransformNormal(normalUpForw, drawMatrix);
                        Vector3  upNormalBackWorld = Vector3.TransformNormal(normalUpBack, drawMatrix);
                        //VRageRender.MyRenderProxy.DebugDrawLine3D(upCenter, upCenter + upNormalForwWorld, Color.Green, Color.Green, false);
                        //VRageRender.MyRenderProxy.DebugDrawLine3D(upCenter, upCenter + upNormalBackWorld, Color.Green, Color.Green, false);

                        MyTransparentGeometry.AddBillboardOriented(
                            "ArrowRed",
                            Vector4.One,
                            upCenter + upNormalForwWorld * 0.3f - upNormalBackWorld * 0.01f,
                            upNormalForwWorld,
                            upDirection,
                            0.5f,
                            110, false, projectionId);

                        MyTransparentGeometry.AddBillboardOriented(
                            "ArrowRed",
                            Vector4.One,
                            upCenter + upNormalBackWorld * 0.3f - upNormalForwWorld * 0.01f,
                            upNormalBackWorld,
                            upDirection,
                            0.5f,
                            110, false, projectionId);

                        VRageRender.MyRenderProxy.DebugDrawText3D(upCenter + upNormalForwWorld * 0.6f - upNormalBackWorld * 0.01f, RotationUpDirection > 0 ? upControlName1 : upControlName2, Color.White, textScale, false, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, projectionId);
                        VRageRender.MyRenderProxy.DebugDrawText3D(upCenter + upNormalBackWorld * 0.6f - upNormalForwWorld * 0.01f, RotationUpDirection > 0 ? upControlName2 : upControlName1, Color.White, textScale, false, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, projectionId);
                    }
                }

                if (!(hideForwardAndUpArrows && RotationForwardAxis != 1))
                {
                    if (drawForwOnFaceCenter)
                    {
                        //VRageRender.MyRenderProxy.DebugDrawSphere((rightStart + rightEnd + rightStart2 + rightEnd2) * 0.25f, 0.2f, Vector3.Backward, 1.0f, false, false);

                        Vector3D faceCenter = (rightStart + rightEnd + rightStart2 + rightEnd2) * 0.25f;

                        MyTransparentGeometry.AddBillboardOriented(
                            "ArrowLeftBlue",
                            Vector4.One,
                            faceCenter + RotationUpDirection * upDirection * 0.2f - RotationForwardDirection * forwDirection * 0.01f,
                            RotationUpDirection * upDirection,
                            -RotationRightDirection * rightDirection,
                            0.2f,
                            110, false, projectionId);

                        MyTransparentGeometry.AddBillboardOriented(
                            "ArrowRightBlue",
                            Vector4.One,
                            faceCenter - RotationUpDirection * upDirection * 0.2f - RotationForwardDirection * forwDirection * 0.01f,
                            -RotationUpDirection * upDirection,
                            RotationRightDirection * rightDirection,
                            0.2f,
                            110, false, projectionId);

                        VRageRender.MyRenderProxy.DebugDrawText3D(faceCenter + RotationUpDirection * upDirection * 0.2f - RotationForwardDirection * forwDirection * 0.01f, forwControlName1, Color.White, textScale, false, MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_CENTER, projectionId);
                        VRageRender.MyRenderProxy.DebugDrawText3D(faceCenter - RotationUpDirection * upDirection * 0.2f - RotationForwardDirection * forwDirection * 0.01f, forwControlName2, Color.White, textScale, false, MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_CENTER, projectionId);
                    }
                    else
                    if (drawForwOnFace)
                    {
                        //VRageRender.MyRenderProxy.DebugDrawLine3D(forwStart2, forwEnd2, Color.Blue, Color.Blue, false);

                        Vector3 normalForwBack, normalForwForw;
                        MyOrientedBoundingBox.GetNormalBetweenEdges(forwAxis, closestForwEdge, closestForwEdge2, out normalForwForw);
                        Vector3D forwCenter          = (forwStart + forwEnd) * 0.5f;
                        Vector3  forwNormalForwWorld = Vector3.TransformNormal(normalForwForw, drawMatrix);

                        MyOrientedBoundingBox.GetNormalBetweenEdges(forwAxis, closestForwEdge2, closestForwEdge, out normalForwBack);
                        Vector3D forwCenter2         = (forwStart2 + forwEnd2) * 0.5f;
                        Vector3  forwNormalBackWorld = Vector3.TransformNormal(normalForwBack, drawMatrix);

                        //VRageRender.MyRenderProxy.DebugDrawLine3D(forwCenter, forwCenter + forwNormalForwWorld, Color.Blue, Color.Blue, false);
                        //VRageRender.MyRenderProxy.DebugDrawLine3D(forwCenter2, forwCenter2 + forwNormalBackWorld, Color.Blue, Color.Blue, false);

                        int  normalEdge = -1;
                        bool opposite   = false;
                        if (closestForwEdge == 0 && closestForwEdge2 == 3)
                        {
                            normalEdge = closestForwEdge + 1;
                        }
                        else
                        if ((closestForwEdge < closestForwEdge2) || (closestForwEdge == 3 && closestForwEdge2 == 0))
                        {
                            normalEdge = closestForwEdge - 1;
                            opposite   = true;
                        }
                        else
                        {
                            normalEdge = closestForwEdge + 1;
                        }

                        if (RotationForwardDirection < 0)
                        {
                            opposite = !opposite;
                        }

                        Vector3 forwOffset;
                        MyOrientedBoundingBox.GetNormalBetweenEdges(forwAxis, closestForwEdge, normalEdge, out forwOffset);
                        Vector3 forwOffsetWorld = Vector3.TransformNormal(forwOffset, drawMatrix);

                        //VRageRender.MyRenderProxy.DebugDrawText3D(forwCenter + forwNormalForwWorld * 0.6f - forwOffsetWorld * 0.01f, opposite ? forwControlName2 : forwControlName1, Color.White, textScale, false);
                        //VRageRender.MyRenderProxy.DebugDrawText3D(forwCenter2 + forwNormalBackWorld * 0.6f - forwOffsetWorld * 0.01f, opposite ? forwControlName1 : forwControlName2, Color.White, textScale, false);

                        MyTransparentGeometry.AddBillboardOriented(
                            "ArrowBlue",
                            Vector4.One,
                            forwCenter + forwNormalForwWorld * 0.4f - forwOffsetWorld * 0.01f,
                            forwNormalBackWorld,
                            forwDirection,
                            0.5f,
                            110, false, projectionId);

                        MyTransparentGeometry.AddBillboardOriented(
                            "ArrowBlue",
                            Vector4.One,
                            forwCenter2 + forwNormalBackWorld * 0.4f - forwOffsetWorld * 0.01f,
                            forwNormalForwWorld,
                            forwDirection,
                            0.5f,
                            110, false, projectionId);

                        VRageRender.MyRenderProxy.DebugDrawText3D(forwCenter + forwNormalForwWorld * 0.3f - forwOffsetWorld * 0.01f, opposite ? forwControlName1 : forwControlName2, Color.White, textScale, false, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, projectionId);
                        VRageRender.MyRenderProxy.DebugDrawText3D(forwCenter2 + forwNormalBackWorld * 0.3f - forwOffsetWorld * 0.01f, opposite ? forwControlName2 : forwControlName1, Color.White, textScale, false, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, projectionId);
                    }
                    else     //draw on edge
                    {
                        Vector3 normalForwBack, normalForwForw;
                        MyOrientedBoundingBox.GetNormalBetweenEdges(forwAxis, closestForwEdge, closestForwEdge + 1, out normalForwForw);
                        MyOrientedBoundingBox.GetNormalBetweenEdges(forwAxis, closestForwEdge, closestForwEdge - 1, out normalForwBack);
                        Vector3D forwCenter          = (forwStart + forwEnd) * 0.5f;
                        Vector3  forwNormalForwWorld = Vector3.TransformNormal(normalForwForw, drawMatrix);
                        Vector3  forwNormalBackWorld = Vector3.TransformNormal(normalForwBack, drawMatrix);
                        //VRageRender.MyRenderProxy.DebugDrawLine3D(forwCenter, forwCenter + forwNormalForwWorld, Color.Blue, Color.Blue, false);
                        //VRageRender.MyRenderProxy.DebugDrawLine3D(forwCenter, forwCenter + forwNormalBackWorld, Color.Blue, Color.Blue, false);

                        MyTransparentGeometry.AddBillboardOriented(
                            "ArrowBlue",
                            Vector4.One,
                            forwCenter + forwNormalForwWorld * 0.3f - forwNormalBackWorld * 0.01f,
                            forwNormalForwWorld,
                            forwDirection,
                            0.5f,
                            110, false, projectionId);

                        MyTransparentGeometry.AddBillboardOriented(
                            "ArrowBlue",
                            Vector4.One,
                            forwCenter + forwNormalBackWorld * 0.3f - forwNormalForwWorld * 0.01f,
                            forwNormalBackWorld,
                            forwDirection,
                            0.5f,
                            110, false, projectionId);

                        VRageRender.MyRenderProxy.DebugDrawText3D(forwCenter + forwNormalForwWorld * 0.3f - forwNormalBackWorld * 0.01f, RotationForwardDirection < 0 ? forwControlName1 : forwControlName2, Color.White, textScale, false, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, projectionId);
                        VRageRender.MyRenderProxy.DebugDrawText3D(forwCenter + forwNormalBackWorld * 0.3f - forwNormalForwWorld * 0.01f, RotationForwardDirection < 0 ? forwControlName2 : forwControlName1, Color.White, textScale, false, MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, projectionId);
                    }
                }
            }
        }
Esempio n. 4
0
        private void DrawTarget()
        {
            var s           = _session;
            var focus       = s.TrackingAi.Construct.Data.Repo.FocusData;
            var detailedHud = !_session.Settings.ClientConfig.MinimalHud;

            for (int i = 0; i < s.TrackingAi.TargetState.Length; i++)
            {
                if (focus.Target[i] <= 0)
                {
                    continue;
                }
                var lockMode = focus.Locked[i];

                var targetState = s.TrackingAi.TargetState[i];
                var isActive    = i == focus.ActiveId;
                var primary     = i == 0;
                var shielded    = detailedHud && targetState.ShieldHealth >= 0;

                Dictionary <string, HudInfo> collection;
                if (detailedHud)
                {
                    collection = primary ? _primaryTargetHuds : _secondaryTargetHuds;
                }
                else
                {
                    collection = primary ? _primaryMinimalHuds : _secondaryMinimalHuds;
                }

                foreach (var hud in collection.Keys)
                {
                    if (isActive && (hud == InactiveShield || hud == InactiveNoShield))
                    {
                        continue;
                    }

                    if (!isActive && (hud == ActiveShield || hud == ActiveNoShield))
                    {
                        continue;
                    }

                    if (shielded && (hud == ActiveNoShield || hud == InactiveNoShield))
                    {
                        continue;
                    }
                    if (!shielded && (hud == ActiveShield || hud == InactiveShield))
                    {
                        continue;
                    }

                    Vector3D offset;
                    Vector2  localOffset;

                    float      scale;
                    float      screenScale;
                    float      fontScale;
                    MyStringId textureName;
                    var        hudInfo = collection[hud];
                    hudInfo.GetTextureInfo(s, out textureName, out scale, out screenScale, out fontScale, out offset, out localOffset);

                    var color = Color.White;
                    switch (lockMode)
                    {
                    case FocusData.LockModes.None:
                        color = Color.White;
                        break;

                    case FocusData.LockModes.Locked:
                        color = s.Count < 60 ? Color.White : new Color(255, 255, 255, 64);
                        break;

                    case FocusData.LockModes.ExclusiveLock:
                        color = s.SCount < 30 ? Color.White : new Color(255, 255, 255, 64);
                        break;
                    }

                    var hudOpacity = MathHelper.Clamp(_session.UIHudOpacity, 0.25f, 1f);
                    color = new Vector4(1, 1, 1, hudOpacity);
                    MyTransparentGeometry.AddBillboardOriented(textureName, color, offset, s.CameraMatrix.Left, s.CameraMatrix.Up, screenScale, BlendTypeEnum.PostPP);
                    var quickUpdate = _session.UiInput.FirstPersonView && _session.HudUi.NeedsUpdate && _session.ControlledEntity is IMyGunBaseUser;
                    if (s.Tick20 || quickUpdate)
                    {
                        for (int j = 0; j < 11; j++)
                        {
                            string  text;
                            Vector2 textOffset;
                            if (TargetTextStatus(j, targetState, scale, localOffset, shielded, detailedHud, out text, out textOffset))
                            {
                                var textColor   = Color.White;
                                var fontSize    = (float)Math.Round(21 * fontScale, 1);
                                var fontHeight  = 0.75f;
                                var fontAge     = !quickUpdate ? 18 : 0;
                                var fontJustify = Hud.Justify.None;
                                var fontType    = Hud.FontType.Shadow;
                                var elementId   = MathFuncs.UniqueId(i, j);

                                s.HudUi.AddText(text: text, x: textOffset.X, y: textOffset.Y, elementId: elementId, ttl: fontAge, color: textColor, justify: fontJustify, fontType: fontType, fontSize: fontSize, heightScale: fontHeight);
                            }
                        }
                    }
                }

                MyEntity target;
                if (isActive && MyEntities.TryGetEntityById(focus.Target[focus.ActiveId], out target))
                {
                    var targetSphere = target.PositionComp.WorldVolume;
                    var targetCenter = targetSphere.Center;
                    var screenPos    = s.Camera.WorldToScreen(ref targetCenter);

                    if (Vector3D.Transform(targetCenter, s.Camera.ViewMatrix).Z > 0)
                    {
                        screenPos.X *= -1;
                        screenPos.Y  = -1;
                    }

                    var dotpos      = new Vector2D(MathHelper.Clamp(screenPos.X, -0.98, 0.98), MathHelper.Clamp(screenPos.Y, -0.98, 0.98));
                    var screenScale = 0.1 * s.ScaleFov;
                    dotpos.X *= (float)(screenScale * _session.AspectRatio);
                    dotpos.Y *= (float)screenScale;
                    screenPos = Vector3D.Transform(new Vector3D(dotpos.X, dotpos.Y, -0.1), s.CameraMatrix);
                    MyTransparentGeometry.AddBillboardOriented(_active, Color.White, screenPos, s.CameraMatrix.Left, s.CameraMatrix.Up, (float)screenScale * 0.075f, BlendTypeEnum.PostPP);
                }
            }
        }
        //  Update position, check collisions, etc. and draw if particle still lives.
        //  Return false if particle dies/timeouts in this tick.
        public bool Draw(VRageRender.MyBillboard billboard)
        {
            MyTransparentGeometry.StartParticleProfilingBlock("Distance calculation");
            //  This time is scaled according to planned lifespan of the particle

            // Distance for sorting
            billboard.DistanceSquared = (float)Vector3D.DistanceSquared(MyTransparentGeometry.Camera.Translation, m_actualPosition);

            MyTransparentGeometry.EndParticleProfilingBlock();

            // If distance to camera is really small don't draw it.
            if (billboard.DistanceSquared <= 0.1f)
            {
                return(false);
            }

            MyTransparentGeometry.StartParticleProfilingBlock("Quad calculation");

            MyTransparentGeometry.StartParticleProfilingBlock("actualRadius");
            float actualRadius = 1;

            Radius.GetInterpolatedValue <float>(m_normalizedTime, out actualRadius);
            MyTransparentGeometry.EndParticleProfilingBlock();

            billboard.ContainedBillboards.Clear();

            billboard.Near   = m_generation.GetEffect().Near;
            billboard.Lowres = m_generation.GetEffect().LowRes || VRageRender.MyRenderConstants.RenderQualityProfile.LowResParticles;
            billboard.CustomViewProjection = -1;
            billboard.ParentID             = -1;

            float alpha = 1;

            if (Type == MyParticleTypeEnum.Point)
            {
                MyTransparentGeometry.StartParticleProfilingBlock("GetBillboardQuadRotated");
                GetBillboardQuadRotated(billboard, ref m_actualPosition, actualRadius, m_actualAngle);
                MyTransparentGeometry.EndParticleProfilingBlock();
            }
            else if (Type == MyParticleTypeEnum.Line)
            {
                if (MyUtils.IsZero(Velocity.LengthSquared()))
                {
                    Velocity = MyUtils.GetRandomVector3Normalized();
                }

                MyQuadD quad = new MyQuadD();

                MyPolyLineD polyLine = new MyPolyLineD();
                polyLine.LineDirectionNormalized = MyUtils.Normalize(Velocity);

                if (m_actualAngle > 0)
                {
                    polyLine.LineDirectionNormalized = Vector3.TransformNormal(polyLine.LineDirectionNormalized, Matrix.CreateRotationY(MathHelper.ToRadians(m_actualAngle)));
                }

                polyLine.Point0   = m_actualPosition;
                polyLine.Point1.X = m_actualPosition.X + polyLine.LineDirectionNormalized.X * actualRadius;
                polyLine.Point1.Y = m_actualPosition.Y + polyLine.LineDirectionNormalized.Y * actualRadius;
                polyLine.Point1.Z = m_actualPosition.Z + polyLine.LineDirectionNormalized.Z * actualRadius;

                if (m_actualAngle > 0)
                { //centerize
                    polyLine.Point0.X = polyLine.Point0.X - polyLine.LineDirectionNormalized.X * actualRadius * 0.5f;
                    polyLine.Point0.Y = polyLine.Point0.Y - polyLine.LineDirectionNormalized.Y * actualRadius * 0.5f;
                    polyLine.Point0.Z = polyLine.Point0.Z - polyLine.LineDirectionNormalized.Z * actualRadius * 0.5f;
                    polyLine.Point1.X = polyLine.Point1.X - polyLine.LineDirectionNormalized.X * actualRadius * 0.5f;
                    polyLine.Point1.Y = polyLine.Point1.Y - polyLine.LineDirectionNormalized.Y * actualRadius * 0.5f;
                    polyLine.Point1.Z = polyLine.Point1.Z - polyLine.LineDirectionNormalized.Z * actualRadius * 0.5f;
                }

                polyLine.Thickness = Thickness;
                var camPos = MyTransparentGeometry.Camera.Translation;
                MyUtils.GetPolyLineQuad(out quad, ref polyLine, camPos);

                if (this.m_generation.AlphaAnisotropic)
                {
                    float angle     = 1 - Math.Abs(Vector3.Dot(MyUtils.Normalize(MyTransparentGeometry.Camera.Forward), polyLine.LineDirectionNormalized));
                    float alphaCone = (float)Math.Pow(angle, 0.5f);
                    alpha = alphaCone;
                }

                billboard.Position0 = quad.Point0;
                billboard.Position1 = quad.Point1;
                billboard.Position2 = quad.Point2;
                billboard.Position3 = quad.Point3;
            }
            else if (Type == MyParticleTypeEnum.Trail)
            {
                if (Quad.Point0 == Quad.Point2) //not moving particle
                {
                    return(false);
                }
                if (Quad.Point1 == Quad.Point3) //not moving particle was previous one
                {
                    return(false);
                }
                if (Quad.Point0 == Quad.Point3) //not moving particle was previous one
                {
                    return(false);
                }

                billboard.Position0 = Quad.Point0;
                billboard.Position1 = Quad.Point1;
                billboard.Position2 = Quad.Point2;
                billboard.Position3 = Quad.Point3;

                //if (this.m_generation.AlphaAnisotropic)

                /*   { //Trails are anisotropic by default (nobody wants them to see ugly)
                 *     Vector3 lineDir = Vector3.Normalize(Quad.Point1 - Quad.Point0);
                 *     float angle = 1 - Math.Abs(Vector3.Dot(MyMwcUtils.Normalize(MyCamera.ForwardVector), lineDir));
                 *     float alphaCone = (float)Math.Pow(angle, 0.3f);
                 *     alpha = alphaCone;
                 * }*/
            }
            else
            {
                throw new NotSupportedException(Type + " is not supported particle type");
            }

            MyTransparentGeometry.EndParticleProfilingBlock();

            MyTransparentGeometry.StartParticleProfilingBlock("Material calculation");

            Vector4 color;

            Color.GetInterpolatedValue <Vector4>(m_normalizedTime, out color);

            var   material1         = MyTransparentMaterials.GetMaterial("ErrorMaterial");
            var   material2         = MyTransparentMaterials.GetMaterial("ErrorMaterial");
            float textureBlendRatio = 0;

            if ((Flags & ParticleFlags.BlendTextures) != 0)
            {
                float prevTime, nextTime, difference;
                Material.GetPreviousValue(m_normalizedTime, out material1, out prevTime);
                Material.GetNextValue(m_normalizedTime, out material2, out nextTime, out difference);

                if (prevTime != nextTime)
                {
                    textureBlendRatio = (m_normalizedTime - prevTime) * difference;
                }
            }
            else
            {
                Material.GetInterpolatedValue(m_normalizedTime, out material1);
            }

            MyTransparentGeometry.EndParticleProfilingBlock();

            //This gets 0.44ms for 2000 particles
            MyTransparentGeometry.StartParticleProfilingBlock("billboard.Start");


            billboard.Material          = material1.Name;
            billboard.BlendMaterial     = material2.Name;
            billboard.BlendTextureRatio = textureBlendRatio;
            billboard.EnableColorize    = false;

            billboard.Color = color * alpha * m_generation.GetEffect().UserColorMultiplier;

            MyTransparentGeometry.EndParticleProfilingBlock();

            return(true);
        }
Esempio n. 6
0
        private void DrawJetpackThrusts(bool updateCalled)
        {
            if (m_character.CanDrawThrusts() == false)
            {
                return;
            }

            //VRageRender.MyRenderProxy.DebugDrawLine3D(WorldMatrix.Translation, WorldMatrix.Translation + Physics.LinearAcceleration, Color.White, Color.Green, false);

            foreach (MyJetpackThrust thrust in m_jetpackThrusts)
            {
                float    strength     = 0;
                Vector3D position     = Vector3D.Zero;
                var      worldToLocal = MatrixD.Invert(Container.Entity.PositionComp.WorldMatrix);

                if (m_character.JetpackEnabled && m_character.IsJetpackPowered() && !m_character.IsInFirstPersonView)
                {
                    var      thrustMatrix = (MatrixD)thrust.ThrustMatrix * Container.Entity.PositionComp.WorldMatrix;
                    Vector3D forward      = Vector3D.TransformNormal(thrust.Forward, thrustMatrix);
                    position  = thrustMatrix.Translation;
                    position += forward * thrust.Offset;

                    float flameScale = 0.05f;
                    if (updateCalled)
                    {
                        thrust.ThrustRadius = MyUtils.GetRandomFloat(0.9f, 1.1f) * flameScale;
                    }
                    strength = Vector3.Dot(forward, -Container.Entity.Physics.LinearAcceleration);
                    strength = MathHelper.Clamp(strength * 0.5f, 0.1f, 1f);

                    if (strength > 0 && thrust.ThrustRadius > 0)
                    {
                        float angle     = 1 - Math.Abs(Vector3.Dot(MyUtils.Normalize(MySector.MainCamera.Position - position), forward));
                        float alphaCone = (1 - (float)Math.Pow(1 - angle, 30)) * 0.5f;

                        if (updateCalled)
                        {
                            thrust.ThrustLength    = strength * 10 * MyUtils.GetRandomFloat(0.6f, 1.0f) * flameScale;
                            thrust.ThrustThickness = MyUtils.GetRandomFloat(thrust.ThrustRadius * 0.90f, thrust.ThrustRadius);
                        }

                        //  We move polyline particle backward, because we are stretching ball texture and it doesn't look good if stretched. This will hide it.
                        MyTransparentGeometry.AddLineBillboard(thrust.ThrustMaterial, thrust.Light.Color * alphaCone, position /*- forward * thrust.ThrustLength * 0.25f*/,
                                                               GetRenderObjectID(), ref worldToLocal, forward, thrust.ThrustLength, thrust.ThrustThickness);
                    }

                    if (thrust.ThrustRadius > 0)
                    {
                        MyTransparentGeometry.AddPointBillboard(thrust.ThrustMaterial, thrust.Light.Color, position, GetRenderObjectID(), ref worldToLocal, thrust.ThrustRadius, 0);
                    }
                }
                else
                {
                    if (updateCalled || (m_character.IsUsing != null))
                    {
                        thrust.ThrustRadius = 0;
                    }
                }

                if (thrust.Light != null)
                {
                    if (thrust.ThrustRadius > 0)
                    {
                        thrust.Light.LightOn   = true;
                        thrust.Light.Intensity = 1.3f + thrust.ThrustLength * 1.2f;

                        thrust.Light.Range = thrust.ThrustRadius * 7f + thrust.ThrustLength / 10;

                        thrust.Light.Position = Vector3D.Transform(position, MatrixD.Invert(Container.Entity.PositionComp.WorldMatrix));
                        thrust.Light.ParentID = GetRenderObjectID();

                        thrust.Light.GlareOn = true;

                        thrust.Light.GlareIntensity = 0.5f + thrust.ThrustLength * 4;

                        thrust.Light.GlareMaterial = "GlareJetpack";
                        thrust.Light.GlareType     = VRageRender.Lights.MyGlareTypeEnum.Normal;

                        thrust.Light.GlareSize = (thrust.ThrustRadius * 2.4f + thrust.ThrustLength * 0.2f) * thrust.ThrustGlareSize;

                        thrust.Light.GlareQuerySize = 0.3f;
                        thrust.Light.UpdateLight();
                    }
                    else
                    {
                        thrust.Light.GlareOn = false;
                        thrust.Light.LightOn = false;
                        thrust.Light.UpdateLight();
                    }
                }
            }
        }
        private void CreateParticle(Vector3D interpolatedEffectPosition)
        {
            MyAnimatedParticle particle = MyTransparentGeometry.AddAnimatedParticle();

            if (particle == null)
            {
                return;
            }

            particle.Type = (MyParticleTypeEnum)ParticleType.GetValue <int>();

            MyUtils.AssertIsValid(m_effect.WorldMatrix);

            Vector3D startOffset;

            m_emitter.CalculateStartPosition(m_effect.GetElapsedTime(), MatrixD.CreateWorld(interpolatedEffectPosition, m_effect.WorldMatrix.Forward, m_effect.WorldMatrix.Up), m_effect.UserEmitterScale * m_effect.UserScale, out startOffset, out particle.StartPosition);

            Vector3D particlePosition = particle.StartPosition;

            m_AABB = m_AABB.Include(ref particlePosition);

            Life.GetInterpolatedValue <float>(m_effect.GetElapsedTime(), out particle.Life);
            float lifeVar = LifeVar;

            if (lifeVar > 0)
            {
                particle.Life = MathHelper.Max(MyUtils.GetRandomFloat(particle.Life - lifeVar, particle.Life + lifeVar), 0.1f);
            }

            Vector3 vel;

            Velocity.GetInterpolatedValue <Vector3>(m_effect.GetElapsedTime(), out vel);
            vel.X            *= m_effect.UserScale;
            vel.Y            *= m_effect.UserScale;
            vel.Z            *= m_effect.UserScale;
            particle.Velocity = vel;

            if (VelocityDir == MyVelocityDirEnum.FromEmitterCenter)
            {
                if (!MyUtils.IsZero(startOffset - particle.StartPosition))
                {
                    float length = particle.Velocity.Length();
                    particle.Velocity = MyUtils.Normalize(particle.StartPosition - (Vector3D)startOffset) * length;
                }
            }
            particle.Velocity = Vector3D.TransformNormal(particle.Velocity, GetEffect().WorldMatrix);

            Angle.GetInterpolatedValue <float>(m_effect.GetElapsedTime(), out particle.Angle);
            float angleVar = AngleVar;

            if (angleVar > 0)
            {
                particle.Angle = MyUtils.GetRandomFloat(particle.Angle - AngleVar, particle.Angle + AngleVar);
            }

            RotationSpeed.GetInterpolatedValue <float>(m_effect.GetElapsedTime(), out particle.RotationSpeed);
            float rotationSpeedVar = RotationSpeedVar;

            if (rotationSpeedVar > 0)
            {
                particle.RotationSpeed = MyUtils.GetRandomFloat(particle.RotationSpeed - RotationSpeedVar, particle.RotationSpeed + RotationSpeedVar);
            }

            float radiusVar;

            RadiusVar.GetInterpolatedValue <float>(m_effect.GetElapsedTime(), out radiusVar);
            float lodRadius = 1.0f;

            if (GetEffect().EnableLods)
            {
                LODRadius.GetInterpolatedValue <float>(GetEffect().Distance, out lodRadius);
            }

            Radius.GetInterpolatedKeys(m_effect.GetElapsedTime(),
                                       radiusVar,
                                       (EnableCustomRadius.GetValue <bool>() ? m_effect.UserRadiusMultiplier : 1.0f)
                                       * lodRadius
                                       * GetEffect().UserScale,
                                       particle.Radius);

            if (particle.Type != MyParticleTypeEnum.Point)
            {
                Thickness.GetInterpolatedValue <float>(m_effect.GetElapsedTime(), out particle.Thickness);
            }

            particle.Thickness *= lodRadius;

            float colorVar;

            ColorVar.GetInterpolatedValue <float>(m_effect.GetElapsedTime(), out colorVar);
            Color.GetInterpolatedKeys(m_effect.GetElapsedTime(), colorVar, 1.0f, particle.Color);

            Material.GetInterpolatedKeys(m_effect.GetElapsedTime(), 0, 1.0f, particle.Material);

            particle.Flags  = 0;
            particle.Flags |= BlendTextures.GetValue <bool>() ? MyAnimatedParticle.ParticleFlags.BlendTextures : 0;
            particle.Flags |= GetEffect().IsInFrustum ? MyAnimatedParticle.ParticleFlags.IsInFrustum : 0;

            particle.Start(this);

            m_particles.Add(particle);
        }
Esempio n. 8
0
                /// <summary>
                /// Adds a triangles in the given starting index range
                /// </summary>
                public static void AddTriangleRange(Vector2I range, IReadOnlyList <int> indices, IReadOnlyList <Vector2> vertices, ref PolyMaterial mat, MatrixD[] matrixRef)
                {
                    var bbPool     = instance.bbPoolBack;
                    var bbDataBack = instance.flatTriangleList;
                    var bbBuf      = instance.bbBuf;
                    var matList    = instance.matrixBuf;
                    var matTable   = instance.matrixTable;

                    // Find matrix index in table or add it
                    int matrixID;

                    if (!matTable.TryGetValue(matrixRef, out matrixID))
                    {
                        matrixID = matList.Count;
                        matList.Add(matrixRef[0]);
                        matTable.Add(matrixRef, matrixID);
                    }

                    // Get triangle count, ensure enough billboards are in the pool and add them to the
                    // render queue before writing QB data to buffer
                    int iMax          = indices.Count,
                        triangleCount = (range.Y - range.X) / 3,
                        bbRemaining   = bbPool.Count - bbDataBack.Count,
                        bbToAdd       = Math.Max(triangleCount - bbRemaining, 0);

                    instance.AddNewBB(bbToAdd);

                    for (int i = bbDataBack.Count; i < triangleCount + bbDataBack.Count; i++)
                    {
                        bbBuf.Add(bbPool[i]);
                    }

                    MyTransparentGeometry.AddBillboards(bbBuf, false);
                    bbBuf.Clear();

                    bbDataBack.EnsureCapacity(bbDataBack.Count + triangleCount);

                    for (int i = range.X; i <= range.Y; i += 3)
                    {
                        var bb = new FlatTriangleBillboardData
                        {
                            Item1 = BlendTypeEnum.PostPP,
                            Item2 = new Vector2I(bbDataBack.Count, matrixID),
                            Item3 = mat.textureID,
                            Item4 = new MyTuple <Vector4, BoundingBox2?>(mat.bbColor, null),
                            Item5 = new MyTuple <Vector2, Vector2, Vector2>
                                    (
                                mat.texCoords[indices[i % iMax]],
                                mat.texCoords[indices[(i + 1) % iMax]],
                                mat.texCoords[indices[(i + 2) % iMax]]
                                    ),
                            Item6 = new MyTuple <Vector2, Vector2, Vector2>
                                    (
                                vertices[indices[i % iMax]],
                                vertices[indices[(i + 1) % iMax]],
                                vertices[indices[(i + 2) % iMax]]
                                    ),
                        };
                        bbDataBack.Add(bb);
                    }
                }
Esempio n. 9
0
                /// <summary>
                /// Adds a list of textured quads in one batch using QuadBoard data
                /// </summary>
                public static void AddQuads(IReadOnlyList <BoundedQuadBoard> quads, MatrixD[] matrixRef, BoundingBox2?mask = null,
                                            Vector2 offset = default(Vector2), float scale = 1f)
                {
                    var bbPool     = instance.bbPoolBack;
                    var bbDataBack = instance.flatTriangleList;
                    var bbBuf      = instance.bbBuf;
                    var matList    = instance.matrixBuf;
                    var matTable   = instance.matrixTable;

                    // Find matrix index in table or add it
                    int matrixID;

                    if (!matTable.TryGetValue(matrixRef, out matrixID))
                    {
                        matrixID = matList.Count;
                        matList.Add(matrixRef[0]);
                        matTable.Add(matrixRef, matrixID);
                    }

                    int triangleCount = quads.Count * 2,
                        bbCountStart  = bbDataBack.Count;

                    bbDataBack.EnsureCapacity(bbDataBack.Count + triangleCount);

                    for (int i = 0; i < quads.Count; i++)
                    {
                        BoundedQuadBoard    boundedQB = quads[i];
                        BoundedQuadMaterial mat       = boundedQB.quadBoard.materialData;
                        Vector2             size      = boundedQB.bounds.Size * scale,
                                            center = offset + boundedQB.bounds.Center * scale;

                        BoundingBox2    bounds      = BoundingBox2.CreateFromHalfExtent(center, .5f * size);
                        BoundingBox2?   maskBox     = mask;
                        ContainmentType containment = ContainmentType.Contains;

                        if (maskBox != null)
                        {
                            maskBox.Value.Contains(ref bounds, out containment);

                            if (containment == ContainmentType.Contains)
                            {
                                maskBox = null;
                            }
                        }

                        if (containment != ContainmentType.Disjoint)
                        {
                            var bbL = new FlatTriangleBillboardData
                            {
                                Item1 = BlendTypeEnum.PostPP,
                                Item2 = new Vector2I(bbDataBack.Count, matrixID),
                                Item3 = mat.textureID,
                                Item4 = new MyTuple <Vector4, BoundingBox2?>(mat.bbColor, maskBox),
                                Item5 = new MyTuple <Vector2, Vector2, Vector2>
                                        (
                                    new Vector2(mat.texBounds.Max.X, mat.texBounds.Min.Y), // 1
                                    mat.texBounds.Max,                                     // 0
                                    new Vector2(mat.texBounds.Min.X, mat.texBounds.Max.Y)  // 3
                                        ),
                                Item6 = new MyTuple <Vector2, Vector2, Vector2>
                                        (
                                    bounds.Max,
                                    new Vector2(bounds.Max.X, bounds.Min.Y),
                                    bounds.Min
                                        ),
                            };
                            var bbR = new FlatTriangleBillboardData
                            {
                                Item1 = BlendTypeEnum.PostPP,
                                Item2 = new Vector2I(bbDataBack.Count + 1, matrixID),
                                Item3 = mat.textureID,
                                Item4 = new MyTuple <Vector4, BoundingBox2?>(mat.bbColor, maskBox),
                                Item5 = new MyTuple <Vector2, Vector2, Vector2>
                                        (
                                    new Vector2(mat.texBounds.Max.X, mat.texBounds.Min.Y), // 1
                                    new Vector2(mat.texBounds.Min.X, mat.texBounds.Max.Y), // 3
                                    mat.texBounds.Min                                      // 2
                                        ),
                                Item6 = new MyTuple <Vector2, Vector2, Vector2>
                                        (
                                    bounds.Max,
                                    bounds.Min,
                                    new Vector2(bounds.Min.X, bounds.Max.Y)
                                        ),
                            };

                            bbDataBack.Add(bbL);
                            bbDataBack.Add(bbR);
                        }
                    }

                    // Add more billboards to pool as needed then queue them for rendering
                    int bbToAdd = Math.Max(bbDataBack.Count - bbPool.Count, 0);

                    instance.AddNewBB(bbToAdd);

                    for (int i = bbCountStart; i < bbDataBack.Count; i++)
                    {
                        bbBuf.Add(bbPool[i]);
                    }

                    MyTransparentGeometry.AddBillboards(bbBuf, false);
                    bbBuf.Clear();
                }
Esempio n. 10
0
                /// <summary>
                /// Adds a list of textured quads in one batch using QuadBoard data
                /// </summary>
                public static void AddQuads(IReadOnlyList <QuadBoardData> quads, MatrixD[] matrixRef = null)
                {
                    var bbPool     = instance.bbPoolBack;
                    var bbDataBack = instance.triangleList;
                    var bbBuf      = instance.bbBuf;
                    var matList    = instance.matrixBuf;
                    var matTable   = instance.matrixTable;

                    // Find matrix index in table or add it
                    int matrixID = -1;

                    if (matrixRef != null && !matTable.TryGetValue(matrixRef, out matrixID))
                    {
                        matrixID = matList.Count;
                        matList.Add(matrixRef[0]);
                        matTable.Add(matrixRef, matrixID);
                    }

                    int triangleCount = quads.Count * 2,
                        bbRemaining   = bbPool.Count - bbDataBack.Count,
                        bbToAdd       = Math.Max(triangleCount - bbRemaining, 0);

                    instance.AddNewBB(bbToAdd);

                    for (int i = bbDataBack.Count; i < triangleCount + bbDataBack.Count; i++)
                    {
                        bbBuf.Add(bbPool[i]);
                    }

                    MyTransparentGeometry.AddBillboards(bbBuf, false);
                    bbBuf.Clear();

                    bbDataBack.EnsureCapacity(bbDataBack.Count + triangleCount);

                    for (int i = 0; i < quads.Count; i++)
                    {
                        QuadBoardData       quadBoard = quads[i];
                        MyQuadD             quad      = quadBoard.positions;
                        BoundedQuadMaterial mat       = quadBoard.material;

                        var bbL = new TriangleBillboardData
                        {
                            Item1 = BlendTypeEnum.PostPP,
                            Item2 = new Vector2I(bbDataBack.Count, matrixID),
                            Item3 = mat.textureID,
                            Item4 = mat.bbColor,
                            Item5 = new MyTuple <Vector2, Vector2, Vector2>
                                    (
                                mat.texBounds.Min,
                                mat.texBounds.Min + new Vector2(0f, mat.texBounds.Size.Y),
                                mat.texBounds.Max
                                    ),
                            Item6 = new MyTuple <Vector3D, Vector3D, Vector3D>
                                    (
                                quad.Point0,
                                quad.Point1,
                                quad.Point2
                                    ),
                        };
                        var bbR = new TriangleBillboardData
                        {
                            Item1 = BlendTypeEnum.PostPP,
                            Item2 = new Vector2I(bbDataBack.Count + 1, matrixID),
                            Item3 = mat.textureID,
                            Item4 = mat.bbColor,
                            Item5 = new MyTuple <Vector2, Vector2, Vector2>
                                    (
                                mat.texBounds.Min,
                                mat.texBounds.Max,
                                mat.texBounds.Min + new Vector2(mat.texBounds.Size.X, 0f)
                                    ),
                            Item6 = new MyTuple <Vector3D, Vector3D, Vector3D>
                                    (
                                quad.Point0,
                                quad.Point2,
                                quad.Point3
                                    ),
                        };

                        bbDataBack.Add(bbL);
                        bbDataBack.Add(bbR);
                    }
                }
Esempio n. 11
0
                /// <summary>
                /// Queues a quad billboard for rendering
                /// </summary>
                public static void AddQuad(ref BoundedQuadMaterial mat, ref MyQuadD quad, MatrixD[] matrixRef = null)
                {
                    var bbPool     = instance.bbPoolBack;
                    var bbDataBack = instance.triangleList;
                    int indexL     = bbDataBack.Count,
                        indexR     = bbDataBack.Count + 1;
                    var matList    = instance.matrixBuf;
                    var matTable   = instance.matrixTable;

                    // Find matrix index in table or add it
                    int matrixID = -1;

                    if (matrixRef != null && !matTable.TryGetValue(matrixRef, out matrixID))
                    {
                        matrixID = matList.Count;
                        matList.Add(matrixRef[0]);
                        matTable.Add(matrixRef, matrixID);
                    }

                    var bbL = new TriangleBillboardData
                    {
                        Item1 = BlendTypeEnum.PostPP,
                        Item2 = new Vector2I(indexL, matrixID),
                        Item3 = mat.textureID,
                        Item4 = mat.bbColor,
                        Item5 = new MyTuple <Vector2, Vector2, Vector2>
                                (
                            mat.texBounds.Min,
                            mat.texBounds.Min + new Vector2(0f, mat.texBounds.Size.Y),
                            mat.texBounds.Max
                                ),
                        Item6 = new MyTuple <Vector3D, Vector3D, Vector3D>
                                (
                            quad.Point0,
                            quad.Point1,
                            quad.Point2
                                ),
                    };
                    var bbR = new TriangleBillboardData
                    {
                        Item1 = BlendTypeEnum.PostPP,
                        Item2 = new Vector2I(indexR, matrixID),
                        Item3 = mat.textureID,
                        Item4 = mat.bbColor,
                        Item5 = new MyTuple <Vector2, Vector2, Vector2>
                                (
                            mat.texBounds.Min,
                            mat.texBounds.Max,
                            mat.texBounds.Min + new Vector2(mat.texBounds.Size.X, 0f)
                                ),
                        Item6 = new MyTuple <Vector3D, Vector3D, Vector3D>
                                (
                            quad.Point0,
                            quad.Point2,
                            quad.Point3
                                ),
                    };

                    bbDataBack.Add(bbL);
                    bbDataBack.Add(bbR);

                    if (indexR >= bbPool.Count)
                    {
                        instance.AddNewBB(indexR - (bbPool.Count - 1));
                    }

                    MyTransparentGeometry.AddBillboard(bbPool[indexL], false);
                    MyTransparentGeometry.AddBillboard(bbPool[indexR], false);
                }
Esempio n. 12
0
        public override void Draw()
        {
            try
            {
                int count = drawInfo.Count;
                if (count == 0)
                {
                    return;
                }

                var camMatrix = MyAPIGateway.Session.Camera.WorldMatrix;

                for (int i = count - 1; i >= 0; i--)
                {
                    var data     = drawInfo[i];
                    var ent      = data.Entity;
                    var settings = data.Settings;

                    if (ent.MarkedForClose)
                    {
                        drawInfo.RemoveAtFast(i);
                        continue;
                    }

                    var gunMatrix = ent.WorldMatrix;

                    var fwDot = gunMatrix.Forward.Dot(camMatrix.Forward);
                    if (fwDot <= 0)
                    {
                        continue; // looking more than 90deg away from the direction of the gun.
                    }
                    if (Vector3D.DistanceSquared(camMatrix.Translation, gunMatrix.Translation) > MAX_VIEW_DIST_SQ)
                    {
                        continue;                           // too far away to be seen
                    }
                    var dummyMatrix = settings.DummyMatrix; // scaled exactly like the dummy from the model

                    var reticleProjectedPosition = Vector3D.Transform(dummyMatrix.Translation, gunMatrix) + gunMatrix.Forward * PROJECTED_DISTANCE;

                    //if(IsLocalPlayerAimingThisGun(data.Entity))
                    //{
                    //    var centerScreenPos = camMatrix.Translation + camMatrix.Forward * Vector3D.Distance(camMatrix.Translation, reticlePosition);
                    //    MyTransparentGeometry.AddBillboardOriented(data.Settings.ReticleMaterial, data.Settings.ReticleColor, centerScreenPos, gunMatrix.Left, gunMatrix.Up, data.Settings.ReticleSize, blendType: RETICLE_BLEND_TYPE);
                    //    continue;
                    //}

                    var sightPosition = Vector3D.Transform(dummyMatrix.Translation, gunMatrix);

                    var fwOffsetDot = gunMatrix.Forward.Dot(sightPosition - camMatrix.Translation);
                    if (fwOffsetDot < 0)
                    {
                        continue; // camera is ahead of sight, don't draw reticle
                    }
                    if (settings.Type == SightType.Rectangle)
                    {
                        var    camToReticleDir = Vector3D.Normalize(reticleProjectedPosition - camMatrix.Translation);
                        double angleH          = Math.Acos(MathHelper.Clamp(Vector3D.Dot(gunMatrix.Left, camToReticleDir), -1, 1)) - (Math.PI / 2); // subtracting 90deg
                        double angleV          = Math.Acos(MathHelper.Clamp(Vector3D.Dot(gunMatrix.Up, camToReticleDir), -1, 1)) - (Math.PI / 2);

                        // simplifies math later on
                        angleH = Math.Abs(angleH);
                        angleV = Math.Abs(angleV);

                        if (angleH < settings.MaxAngleH && angleV < settings.MaxAngleV)
                        {
                            var alphaH = GetAlphaForAngle(settings.FadeStartRatio, angleH, settings.MaxAngleH);
                            var alphaV = GetAlphaForAngle(settings.FadeStartRatio, angleV, settings.MaxAngleV);

                            var camToSightDistance = Vector3D.Distance(sightPosition, camMatrix.Translation) + RETICLE_FRONT_OFFSET;
                            var reticlePosition    = camMatrix.Translation + (camToReticleDir * camToSightDistance);

                            MyTransparentGeometry.AddBillboardOriented(settings.ReticleMaterial, settings.ReticleColor * (alphaH * alphaV), reticlePosition, gunMatrix.Left, gunMatrix.Up, settings.ReticleSize, blendType: RETICLE_BLEND_TYPE);
                        }
                    }
                    else if (settings.Type == SightType.Circle)
                    {
                        var    camToReticleDir = Vector3D.Normalize(reticleProjectedPosition - camMatrix.Translation);
                        double angle           = Math.Acos(MathHelper.Clamp(Vector3D.Dot(gunMatrix.Forward, camToReticleDir), -1, 1));

                        if (angle < settings.MaxAngleH)
                        {
                            var alpha = GetAlphaForAngle(settings.FadeStartRatio, angle, settings.MaxAngleH);

                            var camToSightDistance = Vector3D.Distance(sightPosition, camMatrix.Translation) + RETICLE_FRONT_OFFSET;
                            var reticlePosition    = camMatrix.Translation + (camToReticleDir * camToSightDistance);

                            MyTransparentGeometry.AddBillboardOriented(settings.ReticleMaterial, settings.ReticleColor * alpha, reticlePosition, gunMatrix.Left, gunMatrix.Up, settings.ReticleSize, blendType: RETICLE_BLEND_TYPE);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }
        public override void Draw()
        {
            base.Draw();
            if (MyTrashRemoval.PreviewEnabled && MySession.Static.HasAdminRights)
            {
                DrawTrashAdminView();
            }

            bool visible = false;

            for (int i = 0; i < RenderObjectIDs.Length; i++)
            {
                if (RenderObjectIDs[i] == MyRenderProxy.RENDER_ID_UNASSIGNED)
                {
                    break;
                }
                if (MyRenderProxy.VisibleObjectsRead.Contains(this.RenderObjectIDs[i]))
                {
                    visible = true;
                    break;
                }
            }
            if (visible)
            {
                foreach (var block in m_grid.BlocksForDraw)
                {
                    if (MyRenderProxy.VisibleObjectsRead.Contains(block.Render.RenderObjectIDs[0]))
                    {
                        block.Render.Draw();
                    }
                }
            }
            if (MyCubeGrid.ShowCenterOfMass && !IsStatic && Container.Entity.Physics != null && Container.Entity.Physics.HasRigidBody)
            {
                var  matrix = Container.Entity.Physics.GetWorldMatrix();
                var  center = Container.Entity.Physics.CenterOfMassWorld;
                var  cam    = MySector.MainCamera.Position;
                var  dist   = Vector3.Distance(cam, center);
                bool draw   = false;
                if (dist < 30)
                {
                    draw = true;
                }
                else if (dist < 200)
                {
                    draw = true;
                    MyPhysics.CastRay(cam, center, m_tmpHitList, MyPhysics.CollisionLayers.DynamicDoubledCollisionLayer);
                    foreach (var hit in m_tmpHitList)
                    {
                        if (hit.HkHitInfo.GetHitEntity() != this)
                        {
                            draw = false;
                            break;
                        }
                    }
                    m_tmpHitList.Clear();
                }
                if (draw)
                {
                    float size      = MathHelper.Lerp(1, 9, dist / 200);
                    var   mat       = "WeaponLaserIgnoreDepth";
                    var   color     = Color.Yellow.ToVector4();
                    var   thickness = 0.02f * size;
                    MySimpleObjectDraw.DrawLine(center - matrix.Up * 0.5f * size, center + matrix.Up * 0.5f * size, mat, ref color, thickness);
                    MySimpleObjectDraw.DrawLine(center - matrix.Forward * 0.5f * size, center + matrix.Forward * 0.5f * size, mat, ref color, thickness);
                    MySimpleObjectDraw.DrawLine(center - matrix.Right * 0.5f * size, center + matrix.Right * 0.5f * size, mat, ref color, thickness);
                    MyTransparentGeometry.AddBillboardOriented("RedDotIgnoreDepth", Color.White.ToVector4(), center, MySector.MainCamera.LeftVector, MySector.MainCamera.UpVector, 0.1f * size, priority: 1);
                }
            }
            if (MyCubeGrid.ShowGridPivot)
            {
                var  matrix = Container.Entity.WorldMatrix;
                var  pos    = matrix.Translation;
                var  cam    = MySector.MainCamera.Position;
                var  dist   = Vector3.Distance(cam, pos);
                bool draw   = false;
                if (dist < 30)
                {
                    draw = true;
                }
                else if (dist < 200)
                {
                    draw = true;
                    MyPhysics.CastRay(cam, pos, m_tmpHitList, MyPhysics.CollisionLayers.DynamicDoubledCollisionLayer);
                    foreach (var hit in m_tmpHitList)
                    {
                        if (hit.HkHitInfo.GetHitEntity() != this)
                        {
                            draw = false;
                            break;
                        }
                    }
                    m_tmpHitList.Clear();
                }
                if (draw)
                {
                    float size      = MathHelper.Lerp(1, 9, dist / 200);
                    var   mat       = "WeaponLaserIgnoreDepth";
                    var   thickness = 0.02f * size;
                    var   color     = Color.Green.ToVector4();
                    MySimpleObjectDraw.DrawLine(pos, pos + matrix.Up * 0.5f * size, mat, ref color, thickness);
                    color = Color.Blue.ToVector4();
                    MySimpleObjectDraw.DrawLine(pos, pos + matrix.Forward * 0.5f * size, mat, ref color, thickness);
                    color = Color.Red.ToVector4();
                    MySimpleObjectDraw.DrawLine(pos, pos + matrix.Right * 0.5f * size, mat, ref color, thickness);
                    MyTransparentGeometry.AddBillboardOriented("RedDotIgnoreDepth", Color.White.ToVector4(), pos, MySector.MainCamera.LeftVector, MySector.MainCamera.UpVector, 0.1f * size, priority: 1);
                    MyRenderProxy.DebugDrawAxis(matrix, 0.5f, false);//DX 11 desnt support depthRead false
                }
            }

            if (MyCubeGrid.ShowStructuralIntegrity)
            {
                if (m_grid.StructuralIntegrity == null)
                {
                    if (MyFakes.ENABLE_STRUCTURAL_INTEGRITY)
                    {
                        m_grid.CreateStructuralIntegrity();

                        if (m_grid.StructuralIntegrity != null)
                        {
                            m_grid.StructuralIntegrity.EnabledOnlyForDraw = true;
                        }
                    }
                }
                else
                {
                    m_grid.StructuralIntegrity.Draw();
                }
            }
            else
            if (m_grid.StructuralIntegrity != null && m_grid.StructuralIntegrity.EnabledOnlyForDraw)
            {
                m_grid.CloseStructuralIntegrity();
            }

            if (MyFakes.ENABLE_ATMOSPHERIC_ENTRYEFFECT)
            {
                ProfilerShort.Begin("DrawAtmosphericEntryEffect");
                DrawAtmosphericEntryEffect();
                ProfilerShort.End();
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Method is called defacto from Update, but only the last one in sequence, where
        /// creating render messages makes sense
        /// </summary>
        public override void Draw()
        {
            if (!MyRenderProxy.DebugOverrides.BillboardsStatic)
            {
                return;
            }

            ProfilerShort.Begin("MyRenderComponent::Draw");

            var objToCameraSq = Vector3.DistanceSquared(MySector.MainCamera.Position, Container.Entity.PositionComp.GetPosition());

            //Disable glass for holograms (transparency < 0)
            if (Transparency >= 0f && m_model != null && m_model.GlassData != null && objToCameraSq < Container.Entity.MaxGlassDistSq)
            {
                string mat;
                var    world = (Matrix)Container.Entity.PositionComp.WorldMatrix;

                Vector3 worldP0;
                Vector3 worldP1;
                Vector3 worldP2;

                Vector3 n0;
                Vector3 n1;
                Vector3 n2;

                for (int i = 0; i < m_model.GlassData.TriCount; i++)
                {
                    var     tri = m_model.GetTriangle(m_model.GlassData.TriStart + i);
                    Vector3 p0  = m_model.GetVertex(tri.I0);
                    Vector3 p1  = m_model.GetVertex(tri.I1);
                    Vector3 p2  = m_model.GetVertex(tri.I2);

                    Vector3.Transform(ref p0, ref world, out worldP0);
                    Vector3.Transform(ref p1, ref world, out worldP1);
                    Vector3.Transform(ref p2, ref world, out worldP2);

                    var uv0 = m_model.GlassTexCoords[i * 3 + 0];
                    var uv1 = m_model.GlassTexCoords[i * 3 + 2];
                    var uv2 = m_model.GlassTexCoords[i * 3 + 1];

                    var normal = Vector3.Cross(worldP0 - worldP1, worldP0 - worldP2);

                    float dot = Vector3.Dot(normal, worldP0 - MySector.MainCamera.Position);
                    if (dot > 0)
                    {
                        mat = string.IsNullOrEmpty(m_model.GlassData.Material.GlassCW) ? "GlassCW" : m_model.GlassData.Material.GlassCW;
                    }
                    else
                    {
                        mat = string.IsNullOrEmpty(m_model.GlassData.Material.GlassCCW) ? "GlassCCW" : m_model.GlassData.Material.GlassCCW;
                    }

                    // this does not make sense, as the shader takes only the one normal from the first point; better to use calculated triangle normal

                    /*bool smooth = m_model.GlassData.Material.GlassSmooth;
                     *
                     * if (smooth)
                     * {
                     *  n0 = m_model.GetVertexNormal(tri.I0);
                     *  n1 = m_model.GetVertexNormal(tri.I1);
                     *  n2 = m_model.GetVertexNormal(tri.I2);
                     * }
                     * else
                     * {*/
                    n0 = n1 = n2 = normal;
                    //}
                    if (dot > 0)
                    {
                        n0 = -n0;
                        n1 = -n1;
                        n2 = -n2;
                    }

                    var renderID = m_renderObjectIDs[0];

                    Vector3 center; // Old way: (p0 + p1 + p2) / 3
                    //Vector3 center = (p0 + p1 + p2) / 3;

                    float worldP0P1 = (worldP1 - worldP0).LengthSquared();
                    float worldP1P2 = (worldP2 - worldP1).LengthSquared();
                    float worldP2P0 = (worldP0 - worldP2).LengthSquared();

                    if (worldP0P1 > worldP1P2 && worldP0P1 > worldP2P0)
                    {
                        center = (worldP0 + worldP1) * 0.5f;
                    }
                    else if (worldP1P2 > worldP2P0 && worldP1P2 > worldP0P1)
                    {
                        center = (worldP1 + worldP2) * 0.5f;
                    }
                    else
                    {
                        center = (worldP2 + worldP0) * 0.5f;
                    }

                    MyTransparentGeometry.AddTriangleBillboard(
                        p0, p1, p2,
                        n0, n1, n2,
                        uv0.ToVector2(), uv1.ToVector2(), uv2.ToVector2(),
                        mat, (int)renderID, center);
                }
            }

            ProfilerShort.End();
        }
Esempio n. 15
0
        private void DrawJetpackThrusts(bool updateCalled)
        {
            MyCharacter skinnedEntity = base.m_skinnedEntity as MyCharacter;

            if ((skinnedEntity != null) && (skinnedEntity.GetCurrentMovementState() != MyCharacterMovementEnum.Died))
            {
                MyCharacterJetpackComponent jetpackComp = skinnedEntity.JetpackComp;
                if ((jetpackComp != null) && jetpackComp.CanDrawThrusts)
                {
                    MyEntityThrustComponent component2 = base.Container.Get <MyEntityThrustComponent>();
                    if (component2 != null)
                    {
                        MatrixD worldToLocal = MatrixD.Invert(base.Container.Entity.PositionComp.WorldMatrix);
                        foreach (MyJetpackThrust thrust in this.m_jetpackThrusts)
                        {
                            Vector3D zero = Vector3D.Zero;
                            if ((!jetpackComp.TurnedOn || !jetpackComp.IsPowered) || ((skinnedEntity.IsInFirstPersonView && ReferenceEquals(skinnedEntity, MySession.Static.LocalCharacter)) && !MyAnsel.IsAnselSessionRunning))
                            {
                                if (updateCalled || (skinnedEntity.IsUsing != null))
                                {
                                    thrust.ThrustRadius = 0f;
                                }
                            }
                            else
                            {
                                MatrixD  matrix   = thrust.ThrustMatrix * base.Container.Entity.PositionComp.WorldMatrix;
                                Vector3D vectord2 = Vector3D.TransformNormal(thrust.Forward, matrix);
                                zero = matrix.Translation + (vectord2 * thrust.Offset);
                                float num = 0.05f;
                                if (updateCalled)
                                {
                                    thrust.ThrustRadius = MyUtils.GetRandomFloat(0.9f, 1.1f) * num;
                                }
                                float   num2    = MathHelper.Clamp((float)(Vector3.Dot((Vector3)vectord2, (Vector3)(-Vector3.Transform(component2.FinalThrust, base.Entity.WorldMatrix.GetOrientation()) / ((double)skinnedEntity.BaseMass))) * 0.09f), (float)0.1f, (float)1f);
                                Vector4 color   = Vector4.Zero;
                                Vector4 vector2 = Vector4.Zero;
                                if ((num2 > 0f) && (thrust.ThrustRadius > 0f))
                                {
                                    float num4 = (1f - ((float)Math.Pow((double)(1f - (1f - Math.Abs(Vector3.Dot((Vector3)MyUtils.Normalize(MySector.MainCamera.Position - zero), (Vector3)vectord2)))), 30.0))) * 0.5f;
                                    if (updateCalled)
                                    {
                                        thrust.ThrustLength    = ((num2 * 12f) * MyUtils.GetRandomFloat(1.6f, 2f)) * num;
                                        thrust.ThrustThickness = MyUtils.GetRandomFloat(thrust.ThrustRadius * 1.9f, thrust.ThrustRadius);
                                    }
                                    color = thrust.Light.Color.ToVector4() * new Vector4(1f, 1f, 1f, 0.4f);
                                    MyTransparentGeometry.AddLineBillboard(thrust.ThrustLengthMaterial, color, zero + (vectord2 * JETPACK_THRUST_OFFSET), base.GetRenderObjectID(), ref worldToLocal, (Vector3)vectord2, thrust.ThrustLength * JETPACK_THRUST_LENGTH, thrust.ThrustThickness * JETPACK_THRUST_THICKNESS, MyBillboard.BlendTypeEnum.Standard, -1, num4 * (JETPACK_THRUST_INTENSITY_BASE + (num2 * JETPACK_THRUST_INTENSITY)), null);
                                }
                                if (thrust.ThrustRadius > 0f)
                                {
                                    vector2 = thrust.Light.Color.ToVector4() * new Vector4(1f, 1f, 1f, 0.4f);
                                    MyTransparentGeometry.AddPointBillboard(thrust.ThrustPointMaterial, vector2, zero, base.GetRenderObjectID(), ref worldToLocal, thrust.ThrustRadius * JETPACK_THRUST_THICKNESS, 0f, -1, MyBillboard.BlendTypeEnum.Standard, JETPACK_THRUST_INTENSITY_BASE + (num2 * JETPACK_THRUST_INTENSITY), null);
                                }
                            }
                            if (thrust.Light != null)
                            {
                                if (thrust.ThrustRadius <= 0f)
                                {
                                    thrust.Light.GlareOn = false;
                                    thrust.Light.LightOn = false;
                                    thrust.Light.UpdateLight();
                                }
                                else
                                {
                                    thrust.Light.LightOn        = true;
                                    thrust.Light.Intensity      = JETPACK_LIGHT_INTENSITY_BASE + (thrust.ThrustLength * JETPACK_LIGHT_INTENSITY_LENGTH);
                                    thrust.Light.Range          = (thrust.ThrustRadius * JETPACK_LIGHT_RANGE_RADIUS) + (thrust.ThrustLength * JETPACK_LIGHT_RANGE_LENGTH);
                                    thrust.Light.Position       = Vector3D.Transform(zero, base.Container.Entity.PositionComp.WorldMatrixNormalizedInv);
                                    thrust.Light.ParentID       = this.m_cullRenderId;
                                    thrust.Light.GlareOn        = true;
                                    thrust.Light.GlareIntensity = (JETPACK_GLARE_INTENSITY_BASE + (thrust.ThrustLength * JETPACK_GLARE_INTENSITY_LENGTH)) * this.m_flareJetpack.Intensity;
                                    thrust.Light.GlareType      = MyGlareTypeEnum.Normal;
                                    thrust.Light.GlareSize      = (this.m_flareJetpack.Size * ((thrust.ThrustRadius * JETPACK_GLARE_SIZE_RADIUS) + (thrust.ThrustLength * JETPACK_GLARE_SIZE_LENGTH))) * thrust.ThrustGlareSize;
                                    thrust.Light.SubGlares      = this.m_flareJetpack.SubGlares;
                                    thrust.Light.GlareQuerySize = 0.1f;
                                    thrust.Light.UpdateLight();
                                }
                            }
                        }
                    }
                }
            }
        }
Esempio n. 16
0
                /// <summary>
                /// Queues a quad billboard for rendering
                /// </summary>
                public static void AddQuad(ref FlatQuad quad, ref BoundedQuadMaterial mat, MatrixD[] matrixRef, BoundingBox2?mask = null)
                {
                    var bbPool     = instance.bbPoolBack;
                    var bbDataBack = instance.flatTriangleList;
                    var matList    = instance.matrixBuf;
                    var matTable   = instance.matrixTable;

                    // Find matrix index in table or add it
                    int matrixID;

                    if (!matTable.TryGetValue(matrixRef, out matrixID))
                    {
                        matrixID = matList.Count;
                        matList.Add(matrixRef[0]);
                        matTable.Add(matrixRef, matrixID);
                    }

                    // Mask bounding check. Null mask if not intersecting.
                    BoundingBox2?   maskBox     = mask;
                    ContainmentType containment = ContainmentType.Contains;

                    if (maskBox != null)
                    {
                        BoundingBox2 bounds = new BoundingBox2(quad.Point2, quad.Point0);
                        maskBox.Value.Contains(ref bounds, out containment);

                        if (containment == ContainmentType.Contains)
                        {
                            maskBox = null;
                        }
                    }

                    if (containment != ContainmentType.Disjoint)
                    {
                        int indexL = bbDataBack.Count,
                            indexR = bbDataBack.Count + 1;

                        var bbL = new FlatTriangleBillboardData
                        {
                            Item1 = BlendTypeEnum.PostPP,
                            Item2 = new Vector2I(bbDataBack.Count, matrixID),
                            Item3 = mat.textureID,
                            Item4 = new MyTuple <Vector4, BoundingBox2?>(mat.bbColor, maskBox),
                            Item5 = new MyTuple <Vector2, Vector2, Vector2>
                                    (
                                new Vector2(mat.texBounds.Max.X, mat.texBounds.Min.Y), // 1
                                mat.texBounds.Max,                                     // 0
                                new Vector2(mat.texBounds.Min.X, mat.texBounds.Max.Y)  // 3
                                    ),
                            Item6 = new MyTuple <Vector2, Vector2, Vector2>
                                    (
                                quad.Point0,
                                quad.Point1,
                                quad.Point2
                                    ),
                        };
                        var bbR = new FlatTriangleBillboardData
                        {
                            Item1 = BlendTypeEnum.PostPP,
                            Item2 = new Vector2I(bbDataBack.Count + 1, matrixID),
                            Item3 = mat.textureID,
                            Item4 = new MyTuple <Vector4, BoundingBox2?>(mat.bbColor, maskBox),
                            Item5 = new MyTuple <Vector2, Vector2, Vector2>
                                    (
                                new Vector2(mat.texBounds.Max.X, mat.texBounds.Min.Y), // 1
                                new Vector2(mat.texBounds.Min.X, mat.texBounds.Max.Y), // 3
                                mat.texBounds.Min                                      // 2
                                    ),
                            Item6 = new MyTuple <Vector2, Vector2, Vector2>
                                    (
                                quad.Point0,
                                quad.Point2,
                                quad.Point3
                                    ),
                        };

                        bbDataBack.Add(bbL);
                        bbDataBack.Add(bbR);

                        if (indexR >= bbPool.Count)
                        {
                            instance.AddNewBB(indexR - (bbPool.Count - 1));
                        }

                        MyTransparentGeometry.AddBillboard(bbPool[indexL], false);
                        MyTransparentGeometry.AddBillboard(bbPool[indexR], false);
                    }
                }
Esempio n. 17
0
        public override void Draw()
        {
            base.Draw();

            UpdateCharacterSkeleton();

            VRageRender.MyRenderProxy.SetCharacterTransforms(RenderObjectIDs[0], m_character.BoneRelativeTransforms);

            Matrix headMatrix = m_character.GetHeadMatrix(false);


            Vector3 position      = m_light.Position;
            Vector3 forwardVector = m_light.ReflectorDirection;
            Vector3 leftVector    = headMatrix.Left;
            Vector3 upVector      = headMatrix.Up;

            float reflectorLength    = MyCharacter.REFLECTOR_BILLBOARD_LENGTH * 0.4f * 0.16f;
            float reflectorThickness = MyCharacter.REFLECTOR_BILLBOARD_THICKNESS * 0.08f;
            //float reflectorRadiusForAdditive = 0.25f;//0.65f;

            Vector3 color = new Vector3(m_light.ReflectorColor);

            Vector3 glarePosition          = position + forwardVector * 0.28f;
            var     dot                    = Vector3.Dot(Vector3.Normalize(MySector.MainCamera.Position - glarePosition), forwardVector);
            float   angle                  = 1 - Math.Abs(dot);
            float   alphaGlareAlphaBlended = (float)Math.Pow(1 - angle, 2);
            float   alphaGlareAdditive     = (float)Math.Pow(1 - angle, 2);
            float   alphaCone              = (1 - (float)Math.Pow(1 - angle, 30)) * 0.5f;

            float reflectorRadiusForAlphaBlended = MathHelper.Lerp(0.1f, 0.5f, alphaGlareAlphaBlended); //3.5f;

            //  Multiply alpha by reflector level (and not the color), because if we multiply the color and let alpha unchanged, reflector cune will be drawn as very dark cone, but still visible
            var reflectorLevel = m_character.CurrentLightPower;

            m_light.ReflectorIntensity = reflectorLevel;

            alphaCone *= reflectorLevel * 0.2f;
            alphaGlareAlphaBlended *= reflectorLevel * 0.1f;
            alphaGlareAdditive     *= reflectorLevel * 0.8f;

            float distance = Vector3.Distance(m_character.PositionComp.GetPosition(), MySector.MainCamera.Position);

            if (!m_character.IsInFirstPersonView && distance < MyCharacter.LIGHT_GLARE_MAX_DISTANCE && reflectorLevel > 0)
            {
                float alpha = MathHelper.Clamp((MyCharacter.LIGHT_GLARE_MAX_DISTANCE - 10.0f) / distance, 0, 1);

                if (reflectorLength > 0 && reflectorThickness > 0)
                {
                    if (m_leftGlare != null)
                    {
                        MyTransparentGeometry.AddLineBillboard("ReflectorConeCharacter", new Vector4(color, 1.0f) * alphaCone * alpha,
                                                               m_leftGlare.Position,
                                                               m_leftGlare.ReflectorDirection, reflectorLength, reflectorThickness);
                    }

                    if (m_rightGlare != null)
                    {
                        MyTransparentGeometry.AddLineBillboard("ReflectorConeCharacter", new Vector4(color, 1.0f) * alphaCone * alpha,
                                                               m_rightGlare.Position,
                                                               m_rightGlare.ReflectorDirection, reflectorLength, reflectorThickness);
                    }
                }

                if (m_leftGlare != null)
                {
                    MyTransparentGeometry.AddPointBillboard("ReflectorGlareAlphaBlended", new Vector4(color, 1.0f) * alphaGlareAlphaBlended * alpha,
                                                            m_leftGlare.Position, reflectorRadiusForAlphaBlended * 0.3f, 0);
                }

                if (m_rightGlare != null)
                {
                    MyTransparentGeometry.AddPointBillboard("ReflectorGlareAlphaBlended", new Vector4(color, 1.0f) * alphaGlareAlphaBlended * alpha,
                                                            m_rightGlare.Position, reflectorRadiusForAlphaBlended * 0.3f, 0);
                }
            }

            DrawJetpackThrusts(m_character.UpdateCalled());

            if (m_character.Hierarchy.Parent != null)
            {
                if (m_leftGlare != null && m_leftGlare.LightOn == true)
                {
                    m_leftGlare.LightOn = false;
                    m_leftGlare.GlareOn = false;
                    m_leftGlare.UpdateLight();
                }

                if (m_rightGlare != null && m_rightGlare.LightOn == true)
                {
                    m_rightGlare.LightOn = false;
                    m_rightGlare.GlareOn = false;
                    m_rightGlare.UpdateLight();
                }
            }
            else
            {
                if (m_leftGlare != null && m_leftGlare.LightOn == false)
                {
                    m_leftGlare.LightOn = true;
                    m_leftGlare.GlareOn = true;
                    m_leftGlare.UpdateLight();
                }

                if (m_rightGlare != null && m_rightGlare.LightOn == true)
                {
                    m_rightGlare.LightOn = true;
                    m_rightGlare.GlareOn = true;
                    m_rightGlare.UpdateLight();
                }
            }

            if (MySession.ControlledEntity == m_character)
            {
                if (m_character.IsDead && m_character.CurrentRespawnCounter > 0)
                {
                    DrawBlood(1);
                }

                if (!m_character.IsDead && m_currentHitIndicatorCounter > 0)
                {
                    m_currentHitIndicatorCounter -= MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS;

                    if (m_currentHitIndicatorCounter < 0)
                    {
                        m_currentHitIndicatorCounter = 0;
                    }

                    float alpha = m_currentHitIndicatorCounter / HIT_INDICATOR_LENGTH;

                    DrawBlood(alpha);
                }

                if (m_character.StatComp != null)
                {
                    var healthRatio = m_character.StatComp.HealthRatio;
                    if (healthRatio <= MyCharacterStatComponent.LOW_HEALTH_RATIO && !m_character.IsDead)
                    {
                        float alpha = MathHelper.Clamp(MyCharacterStatComponent.LOW_HEALTH_RATIO - healthRatio, 0, 1) / MyCharacterStatComponent.LOW_HEALTH_RATIO + 0.3f;
                        DrawBlood(alpha);
                    }
                }
            }

            //DebugDraw();
        }
Esempio n. 18
0
        void DrawSkinSelector(MatrixD camMatrix, Vector3D worldPos, float scaleFOV, float bgAlpha)
        {
            PlayerInfo      localInfo  = Main.Palette.LocalInfo;
            List <SkinInfo> shownSkins = Main.Palette.SkinsForHUD;

            if (localInfo == null || shownSkins == null || !localInfo.ApplySkin || !Main.Palette.HasAnySkin)
            {
                return;
            }

            float        iconSize               = 0.0024f * scaleFOV;
            float        selectedIconSize       = 0.003f * scaleFOV;
            MyStringHash selectedSkinId         = localInfo.SelectedSkin;
            double       iconSpacingAdd         = (selectedIconSize - iconSize); // 0.0012 * scaleFOV;
            double       iconSpacingWidth       = (iconSize * 2) + iconSpacingAdd;
            float        iconBgSpacingAddWidth  = 0.0004f * scaleFOV;
            float        iconBgSpacingAddHeight = 0.0006f * scaleFOV;
            //float iconBgSpacingAddWidth = 0.0006f * scaleFOV;
            //float iconBgSpacingAddHeight = 0.0008f * scaleFOV;

            Vector3D pos = worldPos;

            if (localInfo.ApplyColor)
            {
                pos += camMatrix.Up * (0.0075f * scaleFOV);
            }

            DrawSkinNameText(localInfo.SelectedSkinInfo);

            const int    MAX_VIEW_SKINS        = 7; // must be an odd number.
            const int    MAX_VIEW_SKINS_HALF   = ((MAX_VIEW_SKINS - 1) / 2);
            const double MAX_VIEW_SKINS_HALF_D = (MAX_VIEW_SKINS / 2d);
            //const double MAX_VIEW_SKINS_HALF_D_BG = ((MAX_VIEW_SKINS - 4) / 2d);

            int showSkinsCount = shownSkins.Count;

            if (showSkinsCount >= MAX_VIEW_SKINS) // scrolling skin bar
            {
                //var bgPos = pos + camMatrix.Right * ((iconSpacingWidth * 0.5) - (iconSpacingWidth * 0.5));
                //MyTransparentGeometry.AddBillboardOriented(MATERIAL_PALETTE_BACKGROUND, PALETTE_COLOR_BG * bgAlpha, bgPos, camMatrix.Left, camMatrix.Up, (float)(iconSpacingWidth * MAX_VIEW_SKINS_HALF_D_BG) + iconBgSpacingAddWidth, iconSize + iconBgSpacingAddHeight, Vector2.Zero, UI_BG_BLENDTYPE);

                pos += camMatrix.Left * ((iconSpacingWidth * MAX_VIEW_SKINS_HALF_D) - (iconSpacingWidth * 0.5));

                int skinIndex = 0;

                for (int i = 0; i < showSkinsCount; ++i)
                {
                    SkinInfo skin = shownSkins[i];
                    if (skin.SubtypeId == selectedSkinId)
                    {
                        skinIndex = i;
                        break;
                    }
                }

                const float MIN_ALPHA         = 0.5f; // alpha of the skin icon on the edge of the scrollable bar
                float       alphaSubtractStep = ((1f - MIN_ALPHA) / MAX_VIEW_SKINS_HALF);

                int index = skinIndex - MAX_VIEW_SKINS_HALF;

                for (int a = -MAX_VIEW_SKINS_HALF; a <= MAX_VIEW_SKINS_HALF; ++a)
                {
                    if (index < 0)
                    {
                        index = showSkinsCount + index;
                    }
                    if (index >= showSkinsCount)
                    {
                        index %= showSkinsCount;
                    }

                    SkinInfo skin = shownSkins[index];

                    float alpha = 1f - (Math.Abs(a) * alphaSubtractStep);

                    if (selectedSkinId == skin.SubtypeId)
                    {
                        MyTransparentGeometry.AddBillboardOriented(MATERIAL_PALETTE_COLOR, Color.White, pos, camMatrix.Left, camMatrix.Up, selectedIconSize, selectedIconSize, Vector2.Zero, GUI_FG_BLENDTYPE);
                    }

                    MyTransparentGeometry.AddBillboardOriented(skin.Icon, Color.White * alpha, pos, camMatrix.Left, camMatrix.Up, iconSize, iconSize, Vector2.Zero, GUI_FG_BLENDTYPE);

                    pos += camMatrix.Right * iconSpacingWidth;

                    index++;
                }
            }
            else // static skin bar with moving selection
            {
                double halfOwnedSkins = showSkinsCount * 0.5;

                //MyTransparentGeometry.AddBillboardOriented(MATERIAL_PALETTE_BACKGROUND, PALETTE_COLOR_BG * bgAlpha, pos, camMatrix.Left, camMatrix.Up, (float)(iconSpacingWidth * halfOwnedSkins) + iconBgSpacingAddWidth, iconSize + iconBgSpacingAddHeight, Vector2.Zero, UI_BG_BLENDTYPE);

                pos += camMatrix.Left * ((iconSpacingWidth * halfOwnedSkins) - (iconSpacingWidth * 0.5));

                foreach (SkinInfo skin in shownSkins)
                {
                    if (selectedSkinId == skin.SubtypeId)
                    {
                        MyTransparentGeometry.AddBillboardOriented(MATERIAL_PALETTE_COLOR, Color.White, pos, camMatrix.Left, camMatrix.Up, selectedIconSize, selectedIconSize, Vector2.Zero, GUI_FG_BLENDTYPE);
                    }

                    MyTransparentGeometry.AddBillboardOriented(skin.Icon, Color.White, pos, camMatrix.Left, camMatrix.Up, iconSize, iconSize, Vector2.Zero, GUI_FG_BLENDTYPE);

                    pos += camMatrix.Right * iconSpacingWidth;
                }
            }
        }
        private void UpdateParticlesLife()
        {
            int counter = 0;

            VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("ParticleGeneration-UpdateParticlesLife");

            MyParticleGeneration inheritedGeneration      = null;
            Vector3D             previousParticlePosition = m_effect.WorldMatrix.Translation;
            float particlesToCreate = 0;

            m_AABB = BoundingBoxD.CreateInvalid();
            m_AABB = m_AABB.Include(ref previousParticlePosition);

            if (OnDie.GetValue <int>() != -1)
            {
                inheritedGeneration = GetInheritedGeneration(OnDie.GetValue <int>());

                if (inheritedGeneration == null)
                {
                    OnDie.SetValue(-1);
                }
                else
                {
                    inheritedGeneration.IsInherited = true;
                    particlesToCreate = inheritedGeneration.m_particlesToCreate;
                }
            }

            VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();

            VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("ParticleGeneration-Update01");

            Vector3D previousTrail0 = previousParticlePosition;
            Vector3D previousTrail1 = previousParticlePosition;

            using (ParticlesLock.AcquireExclusiveUsing())
            {
                while (counter < m_particles.Count)
                {
                    float motionInheritance;
                    MotionInheritance.GetInterpolatedValue(m_effect.GetElapsedTime(), out motionInheritance);

                    MyAnimatedParticle particle = m_particles[counter];

                    if (motionInheritance > 0)
                    {
                        m_effect.CalculateDeltaMatrix = true;
                    }

                    if (particle.Update())
                    {
                        if (motionInheritance > 0)
                        {
                            var delta = m_effect.GetDeltaMatrix();
                            particle.AddMotionInheritance(ref motionInheritance, ref delta);
                        }

                        if (counter == 0)
                        {
                            previousParticlePosition = particle.ActualPosition;
                            previousTrail0           = particle.Quad.Point1;
                            previousTrail1           = particle.Quad.Point2;
                            particle.Quad.Point0     = particle.ActualPosition;
                            particle.Quad.Point2     = particle.ActualPosition;
                        }

                        counter++;


                        if (particle.Type == MyParticleTypeEnum.Trail)
                        {
                            if (particle.ActualPosition == previousParticlePosition)
                            {
                                particle.Quad.Point0 = particle.ActualPosition;
                                particle.Quad.Point1 = particle.ActualPosition;
                                particle.Quad.Point2 = particle.ActualPosition;
                                particle.Quad.Point3 = particle.ActualPosition;
                            }
                            else
                            {
                                MyPolyLineD polyLine = new MyPolyLineD();
                                polyLine.Thickness = particle.Thickness;
                                polyLine.Point0    = particle.ActualPosition;
                                polyLine.Point1    = previousParticlePosition;

                                Vector3D direction           = polyLine.Point1 - polyLine.Point0;
                                Vector3D normalizedDirection = MyUtils.Normalize(polyLine.Point1 - polyLine.Point0);

                                polyLine.LineDirectionNormalized = normalizedDirection;
                                var camPos = MyTransparentGeometry.Camera.Translation;
                                MyUtils.GetPolyLineQuad(out particle.Quad, ref polyLine, camPos);

                                particle.Quad.Point0 = previousTrail0 + direction * 0.15f;
                                particle.Quad.Point3 = previousTrail1 + direction * 0.15f;
                                previousTrail0       = particle.Quad.Point1;
                                previousTrail1       = particle.Quad.Point2;
                            }
                        }

                        previousParticlePosition = particle.ActualPosition;

                        m_AABB         = m_AABB.Include(ref previousParticlePosition);
                        particle.Flags = GetEffect().IsInFrustum ? particle.Flags | MyAnimatedParticle.ParticleFlags.IsInFrustum : particle.Flags & ~MyAnimatedParticle.ParticleFlags.IsInFrustum;
                        continue;
                    }

                    if (inheritedGeneration != null)
                    {
                        inheritedGeneration.m_particlesToCreate = particlesToCreate;
                        inheritedGeneration.EffectMatrix        = MatrixD.CreateWorld(particle.ActualPosition, Vector3D.Normalize(particle.Velocity), Vector3D.Cross(Vector3D.Left, particle.Velocity));
                        inheritedGeneration.UpdateParticlesCreation();
                    }

                    m_particles.Remove(particle);
                    MyTransparentGeometry.DeallocateAnimatedParticle(particle);
                }
            }

            VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
        }
Esempio n. 20
0
        public static void DrawTransparentCylinder(ref MatrixD worldMatrix, float radius1, float radius2, float length,
                                                   Vector4 lineColor, Vector4 faceColor, int wireDivideRatio, float thickness,
                                                   MyStringId?lineMaterial = null, MyStringId?faceMaterial = null)
        {
            Vector3D centerTop    = Vector3D.Transform(new Vector3D(0, length / 2f, 0), ref worldMatrix);
            Vector3D centerBottom = Vector3D.Transform(new Vector3D(0, -length / 2f, 0), ref worldMatrix);

            Vector3D upDir = Vector3D.TransformNormal(new Vector3D(0, 1, 0), ref worldMatrix);

            upDir.Normalize();

            Vector3D currTop    = Vector3D.Zero;
            Vector3D currBottom = Vector3D.Zero;
            Vector3D prevTop    = Vector3D.Zero;
            Vector3D prevBottom = Vector3D.Zero;
            float    num        = 360f / wireDivideRatio;

            for (int i = 0; i <= wireDivideRatio; i++)
            {
                float degrees = i * num;
                currTop.X    = (float)(radius1 * Math.Cos(MathHelper.ToRadians(degrees)));
                currTop.Y    = length / 2f;
                currTop.Z    = (float)(radius1 * Math.Sin(MathHelper.ToRadians(degrees)));
                currBottom.X = (float)(radius2 * Math.Cos(MathHelper.ToRadians(degrees)));
                currBottom.Y = -length / 2f;
                currBottom.Z = (float)(radius2 * Math.Sin(MathHelper.ToRadians(degrees)));
                currTop      = Vector3D.Transform(currTop, worldMatrix);
                currBottom   = Vector3D.Transform(currBottom, worldMatrix);

                if (lineMaterial.HasValue)
                {
                    MySimpleObjectDraw.DrawLine(currBottom, currTop, lineMaterial, ref lineColor, thickness);
                }

                if (i > 0)
                {
                    if (lineMaterial.HasValue)
                    {
                        MySimpleObjectDraw.DrawLine(prevBottom, currBottom, lineMaterial, ref lineColor, thickness);
                        MySimpleObjectDraw.DrawLine(prevTop, currTop, lineMaterial, ref lineColor, thickness);
                    }

                    if (faceMaterial.HasValue)
                    {
                        var quad = new MyQuadD()
                        {
                            Point0 = prevTop,
                            Point1 = currTop,
                            Point2 = currBottom,
                            Point3 = prevBottom
                        };
                        MyTransparentGeometry.AddQuad(faceMaterial.Value, ref quad, faceColor, ref currTop);

                        MyTransparentGeometry.AddTriangleBillboard(centerTop, currTop, prevTop, upDir, upDir, upDir,
                                                                   Vector2.Zero, Vector2.Zero, Vector2.Zero, faceMaterial.Value, 0, currTop, faceColor);
                        MyTransparentGeometry.AddTriangleBillboard(centerBottom, currBottom, prevBottom, -upDir, -upDir, -upDir,
                                                                   Vector2.Zero, Vector2.Zero, Vector2.Zero, faceMaterial.Value, 0, currBottom, faceColor);
                    }
                }

                prevBottom = currBottom;
                prevTop    = currTop;
            }
        }
Esempio n. 21
0
        private void DrawActiveMarks()
        {
            var s = _session;

            var time                = s.Tick % 20; // forward and backward total time
            var increase            = time < 10;
            var directionalTimeStep = increase ? time  : 19 - time;
            var textureMap          = s.HudUi.PaintedTexture[directionalTimeStep];
            var colorStep           = s.Tick % 120;
            var amplify             = colorStep <= 60;
            var modifyStep          = MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS;
            var cMod1               = MathHelper.Clamp(amplify ? (colorStep * modifyStep) :  2 - (+(colorStep * modifyStep)), 0.1f, 1f);
            var left                = (Vector3)s.CameraMatrix.Left;
            var up            = (Vector3)s.CameraMatrix.Up;
            var scale         = s.Settings.ClientConfig.HudScale;
            var screenScale   = 0.1 * s.ScaleFov;
            var size          = (float)((0.0025f * scale) * s.ScaleFov);
            var invScaler     = MathHelper.Clamp(1 / s.ScaleFov, 0, 20);
            var fontScale     = scale * s.ScaleFov;
            var invScaleLimit = 4.2;

            if (invScaler >= invScaleLimit)
            {
                fontScale *= (invScaler / invScaleLimit);
                size      *= (float)(invScaler / invScaleLimit);
                invScaler  = MathHelper.Clamp(20f / invScaler, 1, 20);
            }

            var fontYOffset = (float)((-0.05f * scale) * invScaler);

            for (int i = 0; i < s.ActiveMarks.Count; i++)
            {
                var mark       = s.ActiveMarks[i];
                var player     = mark.Item1;
                var repColor   = mark.Item2;
                var fakeTarget = mark.Item3;

                var textColor = new Vector4(repColor.X, repColor.Y, repColor.Z, cMod1 * repColor.W);

                var targetCenter = fakeTarget.GetFakeTargetInfo(s.TrackingAi).WorldPosition;
                var viewSphere   = new BoundingSphereD(targetCenter, 100f);
                if (!s.Camera.IsInFrustum(ref viewSphere))
                {
                    continue;
                }

                var screenPos = s.Camera.WorldToScreen(ref targetCenter);

                Vector3D drawPos = screenPos;
                if (Vector3D.Transform(targetCenter, s.Camera.ViewMatrix).Z > 0)
                {
                    drawPos.X *= -1;
                    drawPos.Y  = -1;
                }

                var dotpos = new Vector2D(MathHelper.Clamp(drawPos.X, -0.98, 0.98), MathHelper.Clamp(drawPos.Y, -0.98, 0.98));
                dotpos.X *= (float)(screenScale * _session.AspectRatio);
                dotpos.Y *= (float)screenScale;
                drawPos   = Vector3D.Transform(new Vector3D(dotpos.X, dotpos.Y, -0.1), s.CameraMatrix);


                MyQuadD quad;
                MyUtils.GetBillboardQuadOriented(out quad, ref drawPos, size, size, ref left, ref up);
                MyTransparentGeometry.AddTriangleBillboard(quad.Point0, quad.Point1, quad.Point2, Vector3.Zero, Vector3.Zero, Vector3.Zero, textureMap.P0, textureMap.P1, textureMap.P3, textureMap.Material, 0, drawPos, repColor, BlendTypeEnum.PostPP);
                MyTransparentGeometry.AddTriangleBillboard(quad.Point0, quad.Point3, quad.Point2, Vector3.Zero, Vector3.Zero, Vector3.Zero, textureMap.P0, textureMap.P2, textureMap.P3, textureMap.Material, 0, drawPos, repColor, BlendTypeEnum.PostPP);

                string textLine1   = player.DisplayName;
                var    fontSize    = (float)Math.Round(10 * fontScale, 1);
                var    fontHeight  = 0.75f;
                var    fontAge     = -1;
                var    fontJustify = Hud.Justify.Center;
                var    fontType    = Hud.FontType.Shadow;
                var    elementId   = 3102 + (100 + i);
                s.HudUi.AddText(text: textLine1, x: (float)screenPos.X, y: (float)screenPos.Y + fontYOffset, elementId: elementId, ttl: fontAge, color: textColor, justify: fontJustify, fontType: fontType, fontSize: fontSize, heightScale: fontHeight);
            }
        }
        private void UpdateBolts(bool active = false)
        {
            if (MyAPIGateway.Session.Player == null)
            {
                return;
            }

            if (Vector3D.DistanceSquared(MyAPIGateway.Session.Player.GetPosition(), m_block.PositionComp.GetPosition()) > 50f * 50f)
            {
                return;
            }

            for (int s = m_activeBolts.Count - 1; s >= 0; s--)
            {
                var activeItem = m_activeBolts[s];

                activeItem.Position++;
                if (activeItem.Position >= activeItem.MaxPosition)
                {
                    m_activeBolts.Remove(activeItem);
                    continue;
                }
            }

            if (m_activeBolts.Count < m_maxBolts)
            {
                int numAdd = m_maxBolts - m_activeBolts.Count;
                for (int r = 0; r < numAdd; r++)
                {
                    var bolt     = LightningBoltEffect.BoltPool[MyUtils.GetRandomInt(0, LightningBoltEffect.BoltPool.Count)];
                    var boltItem = new LightningBoltInstance(bolt, null, 60 + MyUtils.GetRandomInt(-10, 15));
                    m_activeBolts.Add(boltItem);
                }
            }

            for (int s = 0; s < m_activeBolts.Count; s++)
            {
                var activeItem = m_activeBolts[s];

                Vector3D endBoltPosition = m_centerSphere.PositionComp.LocalMatrix.Translation + new Vector3D(0f, 1.5f, 0f);

                int startPos      = 0;
                int maxPos        = activeItem.Bolt.Points.Count;
                var previousPoint = activeItem.Bolt.Points[startPos];
                var color         = new Vector4(0.35f, 0.05f, 0.35f, 0.75f);
                if (active)
                {
                    color = new Vector4(0.05f, 0.05f, 0.35f, 0.75f);
                }

                for (int r = startPos + 1; r < maxPos; r++)
                {
                    var currentPoint = activeItem.Bolt.Points[startPos + r];

                    if (previousPoint.Length() > endBoltPosition.Length())
                    {
                        break;
                    }

                    var startPoint = Vector3D.Transform(currentPoint, MatrixD.CreateRotationY(MathHelper.ToRadians((float)activeItem.Position * 5)));
                    startPoint -= new Vector3D(0f, 1.5f, 0f);
                    startPoint  = Vector3D.Transform(startPoint, m_block.WorldMatrix);

                    var endPoint = Vector3D.Transform(previousPoint, MatrixD.CreateRotationY(MathHelper.ToRadians((float)activeItem.Position * 5)));
                    endPoint -= new Vector3D(0f, 1.5f, 0f);
                    endPoint  = Vector3D.Transform(endPoint, m_block.WorldMatrix);

                    var dir    = Vector3D.Normalize(endPoint - startPoint);
                    var length = (endPoint - startPoint).Length() * 2f;

                    float pulse = MathExtensions.TrianglePulse((float)activeItem.Position, 1f, activeItem.MaxPosition / 2f) + 0.2f;
                    if (activeItem.Position < 10)
                    {
                        pulse = MathExtensions.TrianglePulse((float)activeItem.Position, 1f, 2.5f);
                    }

                    Vector4 diff      = color * pulse;
                    float   thickness = (0.0125f);

                    MyTransparentGeometry.AddLineBillboard(MyStringId.GetOrCompute("Testfly"), diff, startPoint, dir, (float)length, (float)thickness);
                    previousPoint = currentPoint;
                }
            }
        }
Esempio n. 23
0
        private void DrawSelector()
        {
            var s = _session;

            if (!_cachedPointerPos)
            {
                InitPointerOffset(0.05);
            }
            if (!_cachedTargetPos)
            {
                InitTargetOffset();
            }
            var offetPosition = Vector3D.Transform(PointerOffset, _session.CameraMatrix);

            if (s.UiInput.CameraBlockView)
            {
                _pointerPosition.Y = 0f;
            }
            else if (s.UiInput.FirstPersonView)
            {
                if (!MyUtils.IsZero(_pointerPosition.Y))
                {
                    _pointerPosition.Y = 0f;
                    InitPointerOffset(0.05);
                }
            }
            else if (s.UiInput.CtrlPressed)
            {
                if (s.UiInput.PreviousWheel != s.UiInput.CurrentWheel)
                {
                    var currentPos = _pointerPosition.Y;
                    if (s.UiInput.CurrentWheel > s.UiInput.PreviousWheel)
                    {
                        currentPos += 0.05f;
                    }
                    else
                    {
                        currentPos -= 0.05f;
                    }
                    var clampPos = MathHelper.Clamp(currentPos, -1.25f, 1.25f);
                    _3RdPersonPos.Y = clampPos;
                    InitPointerOffset(0.05);
                }
                if (!MyUtils.IsEqual(_pointerPosition, _3RdPersonPos))
                {
                    _pointerPosition = _3RdPersonPos;
                    InitPointerOffset(0.05);
                }
            }
            else if (!MyUtils.IsEqual(_pointerPosition, _3RdPersonPos))
            {
                _pointerPosition = _3RdPersonPos;
                InitPointerOffset(0.05);
            }

            SelectTarget(manualSelect: false);

            if (s.Tick - _lastDrawTick > 1 && _delay++ < 10)
            {
                return;
            }
            _delay        = 0;
            _lastDrawTick = s.Tick;

            MyTransparentGeometry.AddBillboardOriented(_cross, _reticleColor, offetPosition, s.CameraMatrix.Left, s.CameraMatrix.Up, (float)PointerAdjScale, BlendTypeEnum.PostPP);
            DrawReticle = true;
        }
Esempio n. 24
0
        bool UpdateParticles(bool spawn)
        {
            if (!Main.Settings.sprayParticles)
            {
                return(false);
            }

            IMyCamera camera = MyAPIGateway.Session?.Camera;

            if (camera == null)
            {
                return(false);
            }

            MatrixD matrix = Rifle.WorldMatrix;

            if (Vector3D.DistanceSquared(camera.WorldMatrix.Translation, matrix.Translation) > SprayMaxViewDistSq)
            {
                return(false);
            }

            bool paused = Main.IsPaused;

            if (!paused && spawn)
            {
                Particle particle = Main.ToolHandler.GetPooledParticle();
                particle.Init(matrix, ParticleColor);
                Particles.Add(particle);
            }

            if (Particles.Count > 0)
            {
                //const double NozzlePosX = 0.06525;
                //const double NozzlePosZ = 0.16;
                //Vector3D muzzleWorldPos = matrix.Translation + matrix.Up * NozzlePosX + matrix.Forward * NozzlePosZ;
                Vector3D muzzleWorldPos = Rifle.GetMuzzlePosition();

                for (int i = Particles.Count - 1; i >= 0; i--)
                {
                    Particle p = Particles[i];

                    MyTransparentGeometry.AddPointBillboard(SprayMaterial, p.Color, muzzleWorldPos + p.RelativePosition, p.Radius, p.Angle, blendType: SprayBlendType);

                    if (!paused)
                    {
                        if (--p.Life <= 0 || p.Color.A <= 0)
                        {
                            Particles.RemoveAtFast(i);
                            Main.ToolHandler.ReturnParticleToPool(p);
                            continue;
                        }

                        if (p.Angle > 0)
                        {
                            p.Angle += (p.Life * 0.001f);
                        }
                        else
                        {
                            p.Angle -= (p.Life * 0.001f);
                        }

                        p.RelativePosition += p.VelocityPerTick;
                        p.VelocityPerTick  *= 1.3f;
                        p.Radius           *= MyUtils.GetRandomFloat(1.25f, 1.45f);

                        if (p.Life <= 20)
                        {
                            p.Color *= 0.7f;
                        }
                    }
                }
            }

            return(true);
        }
            public void Draw(MyEffectDistantImpostors effect, MyImpostorType impostorType)
            {
                if (!ImpostorProperties.Enabled)
                {
                    return;
                }

                if (impostorType != ImpostorProperties.ImpostorType)
                {
                    return;
                }

                if (ImpostorProperties.ImpostorType == MyImpostorType.Billboards)
                {
                    if (m_trianglesCount <= 0)
                    {
                        return;
                    }

                    m_animationTime += ImpostorProperties.AnimationSpeed;

                    Device device = MyMinerGame.Static.GraphicsDevice;

                    if (MyRenderConstants.RenderQualityProfile.ForwardRender)
                    {
                        DepthStencilState.DepthRead.Apply();
                    }

                    Matrix worldMatrix = Matrix.Identity;

                    if (ImpostorProperties.AnimationSpeed.X > 0)
                    {
                        worldMatrix *= Matrix.CreateRotationX(m_animationTime.X);
                    }
                    if (ImpostorProperties.AnimationSpeed.Y > 0)
                    {
                        worldMatrix *= Matrix.CreateRotationX(m_animationTime.Y);
                    }
                    if (ImpostorProperties.AnimationSpeed.Z > 0)
                    {
                        worldMatrix *= Matrix.CreateRotationX(m_animationTime.Z);
                    }

                    worldMatrix.Translation = MyCamera.Position * 0.5f;
                    effect.SetWorldMatrix(worldMatrix);

                    MyTexture2D texture = null;
                    if (ImpostorProperties.Material.HasValue)
                    {
                        texture = MyTransparentGeometry.GetTexture(ImpostorProperties.Material.Value);
                    }
                    effect.SetImpostorTexture(texture);
                    device.SetStreamSource(0, m_vertexBuffer, 0, MyVertexFormatPositionTextureColor.Stride);
                    device.VertexDeclaration = MyVertexFormatPositionTextureColor.VertexDeclaration;

                    effect.SetTechnique(MyEffectDistantImpostors.Technique.ColoredLit);

                    effect.Begin();
                    device.DrawPrimitives(PrimitiveType.TriangleList, 0, m_trianglesCount);
                    effect.End();
                    MyPerformanceCounter.PerCameraDraw.TotalDrawCalls++;
                }
                else if (ImpostorProperties.ImpostorType == MyImpostorType.Nebula && !MyRenderConstants.RenderQualityProfile.ForwardRender)
                {
                    m_animationTime += ImpostorProperties.AnimationSpeed * (MyFpsManager.FrameTime / 100.0f);

                    BlendState.NonPremultiplied.Apply();
                    RasterizerState.CullCounterClockwise.Apply();
                    DepthStencilState.None.Apply();

                    MyRender.Blit(MyRender.GetRenderTarget(MyRenderTargets.AuxiliaryHalf0), true);
                }
            }
Esempio n. 26
0
        //  Draw the projectile but only if desired polyline trail distance can fit in the trajectory (otherwise we will see polyline growing from the origin and it's ugly).
        //  Or draw if this is last draw of this projectile (useful for short-distance shots).
        public void Draw()
        {
            const float PROJECTILE_POLYLINE_DESIRED_LENGTH = 120;

            //var velPerFrame = m_velocity * VRage.Game.MyEngineConstants.PHYSICS_STEP_SIZE_IN_SECONDS;
            //for (int i = 0; i < 70; i += 5)
            //{
            //    Color col = new Color(255, 0, i * 5, 255);
            //    VRageRender.MyRenderProxy.DebugDrawLine3D(m_position + i * velPerFrame, m_position + i * velPerFrame + 5 * velPerFrame, col, Color.Yellow, false);
            //}

            double trajectoryLength = Vector3D.Distance(m_position, m_origin);

            if ((trajectoryLength > 0) || (m_state == MyProjectileStateEnum.KILLED))
            {
                if (m_state == MyProjectileStateEnum.KILLED)
                {
                    m_state = MyProjectileStateEnum.KILLED_AND_DRAWN;
                }

                if (!m_positionChecked)
                {
                    return;
                }

                //  If we calculate previous position using normalized direction (insted of velocity), projectile trails will
                //  look like coming from cannon, and that is desired. Even during fast movement, acceleration, rotation or changes in movement directions.
                //Vector3 previousPosition = m_position - m_directionNormalized * projectileTrailLength * 1.05f;
                Vector3D previousPosition = m_position - m_directionNormalized * PROJECTILE_POLYLINE_DESIRED_LENGTH * VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS;
                //Vector3 previousPosition = m_previousPosition;
                //Vector3 previousPosition = m_initialSunWindPosition - MyMwcUtils.Normalize(m_desiredVelocity) * projectileTrailLength;

                Vector3D direction = Vector3D.Normalize(m_position - previousPosition);

                double projectileTrailLength = LengthMultiplier * m_projectileAmmoDefinition.ProjectileTrailScale;// PROJECTILE_POLYLINE_DESIRED_LENGTH;

                projectileTrailLength *= MyParticlesManager.Paused ? 0.6f : MyUtils.GetRandomFloat(0.6f, 0.8f);

                if (trajectoryLength < projectileTrailLength)
                {
                    projectileTrailLength = trajectoryLength;
                }

                if (m_state == MyProjectileStateEnum.ACTIVE || trajectoryLength * trajectoryLength >= (m_velocity.LengthSquared() * VRage.Game.MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS * CHECK_INTERSECTION_INTERVAL))
                {
                    previousPosition = m_position - projectileTrailLength * direction;
                }
                else
                {
                    previousPosition = m_position - ((trajectoryLength - projectileTrailLength) * MyUtils.GetRandomFloat(0, 1) + projectileTrailLength) * direction;
                }

                //float color = MyMwcUtils.GetRandomFloat(1, 2);
                float color     = MyParticlesManager.Paused ? 1 : MyUtils.GetRandomFloat(1, 2);
                float thickness = (MyParticlesManager.Paused ? 0.2f : MyUtils.GetRandomFloat(0.2f, 0.3f)) * m_projectileAmmoDefinition.ProjectileTrailScale;

                //  Line particles (polyline) don't look good in distance. Start and end aren't rounded anymore and they just
                //  look like a pieces of paper. Especially when zoom-in.
                thickness *= MathHelper.Lerp(0.2f, 0.8f, MySector.MainCamera.Zoom.GetZoomLevel());

                float alphaCone = 1;

                if (projectileTrailLength > 0)
                {
                    if (m_projectileAmmoDefinition.ProjectileTrailMaterial != null)
                    {
                        MyTransparentGeometry.AddLineBillboard(m_projectileAmmoDefinition.ProjectileTrailMaterial, new Vector4(m_projectileAmmoDefinition.ProjectileTrailColor, 1),
                                                               previousPosition, direction, (float)projectileTrailLength, thickness);
                    }
                    else
                    {
                        MyTransparentGeometry.AddLineBillboard("ProjectileTrailLine", new Vector4(m_projectileAmmoDefinition.ProjectileTrailColor * color, 1) * alphaCone,
                                                               previousPosition, direction, (float)projectileTrailLength, thickness);
                    }
                }
            }
        }
        public override void Draw()
        {
            base.Draw();

            var worldToLocal = MatrixD.Invert(Container.Entity.PositionComp.WorldMatrix);

            if (m_thrust.CanDraw())
            {
                m_thrust.UpdateThrustFlame();
                m_thrust.UpdateThrustColor();

                foreach (var flame in m_thrust.Flames)
                {
                    if (m_thrust.CubeGrid.Physics == null)
                    {
                        continue;
                    }

                    var flameDirection = Vector3D.TransformNormal(flame.Direction, Container.Entity.PositionComp.WorldMatrix);
                    var flamePosition  = Vector3D.Transform(flame.Position, Container.Entity.PositionComp.WorldMatrix);

                    float radius    = m_thrust.ThrustRadiusRand * flame.Radius;
                    float length    = m_thrust.ThrustLengthRand * flame.Radius;
                    float thickness = m_thrust.ThrustThicknessRand * flame.Radius;

                    Vector3D velocityAtNewCOM = Vector3D.Cross(m_thrust.CubeGrid.Physics.AngularVelocity, flamePosition - m_thrust.CubeGrid.Physics.CenterOfMassWorld);
                    var      velocity         = m_thrust.CubeGrid.Physics.LinearVelocity + velocityAtNewCOM;

                    if (m_thrust.CurrentStrength > 0 && length > 0)
                    {
                        float angle     = 1 - Math.Abs(Vector3.Dot(MyUtils.Normalize(MySector.MainCamera.Position - flamePosition), flameDirection));
                        float alphaCone = (1 - (float)Math.Pow(1 - angle, 30)) * 0.5f;
                        //  We move polyline particle backward, because we are stretching ball texture and it doesn't look good if stretched. This will hide it.
                        MyTransparentGeometry.AddLineBillboard(m_thrust.FlameLengthMaterial, m_thrust.ThrustColor * alphaCone, flamePosition - flameDirection * length * 0.25f,
                                                               GetRenderObjectID(), ref worldToLocal, flameDirection, length, thickness);
                    }

                    if (radius > 0)
                    {
                        MyTransparentGeometry.AddPointBillboard(m_thrust.FlamePointMaterial, m_thrust.ThrustColor, flamePosition, GetRenderObjectID(), ref worldToLocal, radius, 0);
                    }

                    if (m_landingEffectUpdateCounter-- <= 0)
                    {
                        m_landingEffectUpdateCounter = (int)Math.Round(m_landingEffectUpdateInterval * (0.8f + MyRandom.Instance.NextFloat() * 0.4f));

                        m_lastHitInfo = MyPhysics.CastRay(flamePosition,
                                                          flamePosition + flameDirection * m_thrust.ThrustLengthRand * (m_thrust.CubeGrid.GridSizeEnum == MyCubeSize.Large ? 5.0f : 3.0f) * flame.Radius,
                                                          MyPhysics.ObjectDetectionCollisionLayer);
                    }

                    if (m_landingEffect != null)
                    {
                        m_landingEffect.Stop(true);
                        m_landingEffect = null;
                        --m_landingEffectCount;
                    }
                    continue;

                    if (m_landingEffect == null && m_landingEffectCount < m_maxNumberLandingEffects && MyParticlesManager.TryCreateParticleEffect(54, out m_landingEffect))
                    {
                        ++m_landingEffectCount;
                    }

                    if (m_landingEffect == null)
                    {
                        continue;
                    }

                    m_landingEffect.UserScale   = m_thrust.CubeGrid.GridSize;
                    m_landingEffect.WorldMatrix = MatrixD.CreateFromTransformScale(Quaternion.CreateFromForwardUp(-m_lastHitInfo.Value.HkHitInfo.Normal, Vector3.CalculatePerpendicularVector(m_lastHitInfo.Value.HkHitInfo.Normal)), m_lastHitInfo.Value.Position, Vector3D.One);
                }
            }
            else if (m_landingEffect != null)
            {
                m_landingEffect.Stop(true);
                m_landingEffect = null;
                --m_landingEffectCount;
            }

            if (m_thrust.Light != null)
            {
                m_thrust.UpdateLight();
            }
        }
Esempio n. 28
0
 public override void Draw()
 {
     base.Draw();
     if (this.m_light != null)
     {
         bool        flag          = true;
         MyCharacter skinnedEntity = base.m_skinnedEntity as MyCharacter;
         float       num           = Vector3.DistanceSquared((Vector3)skinnedEntity.PositionComp.GetPosition(), (Vector3)MySector.MainCamera.Position);
         if (num < 1600f)
         {
             Vector3  reflectorDirection = this.m_light.ReflectorDirection;
             float    length             = 2.56f;
             float    thickness          = 0.48f;
             Vector3  vector2            = new Vector3((Vector4)this.m_light.ReflectorColor);
             Vector3D vectord            = this.m_light.Position + (reflectorDirection * 0.28f);
             float    num4 = Vector3.Dot(Vector3.Normalize(MySector.MainCamera.Position - vectord), reflectorDirection);
             float    currentLightPower = skinnedEntity.CurrentLightPower;
             float    num6 = ((1f - ((float)Math.Pow((double)(1f - (1f - Math.Abs(num4))), 30.0))) * 0.5f) * currentLightPower;
             if (((!ReferenceEquals(skinnedEntity, MySession.Static.LocalCharacter) || (!MySession.Static.CameraController.ForceFirstPersonCamera && !MySession.Static.CameraController.IsInFirstPersonView)) && ((currentLightPower > 0f) && (this.m_leftLightIndex != -1))) && (this.m_rightLightIndex != -1))
             {
                 float num8 = 1296f;
                 float num9 = 1f - MathHelper.Clamp((float)((num - num8) / (1600f - num8)), (float)0f, (float)1f);
                 if (((length > 0f) && (thickness > 0f)) && (num9 > 0f))
                 {
                     MyTransparentGeometry.AddLineBillboard(ID_REFLECTOR_CONE, (new Vector4(vector2, 1f) * num6) * num9, this.m_leftGlarePosition - (reflectorDirection * 0.05f), reflectorDirection, length, thickness, MyBillboard.BlendTypeEnum.AdditiveBottom, -1, 1f, null);
                     MyTransparentGeometry.AddLineBillboard(ID_REFLECTOR_CONE, (new Vector4(vector2, 1f) * num6) * num9, this.m_rightGlarePosition - (reflectorDirection * 0.05f), reflectorDirection, length, thickness, MyBillboard.BlendTypeEnum.AdditiveBottom, -1, 1f, null);
                 }
                 if (num4 > 0f)
                 {
                     flag = false;
                     if (this.m_flareLeft != null)
                     {
                         this.m_flareLeft.GlareOn            = true;
                         this.m_flareLeft.Position           = this.m_leftGlarePosition;
                         this.m_flareLeft.ReflectorDirection = reflectorDirection;
                         this.m_flareLeft.UpdateLight();
                     }
                     if (this.m_flareRight != null)
                     {
                         this.m_flareRight.GlareOn            = true;
                         this.m_flareRight.Position           = this.m_rightGlarePosition;
                         this.m_flareRight.ReflectorDirection = reflectorDirection;
                         this.m_flareRight.UpdateLight();
                     }
                 }
             }
             if ((ReferenceEquals(MySession.Static.ControlledEntity, skinnedEntity) || ((MySession.Static.ControlledEntity is MyCockpit) && ReferenceEquals(((MyCockpit)MySession.Static.ControlledEntity).Pilot, skinnedEntity))) || ((MySession.Static.ControlledEntity is MyLargeTurretBase) && ReferenceEquals(((MyLargeTurretBase)MySession.Static.ControlledEntity).Pilot, skinnedEntity)))
             {
                 if (skinnedEntity.IsDead && (skinnedEntity.CurrentRespawnCounter > 0f))
                 {
                     this.DrawBlood(1f);
                 }
                 if (!skinnedEntity.IsDead && (this.m_currentHitIndicatorCounter > 0f))
                 {
                     this.m_currentHitIndicatorCounter -= 0.01666667f;
                     if (this.m_currentHitIndicatorCounter < 0f)
                     {
                         this.m_currentHitIndicatorCounter = 0f;
                     }
                     float alpha = this.m_currentHitIndicatorCounter / 0.8f;
                     this.DrawBlood(alpha);
                 }
                 if (skinnedEntity.StatComp != null)
                 {
                     float healthRatio = skinnedEntity.StatComp.HealthRatio;
                     if ((healthRatio <= MyCharacterStatComponent.HEALTH_RATIO_CRITICAL) && !skinnedEntity.IsDead)
                     {
                         float alpha = (MathHelper.Clamp((float)(MyCharacterStatComponent.HEALTH_RATIO_CRITICAL - healthRatio), (float)0f, (float)1f) / MyCharacterStatComponent.HEALTH_RATIO_CRITICAL) + 0.3f;
                         this.DrawBlood(alpha);
                     }
                 }
             }
         }
         if ((flag && (this.m_flareRight != null)) && this.m_flareLeft.GlareOn)
         {
             this.m_flareLeft.GlareOn = false;
             this.m_flareLeft.UpdateLight();
             this.m_flareRight.GlareOn = false;
             this.m_flareRight.UpdateLight();
         }
         this.DrawJetpackThrusts(skinnedEntity.UpdateCalled());
         this.DrawDisconnectedIndicator();
     }
 }
Esempio n. 29
0
        private void AgingTextDraw()
        {
            var up   = (Vector3)_cameraWorldMatrix.Up;
            var left = (Vector3)_cameraWorldMatrix.Left;

            foreach (var textAdd in _agingTextRequests.Values)
            {
                textAdd.Position.Z = _viewPortSize.Z;
                var requestPos = textAdd.Position;
                requestPos.Z = _viewPortSize.Z;
                var widthScaler = textAdd.Font == FontType.Shadow ? ShadowSizeScaler : 1f;

                var textPos = Vector3D.Transform(requestPos, _cameraWorldMatrix);
                switch (textAdd.Justify)
                {
                case Justify.Center:
                    textPos += _cameraWorldMatrix.Left * (((textAdd.MessageWidth * ShadowWidthScaler) * 0.5f) * widthScaler);
                    break;

                case Justify.Right:
                    textPos -= _cameraWorldMatrix.Left * ((textAdd.MessageWidth * ShadowWidthScaler) * widthScaler);
                    break;

                case Justify.Left:
                    textPos -= _cameraWorldMatrix.Right * ((textAdd.MessageWidth * ShadowWidthScaler) * widthScaler);
                    break;

                case Justify.None:
                    textPos -= _cameraWorldMatrix.Left * ((textAdd.FontSize * 0.5f) * widthScaler);
                    break;
                }

                var height = textAdd.FontSize * textAdd.HeightScale;
                var remove = textAdd.Ttl-- < 0;

                for (int i = 0; i < textAdd.Data.Count; i++)
                {
                    var textData = textAdd.Data[i];
                    textData.WorldPos.Z = _viewPortSize.Z;

                    if (textData.UvDraw)
                    {
                        var     width = (textData.ScaledWidth * widthScaler) * _session.AspectRatioInv;
                        MyQuadD quad;
                        MyUtils.GetBillboardQuadOriented(out quad, ref textPos, width, height, ref left, ref up);

                        if (textAdd.Color != Vector4.Zero)
                        {
                            MyTransparentGeometry.AddTriangleBillboard(quad.Point0, quad.Point1, quad.Point2, Vector3.Zero, Vector3.Zero, Vector3.Zero, textData.P0, textData.P1, textData.P3, textData.Material, 0, textPos, textAdd.Color, textData.Blend);
                            MyTransparentGeometry.AddTriangleBillboard(quad.Point0, quad.Point3, quad.Point2, Vector3.Zero, Vector3.Zero, Vector3.Zero, textData.P0, textData.P2, textData.P3, textData.Material, 0, textPos, textAdd.Color, textData.Blend);
                        }
                        else
                        {
                            MyTransparentGeometry.AddTriangleBillboard(quad.Point0, quad.Point1, quad.Point2, Vector3.Zero, Vector3.Zero, Vector3.Zero, textData.P0, textData.P1, textData.P3, textData.Material, 0, textPos, textData.Blend);
                            MyTransparentGeometry.AddTriangleBillboard(quad.Point0, quad.Point3, quad.Point2, Vector3.Zero, Vector3.Zero, Vector3.Zero, textData.P0, textData.P2, textData.P3, textData.Material, 0, textPos, textData.Blend);
                        }
                    }

                    textPos -= _cameraWorldMatrix.Left * textData.ScaledWidth;

                    if (remove)
                    {
                        textAdd.Data.Remove(textData);
                        _textDataPool.Return(textData);
                    }
                }

                textAdd.Data.ApplyRemovals();
                AgingTextRequest request;
                if (textAdd.Data.Count == 0 && _agingTextRequests.TryRemove(textAdd.ElementId, out request))
                {
                    _agingTextRequests.Remove(textAdd.ElementId);
                    _agingTextRequestPool.Return(request);
                }
            }
            AgingTextures = _agingTextRequests.Count > 0;
        }
Esempio n. 30
0
        internal void Run()
        {
            if (Session.Tick180)
            {
                Log.LineShortDate($"(DRAWS) --------------- AvShots:[{AvShots.Count}] OnScreen:[{_onScreens}] Shrinks:[{_shrinks}] Glows:[{_glows}] Models:[{_models}] P:[{Session.Projectiles.ActiveProjetiles.Count}] P-Pool:[{Session.Projectiles.ProjectilePool.Count}] AvPool:[{AvShotPool.Count}] (AvBarrels 1:[{AvBarrels1.Count}] 2:[{AvBarrels2.Count}])", "stats");
                _glows   = 0;
                _shrinks = 0;
            }

            _onScreens = 0;
            _models    = 0;
            for (int i = AvShots.Count - 1; i >= 0; i--)
            {
                var av = AvShots[i];
                if (av.OnScreen != AvShot.Screen.None)
                {
                    _onScreens++;
                }
                var refreshed = av.LastTick == Session.Tick;

                if (refreshed && av.Tracer != AvShot.TracerState.Off && av.OnScreen != AvShot.Screen.None)
                {
                    var color    = av.Color;
                    var segColor = av.SegmentColor;

                    if (av.ShotFade > 0)
                    {
                        var fade = MathHelper.Clamp(1f - av.ShotFade, 0.005f, 1f);
                        color    *= fade;
                        segColor *= fade;
                    }

                    if (!av.AmmoDef.Const.OffsetEffect)
                    {
                        if (av.Tracer != AvShot.TracerState.Shrink)
                        {
                            if (av.AmmoDef.Const.TracerMode == AmmoConstants.Texture.Normal)
                            {
                                MyTransparentGeometry.AddLineBillboard(av.AmmoDef.Const.TracerTextures[0], color, av.TracerBack, av.PointDir, (float)av.VisualLength, (float)av.TracerWidth);
                            }
                            else if (av.AmmoDef.Const.TracerMode != AmmoConstants.Texture.Resize)
                            {
                                MyTransparentGeometry.AddLineBillboard(av.AmmoDef.Const.TracerTextures[av.TextureIdx], color, av.TracerBack, av.PointDir, (float)av.VisualLength, (float)av.TracerWidth);
                            }
                            else
                            {
                                var    seg           = av.AmmoDef.AmmoGraphics.Lines.Tracer.Segmentation;
                                var    stepPos       = av.TracerBack;
                                var    segTextureCnt = av.AmmoDef.Const.SegmentTextures.Length;
                                var    gapTextureCnt = av.AmmoDef.Const.TracerTextures.Length;
                                var    segStepLen    = seg.SegmentLength / segTextureCnt;
                                var    gapStepLen    = seg.SegmentGap / gapTextureCnt;
                                var    gapEnabled    = gapStepLen > 0;
                                int    j             = 0;
                                double travel        = 0;
                                while (travel < av.VisualLength)
                                {
                                    var mod   = j++ % 2;
                                    var gap   = gapEnabled && (av.SegmentGaped && mod == 0 || !av.SegmentGaped && mod == 1);
                                    var first = travel <= 0;

                                    double  width;
                                    double  rawLen;
                                    Vector4 dyncColor;
                                    if (!gap)
                                    {
                                        rawLen    = first ? av.SegmentLenTranserved : seg.SegmentLength;
                                        width     = av.SegmentWidth;
                                        dyncColor = segColor;
                                    }
                                    else
                                    {
                                        rawLen    = first ? av.SegmentLenTranserved : seg.SegmentGap;
                                        width     = av.TracerWidth;
                                        dyncColor = color;
                                    }

                                    var notLast   = travel + rawLen < av.VisualLength;
                                    var len       = notLast ? rawLen : av.VisualLength - travel;
                                    var clampStep = !gap?MathHelperD.Clamp((int)((len / segStepLen) + 0.5) - 1, 0, segTextureCnt - 1) : MathHelperD.Clamp((int)((len / gapStepLen) + 0.5) - 1, 0, gapTextureCnt);

                                    var material = !gap ? av.AmmoDef.Const.SegmentTextures[(int)clampStep] : av.AmmoDef.Const.TracerTextures[(int)clampStep];

                                    MyTransparentGeometry.AddLineBillboard(material, dyncColor, stepPos, av.PointDir, (float)len, (float)width);
                                    if (!notLast)
                                    {
                                        travel = av.VisualLength;
                                    }
                                    else
                                    {
                                        travel += len;
                                    }
                                    stepPos += (av.PointDir * len);
                                }
                            }
                        }
                    }
                    else
                    {
                        var list = av.Offsets;
                        for (int x = 0; x < list.Count; x++)
                        {
                            Vector3D fromBeam;
                            Vector3D toBeam;

                            if (x == 0)
                            {
                                fromBeam = av.OffsetMatrix.Translation;
                                toBeam   = Vector3D.Transform(list[x], av.OffsetMatrix);
                            }
                            else
                            {
                                fromBeam = Vector3D.Transform(list[x - 1], av.OffsetMatrix);
                                toBeam   = Vector3D.Transform(list[x], av.OffsetMatrix);
                            }

                            Vector3 dir     = (toBeam - fromBeam);
                            var     length  = dir.Length();
                            var     normDir = dir / length;
                            MyTransparentGeometry.AddLineBillboard(av.AmmoDef.Const.TracerTextures[0], color, fromBeam, normDir, length, (float)av.TracerWidth);

                            if (Vector3D.DistanceSquared(av.OffsetMatrix.Translation, toBeam) > av.TracerLengthSqr)
                            {
                                break;
                            }
                        }
                        list.Clear();
                    }
                }

                var shrinkCnt = av.TracerShrinks.Count;
                if (shrinkCnt > _shrinks)
                {
                    _shrinks = shrinkCnt;
                }

                if (shrinkCnt > 0)
                {
                    RunShrinks(av);
                }

                var glowCnt = av.GlowSteps.Count;

                if (glowCnt > _glows)
                {
                    _glows = glowCnt;
                }

                if (av.Trail != AvShot.TrailState.Off)
                {
                    var steps       = av.AmmoDef.AmmoGraphics.Lines.Trail.DecayTime;
                    var widthScaler = !av.AmmoDef.AmmoGraphics.Lines.Trail.UseColorFade;
                    var remove      = false;
                    for (int j = glowCnt - 1; j >= 0; j--)
                    {
                        var glow = av.GlowSteps[j];

                        if (!refreshed)
                        {
                            glow.Line = new LineD(glow.Line.From + av.ShootVelStep, glow.Line.To + av.ShootVelStep, glow.Line.Length);
                        }

                        if (av.OnScreen != AvShot.Screen.None)
                        {
                            var reduction = (av.GlowShrinkSize * glow.Step);
                            var width     = widthScaler ? (av.AmmoDef.Const.TrailWidth - reduction) * av.TrailScaler : av.AmmoDef.Const.TrailWidth * av.TrailScaler;
                            var color     = av.AmmoDef.AmmoGraphics.Lines.Trail.Color;

                            if (!widthScaler)
                            {
                                color *= MathHelper.Clamp(1f - reduction, 0.01f, 1f);
                            }

                            MyTransparentGeometry.AddLineBillboard(av.AmmoDef.Const.TrailTextures[0], color, glow.Line.From, glow.Line.Direction, (float)glow.Line.Length, width);
                        }

                        if (++glow.Step >= steps)
                        {
                            glow.Parent = null;
                            glow.Step   = 0;
                            remove      = true;
                            glowCnt--;
                            Glows.Push(glow);
                        }
                    }

                    if (remove)
                    {
                        av.GlowSteps.Dequeue();
                    }
                }

                if (glowCnt == 0 && shrinkCnt == 0 && av.MarkForClose)
                {
                    AvShotPool.Return(av);
                    AvShots.RemoveAtFast(i);
                }
            }
        }