internal void Draw(Rectangle rect, Color color, MyVideoRectangleFitMode fitMode)
        {
            int w = 0, h = 0;
            byte [] data = m_wrapper.GetTextureData(ref w, ref h);
            process_frame(data, w, h);

            Rectangle dst = rect;
            Rectangle src = new Rectangle(0, 0, w, h);
            var videoSize = new Vector2(w, h);
            float videoAspect = videoSize.X / videoSize.Y;
            float rectAspect = (float)rect.Width / (float)rect.Height;

            // Automatic decision based on ratios.
            if (fitMode == MyVideoRectangleFitMode.AutoFit)
                fitMode = (videoAspect > rectAspect) ? MyVideoRectangleFitMode.FitHeight : MyVideoRectangleFitMode.FitWidth;

            float scaleRatio = 0.0f;
            switch (fitMode)
            {
                case MyVideoRectangleFitMode.None:
                    break;

                case MyVideoRectangleFitMode.FitWidth:
                    scaleRatio = (float)dst.Width / videoSize.X;
                    dst.Height = (int)(scaleRatio * videoSize.Y);
                    if (dst.Height > rect.Height)
                    {
                        var diff = dst.Height - rect.Height;
                        dst.Height = rect.Height;
                        diff = (int)(diff / scaleRatio);
                        src.Y += (int)(diff * 0.5f);
                        src.Height -= diff;
                    }
                    break;

                case MyVideoRectangleFitMode.FitHeight:
                    scaleRatio = (float)dst.Height / videoSize.Y;
                    dst.Width = (int)(scaleRatio * videoSize.X);
                    if (dst.Width > rect.Width)
                    {
                        var diff = dst.Width - rect.Width;
                        dst.Width = rect.Width;
                        diff = (int)(diff / scaleRatio);
                        src.X += (int)(diff * 0.5f);
                        src.Width -= diff;
                    }
                    break;
            }
            dst.X = rect.Left + (rect.Width - dst.Width) / 2;
            dst.Y = rect.Top + (rect.Height - dst.Height) / 2;


            VRageMath.RectangleF destination = new VRageMath.RectangleF(dst.X, dst.Y, dst.Width, -dst.Height);
            VRageMath.Rectangle? source = src;
            Vector2 origin = new Vector2(src.Width / 2 * 0, src.Height);

            MySpritesRenderer.AddSingleSprite(m_texture, videoSize, color, origin, Vector2.UnitX, source, destination);
        }
        internal static void DrawTriangle(Vector3 v0, Vector3 v1, Vector3 v2, Color color)
        {
            var distance = ((v0 + v1 + v2) / 3f - MyEnvironment.CameraPosition).LengthSquared();
            m_triangleSortDistance.Add(distance);

            m_vertexList.Add(new MyVertexFormatPositionColor(v0, color));
            m_vertexList.Add(new MyVertexFormatPositionColor(v1, color));
            m_vertexList.Add(new MyVertexFormatPositionColor(v2, color));
        }
Example #3
0
        internal void AddQuad(Vector3 v0, Vector3 v1, Vector3 v2, Vector3 v3, Color color)
        {
            var bcolor = new Byte4(color.R, color.G, color.B, color.A);

            Add(new MyVertexFormatPositionColor(v0, bcolor));
            Add(new MyVertexFormatPositionColor(v1, bcolor));

            Add(new MyVertexFormatPositionColor(v1, bcolor));
            Add(new MyVertexFormatPositionColor(v2, bcolor));

            Add(new MyVertexFormatPositionColor(v2, bcolor));
            Add(new MyVertexFormatPositionColor(v3, bcolor));

            Add(new MyVertexFormatPositionColor(v3, bcolor));
            Add(new MyVertexFormatPositionColor(v0, bcolor));
        }
        internal static void AddPointBillboard(string material,
           Color color, Vector3D origin, float radius, float angle, int priority = 0, int customViewProjection = -1)
        {
            Debug.Assert(material != null);

            origin.AssertIsValid();
            angle.AssertIsValid();

            MyQuadD quad;
            if (MyUtils.GetBillboardQuadAdvancedRotated(out quad, origin, radius, angle, MyEnvironment.CameraPosition) != false)
            {
                MyBillboard billboard = SpawnBillboard();
                if (billboard == null)
                    return;

                billboard.Priority = priority;
                billboard.CustomViewProjection = customViewProjection;
                CreateBillboard(billboard, ref quad, material, ref color, ref origin);
            }
        }
Example #5
0
        internal void AddCone(Vector3 translation, Vector3 directionVec, Vector3 baseVec, int tessalation, Color color)
        {
            var axis = directionVec;
            axis.Normalize();

            var apex = translation + directionVec;

            var steps = tessalation;
            var stepsRcp = (float)(Math.PI * 2 / steps);
            for (int i = 0; i < 32; i++)
            {
                float a0 = i * stepsRcp;
                float a1 = (i + 1) * stepsRcp;

                var A = translation + Vector3.Transform(baseVec, Matrix.CreateFromAxisAngle(axis, a0));
                var B = translation + Vector3.Transform(baseVec, Matrix.CreateFromAxisAngle(axis, a1));

                Add(A, B, color);
                Add(A, apex, color);
            }
        }
        internal static void AddBillboardOriented(string material,
            Color color, Vector3D origin, Vector3 leftVector, Vector3 upVector, float radius, int priority = 0, int customViewProjection = -1)
        {
            Debug.Assert(material != null);

            origin.AssertIsValid();
            leftVector.AssertIsValid();
            upVector.AssertIsValid();
            radius.AssertIsValid();
            MyDebug.AssertDebug(radius > 0);

            MyBillboard billboard = SpawnBillboard();
            if (billboard == null)
                return;

            billboard.Priority = priority;
            billboard.CustomViewProjection = customViewProjection;

            MyQuadD quad;
            MyUtils.GetBillboardQuadOriented(out quad, ref origin, radius, ref leftVector, ref upVector);

            CreateBillboard(billboard, ref quad, material, ref color, ref origin);
        }
Example #7
0
 //  Draws sprite batch at specified SCREEN position (in screen coordinates, not normalized coordinates).
 public static void DrawSpriteBatch(string texture, Vector2 position, Rectangle?sourceRectangle, Color color, float rotation, Vector2 origin, float scale, SpriteEffects effects, float layerDepth, bool waitTillLoaded = true)
 {
     DrawSprite(texture, position, sourceRectangle, color, rotation, origin, scale, effects, layerDepth, waitTillLoaded);
 }
 //  Draws sprite batch at specified SCREEN position (in screen coordinates, not normalized coordinates).
 public static void DrawSpriteBatch(string texture, int x, int y, int width, int height, Color color, bool waitTillLoaded = true)
 {
     DrawSprite(texture, new Rectangle(x, y, width, height), color, waitTillLoaded);
 }
 public static void CreateBillboard(VRageRender.MyBillboard billboard, ref MyQuadD quad, string material,
     ref Color color, ref Vector3D origin, Vector2 uvOffset, bool colorize = false, bool near = false, bool lowres = false)
 {
     Debug.Assert(material != null);
     CreateBillboard(billboard, ref quad, material, null, 0, ref color, ref origin, uvOffset, colorize, near, lowres);
 }
Example #10
0
 internal MyVertexFormatPositionColor(Vector3 position, Color color)
 {
     Position = position;
     Color = new Byte4(color.PackedValue);
 }
        // Assuming engine order (+Z first)
        internal static unsafe void Draw6FacedConvexZ(Vector3* vertices, Color color, float alpha)
        {
            Color c = color;
            c.A = (byte)(alpha * 255);

            DrawQuadClockWise(vertices[0], vertices[1], vertices[2], vertices[3], c);
            DrawQuadClockWise(vertices[4], vertices[5], vertices[6], vertices[7], c);

            /* top left bottom right */
            DrawQuadClockWise(vertices[0], vertices[1], vertices[5], vertices[4], c);
            DrawQuadClockWise(vertices[0], vertices[3], vertices[7], vertices[4], c);
            DrawQuadClockWise(vertices[3], vertices[2], vertices[6], vertices[7], c);
            DrawQuadClockWise(vertices[2], vertices[1], vertices[5], vertices[6], c);
        }
        internal static void DrawSunGlare()
        {
            if (MyEnvironment.DirectionalLightDir == Vector3.Zero)
                return;
            if (MyEnvironment.SunMaterial == null)
                return;


            //// this should be computed every time the sector is changed. If it is not initialized, calculate now:
            //m_distanceToSun = MyRender.Sun.DistanceToSun;

            //m_directionToSunNormalized = -MyRender.Sun.Direction;

            //float radius = MyRender.Sun.SunSizeMultiplier * MySunConstants.SUN_SIZE_MULTIPLIER * MySunConstants.RENDER_SUN_DISTANCE / m_distanceToSun;
            ////radius = Math.Max(MySunConstants.MIN_SUN_SIZE * MyRender.Sun.SunSizeMultiplier, radius);
            ////radius = Math.Min(MySunConstants.MAX_SUN_SIZE * MyRender.Sun.SunSizeMultiplier, radius);

            //float sunColorMultiplier = 3;

            //sunColorMultiplier *= (1 - MyRender.FogProperties.FogMultiplier * 0.7f);

            //m_querySize = .5f * radius;

            //var sunPosition = GetSunPosition();
            //radius *= .5f;
            //Color color = new Color(.95f * sunColorMultiplier, .65f * sunColorMultiplier, .35f * sunColorMultiplier, 1);

            //color = color * 5;

            //MyTransparentGeometry.AddPointBillboard(MyRender.Sun.SunMaterial, color, sunPosition, radius, 0);

            var distanceToSun = MyEnvironment.SunDistance;

            var directionToSunNormalized = -MyEnvironment.DirectionalLightDir;

            float radius = MyEnvironment.SunSizeMultiplier * RENDER_SUN_DISTANCE / distanceToSun;

            float sunColorMultiplier = 3;
            sunColorMultiplier *= (1 - MyEnvironment.FogSettings.FogMultiplier * 0.7f);

            var sunPosition = MyEnvironment.CameraPosition + directionToSunNormalized * RENDER_SUN_DISTANCE;
            radius *= .5f;
            Color color = new Color(.95f * sunColorMultiplier, .65f * sunColorMultiplier, .35f * sunColorMultiplier, 1);

            color = color * 5;

            if (MyEnvironment.SunBillboardEnabled)
                MyBillboardsHelper.AddPointBillboard(MyEnvironment.SunMaterial, color, sunPosition, radius, 0);
        }
 internal static void DrawQuad(Vector3 v0, Vector3 v1, Vector3 v2, Vector3 v3, Color color)
 {
     DrawTriangle(v0, v1, v2, color);
     DrawTriangle(v0, v2, v3, color);
 }
        internal static void DrawFrustum(BoundingFrustum frustum, Color color, float alpha)
        {
            var corners = frustum.GetCorners();

            Draw6FacedConvex(corners, color, alpha);
        }
Example #15
0
 public static void DrawSpriteBatchRotate(string texture, Vector2 normalizedCoord, float scale, Color color, MyGuiDrawAlignEnum drawAlign, float rotation, Vector2 originNormalized, float rotationSpeed, bool waitTillLoaded = true)
 {
     VRageRender.MyRenderProxy.DrawSprite(texture, normalizedCoord, Vector2.One, color, drawAlign, rotation, Vector2.UnitX, scale, originNormalized, rotationSpeed, waitTillLoaded);
 }
Example #16
0
        static void DrawSprite(string texture, Rectangle destinationRectangle, Rectangle?sourceRectangle, Color color, float rotation, Vector2 origin, SpriteEffects effects, float layerDepth, bool waitTillLoaded = true)
        {
            var destination = new RectangleF(destinationRectangle.X, destinationRectangle.Y, destinationRectangle.Width, destinationRectangle.Height);

            DrawSprite(texture, ref destination, false, ref sourceRectangle, color, rotation, ref origin, effects, layerDepth, waitTillLoaded);
        }
Example #17
0
 /// <summary>
 ///  Draws sprite batch at specified position
 ///  normalizedPosition -> X and Y are within interval <0..1>
 ///  size -> size of destination rectangle (normalized). Don't forget that it may be distorted by aspect ration, so rectangle size [1,1] can make larger wide than height on your screen.
 ///  rotation -> angle in radians. Rotation is always around "origin" coordinate
 ///  originNormalized -> the origin of the sprite. Specify (0,0) for the upper-left corner.
 ///  RETURN: Method returns rectangle where was sprite/texture drawn in normalized coordinates
 /// </summary>
 /// <returns></returns>
 public static void DrawSpriteBatch(string texture, Vector2 normalizedCoord, Vector2 normalizedSize, Color color, MyGuiDrawAlignEnum drawAlign, float rotation, bool waitTillLoaded = true)
 {
     VRageRender.MyRenderProxy.DrawSprite(texture, normalizedCoord, normalizedSize, color, drawAlign, rotation, Vector2.UnitX, 1, null, waitTillLoaded: waitTillLoaded);
 }
Example #18
0
        // different rounding of coords
        public static void DrawSpriteBatchRoundUp(string texture, Vector2 normalizedCoord, Vector2 normalizedSize, Color color, MyGuiDrawAlignEnum drawAlign, bool waitTillLoaded = true)
        {
            if (string.IsNullOrEmpty(texture))
            {
                return;
            }

            Vector2 screenCoord = GetScreenCoordinateFromNormalizedCoordinate(normalizedCoord);
            Vector2 screenSize  = GetScreenSizeFromNormalizedSize(normalizedSize);

            screenCoord = MyUtils.GetCoordAligned(screenCoord, screenSize, drawAlign);

            DrawSprite(texture, new Rectangle((int)Math.Floor(screenCoord.X), (int)Math.Floor(screenCoord.Y), (int)Math.Ceiling(screenSize.X), (int)Math.Ceiling(screenSize.Y)), color, waitTillLoaded);
        }
Example #19
0
        /// <summary>Draws sprite batch at specified position</summary>
        /// <param name="normalizedCoord">X and Y are within interval [0,1]</param>
        /// <param name="normalizedSize">size of destination rectangle (normalized).
        /// Don't forget that it may be distorted by aspect ration, so rectangle size
        /// [1,1] can make larger wide than height on your screen.</param>
        /// <param name="useFullClientArea">True uses full client rectangle. False limits to GUI rectangle</param>
        public static void DrawSpriteBatch(string texture, Vector2 normalizedCoord, Vector2 normalizedSize, Color color, MyGuiDrawAlignEnum drawAlign, bool useFullClientArea = false, bool waitTillLoaded = true)
        {
            if (string.IsNullOrEmpty(texture))
            {
                return;
            }

            Vector2 screenCoord = GetScreenCoordinateFromNormalizedCoordinate(normalizedCoord, useFullClientArea);
            Vector2 screenSize  = GetScreenSizeFromNormalizedSize(normalizedSize, useFullClientArea);

            screenCoord = MyUtils.GetCoordAligned(screenCoord, screenSize, drawAlign);

            var rect = new Rectangle((int)screenCoord.X, (int)screenCoord.Y, (int)screenSize.X, (int)screenSize.Y);

            DrawSprite(texture, rect, color, waitTillLoaded);
        }
        public static void DrawSpriteAtlas(string texture, Vector2 position, Vector2 textureOffset, Vector2 textureSize, Vector2 rightVector, Vector2 scale, Color color, Vector2 halfSize)
        {
            Debug.Assert(!string.IsNullOrEmpty(texture) && (texture.EndsWith(".dds") || texture.EndsWith(".png")));

            var message = MessagePool.Get<MyRenderMessageDrawSpriteAtlas>(MyRenderMessageEnum.DrawSpriteAtlas);

            message.Texture = texture;
            message.Position = position;
            message.TextureOffset = textureOffset;
            message.TextureSize = textureSize;
            message.RightVector = rightVector;
            message.Scale = scale;
            message.Color = color;
            message.HalfSize = halfSize;

            EnqueueMessage(message);
        }
Example #21
0
        //  Draws sprite batch at specified NORMALIZED position, with NORMALIZED width, but SCREEN-PIXEL height.
        //  Use if you want to draw rectangle where height is in screen coords, but rest is in normalized coord (e.g. slider long line)
        public static void DrawSpriteBatch(string texture, Vector2 normalizedCoord, float normalizedWidth, int screenHeight, Color color, MyGuiDrawAlignEnum drawAlign, bool waitTillLoaded = true)
        {
            if (string.IsNullOrEmpty(texture))
            {
                return;
            }

            Vector2 screenCoord = GetScreenCoordinateFromNormalizedCoordinate(normalizedCoord);
            Vector2 screenSize  = GetScreenSizeFromNormalizedSize(new Vector2(normalizedWidth, 0));

            screenSize.Y = screenHeight; //  Replace with desired value
            screenCoord  = MyUtils.GetCoordAligned(screenCoord, screenSize, drawAlign);

            DrawSprite(texture, new Rectangle((int)screenCoord.X, (int)screenCoord.Y, (int)screenSize.X, (int)screenSize.Y), color, waitTillLoaded);
        }
Example #22
0
        public static Vector3 ToHsvColor(this VRageMath.Color color)
        {
            var hsvColor = color.ColorToHSV();

            return(new Vector3(hsvColor.X, hsvColor.Y * 2f - 1f, hsvColor.Z * 2f - 1f));
        }
        // Assuming natural order (+Y) first
        internal static unsafe void Draw6FacedConvex(Vector3D* vertices, Color color, float alpha)
        {
            Color cc = color;
            cc.A = (byte)(alpha * 255);

            Vector3D c = MyRender11.Environment.CameraPosition;
            Vector3D v0 = vertices[0] - c, v1 = vertices[1] - c, v2 = vertices[2] - c, v3 = vertices[3] - c, v4 = vertices[4] - c, v5 = vertices[5] - c, v6 = vertices[6] - c, v7 = vertices[7] - c;

            DrawQuadRowWise(v0, v1, v2, v3, cc);
            DrawQuadRowWise(v4, v5, v6, v7, cc);

            DrawQuadRowWise(v0, v1, v4, v5, cc);
            DrawQuadRowWise(v0, v2, v4, v6, cc);
            DrawQuadRowWise(v2, v3, v6, v7, cc);
            DrawQuadRowWise(v3, v1, v7, v5, cc);
        }
Example #24
0
        public void ClearBackbuffer(VRageMath.Color clearColor)
        {
            var v3 = clearColor.ToVector3();

            MyRender.Device.Clear(ClearFlags.Target, new ColorBGRA(v3.X, v3.Y, v3.Z, 1), 1, 0);
        }
 internal static void DrawQuadRowWise(Vector3 v0, Vector3 v1, Vector3 v2, Vector3 v3, Color color)
 {
     DrawTriangle(v0, v1, v2, color);
     DrawTriangle(v1, v3, v2, color);
 }
Example #26
0
        /// <summary>
        /// Draws fog (eg. background for notifications) at specified position in normalized GUI coordinates.
        /// </summary>
        private static void DrawFogInternal(string texture, ref Vector2 centerPosition, ref Vector2 size, float fogAlphaMultiplier, MyGuiDrawAlignEnum alignment)
        {
            Color color = new Color(0, 0, 0, (byte)(255 * 0.85f * fogAlphaMultiplier));

            MyGuiManager.DrawSpriteBatch(texture, centerPosition, size, color, alignment, MyVideoSettingsManager.IsTripleHead());
        }
        //  Add billboard for one frame only. This billboard isn't particle (it doesn't survive this frame, doesn't have update/draw methods, etc).
        //  This billboard isn't facing the camera. It's always oriented in specified direction. May be used as thrusts, or inner light of reflector.
        //  It's used by other classes when they want to draw some billboard (e.g. rocket thrusts, reflector glare).
        public static void AddBillboardOriented(string material,
            Color color, Vector3D origin, Vector3 leftVector, Vector3 upVector, float radius, int priority = 0, bool colorize = false, int customViewProjection = -1)
        {
            Debug.Assert(material != null);

            if (!IsEnabled) return;

            origin.AssertIsValid();
            leftVector.AssertIsValid();
            upVector.AssertIsValid();
            radius.AssertIsValid();
            MyDebug.AssertDebug(radius > 0);


            MyBillboard billboard = m_billboardOncePool.Allocate();
            if (billboard == null)
                return;

            billboard.Priority = priority;
            billboard.CustomViewProjection = customViewProjection;

            MyQuadD quad;
            MyUtils.GetBillboardQuadOriented(out quad, ref origin, radius, ref leftVector, ref upVector);

            CreateBillboard(billboard, ref quad, material, ref color, ref origin, colorize);

            m_billboardsOnce.Add(billboard);
        }
        internal void Draw(Rectangle rect, Color color, MyVideoRectangleFitMode fitMode)
        {
            int w = 0, h = 0;

            byte [] data = m_wrapper.GetTextureData(ref w, ref h);
            process_frame(data, w, h);

            Rectangle dst         = rect;
            Rectangle src         = new Rectangle(0, 0, w, h);
            var       videoSize   = new Vector2(w, h);
            float     videoAspect = videoSize.X / videoSize.Y;
            float     rectAspect  = (float)rect.Width / (float)rect.Height;

            // Automatic decision based on ratios.
            if (fitMode == MyVideoRectangleFitMode.AutoFit)
            {
                fitMode = (videoAspect > rectAspect) ? MyVideoRectangleFitMode.FitHeight : MyVideoRectangleFitMode.FitWidth;
            }

            float scaleRatio = 0.0f;

            switch (fitMode)
            {
            case MyVideoRectangleFitMode.None:
                break;

            case MyVideoRectangleFitMode.FitWidth:
                scaleRatio = (float)dst.Width / videoSize.X;
                dst.Height = (int)(scaleRatio * videoSize.Y);
                if (dst.Height > rect.Height)
                {
                    var diff = dst.Height - rect.Height;
                    dst.Height  = rect.Height;
                    diff        = (int)(diff / scaleRatio);
                    src.Y      += (int)(diff * 0.5f);
                    src.Height -= diff;
                }
                break;

            case MyVideoRectangleFitMode.FitHeight:
                scaleRatio = (float)dst.Height / videoSize.Y;
                dst.Width  = (int)(scaleRatio * videoSize.X);
                if (dst.Width > rect.Width)
                {
                    var diff = dst.Width - rect.Width;
                    dst.Width  = rect.Width;
                    diff       = (int)(diff / scaleRatio);
                    src.X     += (int)(diff * 0.5f);
                    src.Width -= diff;
                }
                break;
            }
            dst.X = rect.Left + (rect.Width - dst.Width) / 2;
            dst.Y = rect.Top + (rect.Height - dst.Height) / 2;


            VRageMath.RectangleF destination = new VRageMath.RectangleF(dst.X, dst.Y, dst.Width, -dst.Height);
            VRageMath.Rectangle? source      = src;
            Vector2 origin = new Vector2(src.Width / 2 * 0, src.Height);

            MySpritesRenderer.AddSingleSprite(m_texture, videoSize, color, origin, Vector2.UnitX, source, destination);
        }
        //  This method is like a constructor (which we can't use because billboards are allocated from a pool).
        //  It starts/initializes a billboard. Refs used only for optimalization
        public static void CreateBillboard(VRageRender.MyBillboard billboard, ref MyQuadD quad, string material, string blendMaterial, float textureBlendRatio,
            ref Color color, ref Vector3D origin, Vector2 uvOffset, bool colorize = false, bool near = false, bool lowres = false, float reflectivity = 0)
        {
            Debug.Assert(material != null);
            
            if (string.IsNullOrEmpty(material) || !MyTransparentMaterials.ContainsMaterial(material))
            {
                material = "ErrorMaterial";
                color = Vector4.One;
            }

            billboard.Material = material;
            billboard.BlendMaterial = blendMaterial;
            billboard.BlendTextureRatio = textureBlendRatio;

            quad.Point0.AssertIsValid();
            quad.Point1.AssertIsValid();
            quad.Point2.AssertIsValid();
            quad.Point3.AssertIsValid();


            //  Billboard vertexes
            billboard.Position0 = quad.Point0;
            billboard.Position1 = quad.Point1;
            billboard.Position2 = quad.Point2;
            billboard.Position3 = quad.Point3;

            billboard.UVOffset = uvOffset;

            EnableColorize = colorize;

            if (EnableColorize)
                billboard.Size = (float)(billboard.Position0 - billboard.Position2).Length();

            //  Distance for sorting
            //  IMPORTANT: Must be calculated before we do color and alpha misting, because we need distance there
            billboard.DistanceSquared = (float)Vector3D.DistanceSquared(MyRenderCamera.Position, origin);

            //  Color
            billboard.Color = color;
            billboard.ColorIntensity = 1;
            billboard.Reflectivity = reflectivity;

            billboard.Near = near;
            billboard.Lowres = lowres;
            billboard.ParentID = -1;

            //  Alpha depends on distance to camera. Very close bilboards are more transparent, so player won't see billboard errors or rotating billboards
            var mat = MyTransparentMaterials.GetMaterial(billboard.Material);
            if (mat.AlphaMistingEnable)
                billboard.Color *= MathHelper.Clamp(((float)Math.Sqrt(billboard.DistanceSquared) - mat.AlphaMistingStart) / (mat.AlphaMistingEnd - mat.AlphaMistingStart), 0, 1);

            billboard.Color *= mat.Color;

            billboard.ContainedBillboards.Clear();
        }
 internal MyVertexFormatPositionPackedColor(Vector3 position, Color color)
 {
     Position = new HalfVector4(position.X, position.Y, position.Z, 1);
     Color    = new Byte4(color.PackedValue);
 }
        /// <summary>
        /// Draw a sprite into rectangle specified in screen coordinates (pixels).
        /// </summary>
        /// <param name="texture">Sprite texture as path.</param>
        /// <param name="rectangle">Rectangle in screen coordinates (pixels).</param>
        /// <param name="color">Masking color.</param>
        public static void DrawSprite(string texture, Rectangle rectangle, Color color, bool waitTillLoaded = true)
        {
            var destination = new RectangleF(rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height);

            DrawSprite(texture, ref destination, false, ref nullRectangle, color, 0f, ref vector2Zero, VRageRender.Graphics.SpriteEffects.None, 0f, waitTillLoaded);
        }
 internal MyVertexFormatPositionColor(Vector3 position, Color color)
 {
     Position = position;
     Color    = new Byte4(color.PackedValue);
 }
Example #33
0
        static void DrawSprite(string texture, Vector2 position, Rectangle?sourceRectangle, Color color, float rotation, Vector2 origin, float scale, SpriteEffects effects, float layerDepth, bool waitTillLoaded = true)
        {
            var destination = new RectangleF(position.X, position.Y, scale, scale);

            DrawSprite(texture, ref destination, true, ref sourceRectangle, color, rotation, ref origin, effects, layerDepth, waitTillLoaded);
        }
        public static uint CreateRenderEntity(
            string debugName,
            string model,
            MatrixD worldMatrix,
            MyMeshDrawTechnique technique,
            RenderFlags flags,
            CullingOptions cullingOptions,
            Color diffuseColor,
            Vector3 colorMaskHsv,
            float dithering = 0,
            float maxViewDistance = float.MaxValue,
            byte depthBias = 0
            )
        {
            var message = MessagePool.Get<MyRenderMessageCreateRenderEntity>(MyRenderMessageEnum.CreateRenderEntity);

            uint id = GetMessageId();
            message.ID = id;
            message.DebugName = debugName;
            message.Model = model;
            message.WorldMatrix = worldMatrix;
            message.Technique = technique;
            message.Flags = flags;
            message.CullingOptions = cullingOptions;
            message.MaxViewDistance = maxViewDistance;
            message.DepthBias = depthBias;

            EnqueueMessage(message);

            UpdateRenderEntity(id, diffuseColor, colorMaskHsv, dithering);

            return id;
        }
        private void DrawNetgraphLineBar(int positionX, ref int positionY, long value, float sizeMultiplier, Color colorLine, Color colorTop)
        {
            float offset = value * sizeMultiplier;
            int offsetI = (int)Math.Ceiling(offset);

            VRageRender.MyRenderProxy.DebugDrawLine2D(
                new Vector2(positionX, positionY),
                new Vector2(positionX, positionY - offsetI),
                colorLine,
                colorLine);

            // small dots above each bar
            //if (offsetI > 0)
            //{
            //MyGuiManager.DrawSpriteBatch(MyGuiConstants.NETGRAPH_BG_TEXTURE.Texture,
            //    positionX,
            //    (positionY - offsetI - 1),
            //    1,
            //    1,
            //    top);

            //VRageRender.MyRenderProxy.DebugDrawLine2D(
            //    new Vector2(positionX, positionY - offsetI),
            //    new Vector2(positionX, positionY - offsetI - 1),
            //    colorTop,
            //    colorTop);
            //}
            positionY -= (offsetI);
        }
        private void DrawGravityVectorIndicator(Vector2 centerPos, Vector3 worldGravity, MyHudTexturesEnum texture, Color color)
        {
            float hudSizeX = MyGuiManager.GetSafeFullscreenRectangle().Width / MyGuiManager.GetHudSize().X;
            float hudSizeY = MyGuiManager.GetSafeFullscreenRectangle().Height / MyGuiManager.GetHudSize().Y;

            var textureCoord = GetTextureCoord(texture);
            var viewGravity = Vector3.TransformNormal(worldGravity, MySector.MainCamera.ViewMatrix);
            var viewGravityLen = viewGravity.Length();
            if (!MyUtils.IsZero(viewGravityLen))
                viewGravity /= viewGravityLen;

            var right = new Vector2(viewGravity.Y, viewGravity.X);
            var rightLen = right.Length();

            if (!MyUtils.IsZero(rightLen))
                right /= rightLen;

            var scale = Vector2.One * new Vector2(0.003f, 0.013f);
            scale.Y *= rightLen;

            VRageRender.MyRenderProxy.DrawSpriteAtlas(
                m_atlas,
                centerPos + new Vector2(viewGravity.X, -viewGravity.Y) * 0.02f,
                textureCoord.Offset,
                textureCoord.Size,
                right,
                new Vector2(hudSizeX, hudSizeY),
                color,
                scale);
        }
        public static void DrawString(
            int fontIndex,
            Vector2 screenCoord,
            Color colorMask,
            StringBuilder text,
            float screenScale,
            float screenMaxWidth)
        {
            var message = MessagePool.Get<MyRenderMessageDrawString>(MyRenderMessageEnum.DrawString);
            message.Text.Clear().AppendStringBuilder(text);
            message.FontIndex = fontIndex;
            message.ScreenCoord = screenCoord;
            message.ColorMask = colorMask;
            message.ScreenScale = screenScale;
            message.ScreenMaxWidth = screenMaxWidth;

            EnqueueMessage(message);
        }
Example #38
0
 static void DrawSprite(string texture, ref RectangleF destination, bool scaleDestination, ref Rectangle?sourceRectangle, Color color, float rotation, ref Vector2 origin, SpriteEffects effects, float depth, bool waitTillLoaded = true)
 {
     VRageRender.MyRenderProxy.DrawSprite(texture, ref destination, scaleDestination, ref sourceRectangle, color, rotation, Vector2.UnitX, ref origin, effects, depth, waitTillLoaded);
 }
        public static void UpdateRenderEntity(
            uint id,
            Color? diffuseColor,
            Vector3? colorMaskHsv,
            float dithering = 0
         )
        {
            var message = MessagePool.Get<MyRenderMessageUpdateRenderEntity>(MyRenderMessageEnum.UpdateRenderEntity);

            message.ID = id;
            message.DiffuseColor = diffuseColor;
            message.ColorMaskHSV = colorMaskHsv;
            message.Dithering = dithering;

            EnqueueMessage(message);
        }
        private void DrawGravityVectorIndicator(Vector2 centerPos, Vector3 worldGravity, MyHudTexturesEnum texture, Color color)
        {
            float hudSizeX = MyGuiManager.GetSafeFullscreenRectangle().Width / MyGuiManager.GetHudSize().X;
            float hudSizeY = MyGuiManager.GetSafeFullscreenRectangle().Height / MyGuiManager.GetHudSize().Y;

            var textureCoord   = GetTextureCoord(texture);
            var viewGravity    = Vector3.TransformNormal(worldGravity, MySector.MainCamera.ViewMatrix);
            var viewGravityLen = viewGravity.Length();

            if (!MyUtils.IsZero(viewGravityLen))
            {
                viewGravity /= viewGravityLen;
            }

            var right    = new Vector2(viewGravity.Y, viewGravity.X);
            var rightLen = right.Length();

            if (!MyUtils.IsZero(rightLen))
            {
                right /= rightLen;
            }

            var scale = Vector2.One * new Vector2(0.003f, 0.013f);

            scale.Y *= rightLen;

            VRageRender.MyRenderProxy.DrawSpriteAtlas(
                m_atlas,
                centerPos + new Vector2(viewGravity.X, -viewGravity.Y) * 0.02f,
                textureCoord.Offset,
                textureCoord.Size,
                right,
                new Vector2(hudSizeX, hudSizeY),
                color,
                scale);
        }
 private void DrawNetgraphAverageLine(ref Vector2 position, float average1, float average2, float sizeMultiplier, Color color)
 {
     if (average1 != 0 || average2 != 0)
     {
         Vector2 pointFrom = new Vector2(position.X - 1, position.Y - average1 * sizeMultiplier);
         Vector2 pointTo = new Vector2(position.X, position.Y - average2 * sizeMultiplier);
         VRageRender.MyRenderProxy.DebugDrawLine2D(pointFrom, pointTo, color, color);
     }
 }
        private void DrawNetgraph(MyHudNetgraph netgraph)
        {
            Vector2 bgPos      = MyGuiConstants.NETGRAPH_INITIAL_POSITION;
            var     texture    = MyGuiConstants.NETGRAPH_BG_TEXTURE;
            Vector2 normBgPos  = ConvertHudToNormalizedGuiPosition(ref bgPos);
            Vector2 normSizeBg = MyGuiManager.GetNormalizedSizeFromScreenSize(texture.SizePx);

            normSizeBg.Y = MyGuiConstants.NETGRAPH_BG_NORM_SIZE_Y;


            Vector2 screenOptimalBarSize           = MyGuiManager.GetScreenSizeFromNormalizedSize(MyHudNetgraph.OPTIMAL_LENGTH_BAR_NORMALIZED);
            Vector2 screenOptimalBarSizeMulitplier = screenOptimalBarSize * netgraph.CurrentPacketScaleInvertedMaximumValue;
            float   averageGraphSizeMultiplier     = screenOptimalBarSize.Y * netgraph.CurrentAverageScaleInvertedMaximumValue;
            Vector2 scalePosition = normBgPos;

            scalePosition.X -= normSizeBg.X - 0.035f;
            scalePosition.Y -= normSizeBg.Y * (0.09f / MyGuiConstants.NETGRAPH_BG_NORM_SIZE_Y);

            ProfilerShort.Begin("Draw scales");
            // draw left scale (packet size)
            float         maximumValue = netgraph.CurrentPacketScaleMaximumValue;
            StringBuilder unitForScale = new StringBuilder();

            netgraph.GetProperFormatAndValueForBytes(netgraph.CurrentPacketScaleMaximumValue, out maximumValue, unitForScale);
            DrawNetgraphScaleForPacketScale(scalePosition, (int)screenOptimalBarSize.Y,
                                            maximumValue, 5, unitForScale, true, true, 0.7f, MyFontEnum.White);

            // draw right scale (average)
            Vector2 averageScalePosition = scalePosition;

            averageScalePosition.X += (normSizeBg.X - 0.06f);
            unitForScale.Clear();
            netgraph.GetProperFormatAndValueForBytes(netgraph.CurrentAverageScaleMaximumValue, out maximumValue, unitForScale, true);
            DrawNetgraphScaleForPacketScale(averageScalePosition, (int)screenOptimalBarSize.Y,
                                            maximumValue, 5, unitForScale, false, false, 0.7f, MyFontEnum.Red);

            ProfilerShort.End();

            Vector2 lineNormalizedPosition = scalePosition;

            lineNormalizedPosition.X += 0.014f;
            Vector2 linePosition       = MyGuiManager.GetScreenCoordinateFromNormalizedCoordinate(lineNormalizedPosition);
            Vector2 cachedLinePosition = linePosition;

            ProfilerShort.Begin("Draw netgraph bars");
            // draw netgraph bars
            for (int i = netgraph.CurrentFirstIndex; i < MyHudNetgraph.NUMBER_OF_VISIBLE_PACKETS; i++)
            {
                DrawNetgraphLine(netgraph.GetNetgraphLineDataAtIndex(i), ref linePosition, ref screenOptimalBarSizeMulitplier);
                linePosition.X++;
            }
            for (int i = 0; i < netgraph.CurrentFirstIndex; i++)
            {
                DrawNetgraphLine(netgraph.GetNetgraphLineDataAtIndex(i), ref linePosition, ref screenOptimalBarSizeMulitplier);
                linePosition.X++;
            }
            ProfilerShort.End();

            ProfilerShort.Begin("Draw average line");
            // draw average line
            linePosition = cachedLinePosition;
            float averageOnFirstLine = netgraph.GetNetgraphLineDataAtIndex(netgraph.CurrentFirstIndex).AverageOnThisLine;

            linePosition.X++;
            for (int i = netgraph.CurrentFirstIndex + 1; i < MyHudNetgraph.NUMBER_OF_VISIBLE_PACKETS; i++)
            {
                float averageOnSecondLine = netgraph.GetNetgraphLineDataAtIndex(i).AverageOnThisLine;
                DrawNetgraphAverageLine(ref linePosition, averageOnFirstLine, averageOnSecondLine, averageGraphSizeMultiplier, Color.Red);
                linePosition.X++;
                averageOnFirstLine = averageOnSecondLine;
            }
            for (int i = 0; i < netgraph.CurrentFirstIndex; i++)
            {
                float averageOnSecondLine = netgraph.GetNetgraphLineDataAtIndex(i).AverageOnThisLine;
                DrawNetgraphAverageLine(ref linePosition, averageOnFirstLine, averageOnSecondLine, averageGraphSizeMultiplier, Color.Red);
                linePosition.X++;
                averageOnFirstLine = averageOnSecondLine;
            }
            ProfilerShort.End();
            // draw netgraph status data
            Vector2 textPosition = lineNormalizedPosition;

            textPosition.X  = scalePosition.X - 0.02f;
            textPosition.Y += normSizeBg.Y * (0.012f / MyGuiConstants.NETGRAPH_BG_NORM_SIZE_Y); // 0.012f;
            DrawNetgraphBasicStrings(netgraph, textPosition, new Vector2(0.06f, 0.02f));

            // draw bars legend
            textPosition    = scalePosition;
            textPosition.X -= 0.022f;
            textPosition.Y -= 0.2f;
            m_helperSB.Clear().Append("Reliable");
            Color tmp = MyGuiConstants.NETGRAPH_RELIABLE_PACKET_COLOR;

            tmp.A = 255;
            MyGuiManager.DrawString(MyFontEnum.White, m_helperSB, textPosition, 0.7f, tmp, MyGuiDrawAlignEnum.HORISONTAL_RIGHT_AND_VERTICAL_CENTER);
            textPosition.Y += 0.02f;
            m_helperSB.Clear().Append("Unreliable");
            tmp   = MyGuiConstants.NETGRAPH_UNRELIABLE_PACKET_COLOR;
            tmp.A = 255;
            MyGuiManager.DrawString(MyFontEnum.White, m_helperSB, textPosition, 0.7f, tmp, MyGuiDrawAlignEnum.HORISONTAL_RIGHT_AND_VERTICAL_CENTER);
            textPosition.Y += 0.02f;
            m_helperSB.Clear().Append("Sent");
            tmp   = MyGuiConstants.NETGRAPH_SENT_PACKET_COLOR;
            tmp.A = 255;
            MyGuiManager.DrawString(MyFontEnum.White, m_helperSB, textPosition, 0.7f, tmp, MyGuiDrawAlignEnum.HORISONTAL_RIGHT_AND_VERTICAL_CENTER);
        }
Example #43
0
        static void DrawVideo(uint id, Rectangle rect, Color color, MyVideoRectangleFitMode fitMode)
        {
            MyVideoPlayerDx9 video;
            if (m_videos.TryGetValue(id, out video))
            {
                Rectangle dst = rect;
                Rectangle src = new Rectangle(0, 0, video.VideoWidth, video.VideoHeight);
                var videoSize = new Vector2(video.VideoWidth, video.VideoHeight);
                float videoAspect = videoSize.X / videoSize.Y;
                float rectAspect = (float)rect.Width / (float)rect.Height;

                // Automatic decision based on ratios.
                if (fitMode == MyVideoRectangleFitMode.AutoFit)
                    fitMode = (videoAspect > rectAspect) ? MyVideoRectangleFitMode.FitHeight : MyVideoRectangleFitMode.FitWidth;

                float scaleRatio = 0.0f;
                switch (fitMode)
                {
                    case MyVideoRectangleFitMode.None:
                        break;

                    case MyVideoRectangleFitMode.FitWidth:
                        scaleRatio = (float)dst.Width / videoSize.X;
                        dst.Height = (int)(scaleRatio * videoSize.Y);
                        if (dst.Height > rect.Height)
                        {
                            var diff = dst.Height - rect.Height;
                            dst.Height = rect.Height;
                            diff = (int)(diff / scaleRatio);
                            src.Y += (int)(diff * 0.5f);
                            src.Height -= diff;
                        }
                        break;

                    case MyVideoRectangleFitMode.FitHeight:
                        scaleRatio = (float)dst.Height / videoSize.Y;
                        dst.Width = (int)(scaleRatio * videoSize.X);
                        if (dst.Width > rect.Width)
                        {
                            var diff = dst.Width - rect.Width;
                            dst.Width = rect.Width;
                            diff = (int)(diff / scaleRatio);
                            src.X += (int)(diff * 0.5f);
                            src.Width -= diff;
                        }
                        break;
                }
                dst.X = rect.Left + (rect.Width - dst.Width) / 2;
                dst.Y = rect.Top + (rect.Height - dst.Height) / 2;

                Texture texture = video.OutputFrame;

                // Draw upside down
                VRageMath.RectangleF destination = new VRageMath.RectangleF(dst.X, dst.Y, dst.Width, -dst.Height);
                VRageMath.Rectangle? source = src;
                Vector2 origin = new Vector2(src.Width / 2 * 0, src.Height);
                MyRender.DrawSprite(texture, null, ref destination, false, ref source, color, Vector2.UnitX, ref origin, VRageRender.Graphics.SpriteEffects.None, 0f);
            }
        }
        private void DrawNetgraphLineBar(int positionX, ref int positionY, long value, float sizeMultiplier, Color colorLine, Color colorTop)
        {
            float offset  = value * sizeMultiplier;
            int   offsetI = (int)Math.Ceiling(offset);

            VRageRender.MyRenderProxy.DebugDrawLine2D(
                new Vector2(positionX, positionY),
                new Vector2(positionX, positionY - offsetI),
                colorLine,
                colorLine);

            // small dots above each bar
            //if (offsetI > 0)
            //{
            //MyGuiManager.DrawSpriteBatch(MyGuiConstants.NETGRAPH_BG_TEXTURE.Texture,
            //    positionX,
            //    (positionY - offsetI - 1),
            //    1,
            //    1,
            //    top);

            //VRageRender.MyRenderProxy.DebugDrawLine2D(
            //    new Vector2(positionX, positionY - offsetI),
            //    new Vector2(positionX, positionY - offsetI - 1),
            //    colorTop,
            //    colorTop);
            //}
            positionY -= (offsetI);
        }
        /// <summary>
        /// Draws fog (eg. background for notifications) at specified position in normalized GUI coordinates.
        /// </summary>
        public static void DrawFog(ref Vector2 centerPosition, ref Vector2 textSize)
        {
            Color color = new Color(0, 0, 0, (byte)(255 * 0.85f));
            Vector2 fogFadeSize = textSize * new Vector2(1.4f, 3.0f);

            MyGuiManager.DrawSpriteBatch(MyGuiConstants.FOG_SMALL, centerPosition, fogFadeSize, color,
                MyGuiDrawAlignEnum.HORISONTAL_CENTER_AND_VERTICAL_CENTER, MyVideoSettingsManager.IsTripleHead());
        }
 private void DrawNetgraphAverageLine(ref Vector2 position, float average1, float average2, float sizeMultiplier, Color color)
 {
     if (average1 != 0 || average2 != 0)
     {
         Vector2 pointFrom = new Vector2(position.X - 1, position.Y - average1 * sizeMultiplier);
         Vector2 pointTo   = new Vector2(position.X, position.Y - average2 * sizeMultiplier);
         VRageRender.MyRenderProxy.DebugDrawLine2D(pointFrom, pointTo, color, color);
     }
 }
        internal static unsafe void Draw6FacedConvexZ(Vector3[] vertices, Color color, float alpha)
        {
            Debug.Assert(vertices.Length == 8);

            fixed(Vector3* verticesPtr = vertices)
            {
                Draw6FacedConvexZ(verticesPtr, color, alpha);
            }
        }
Example #48
0
        internal static void CreateBillboard(VRageRender.MyBillboard billboard, ref MyQuadD quad, string material, ref Color color, ref Vector3D origin,
                                             float softParticleDistanceScale = 1.0f, string blendMaterial = "Test", float textureBlendRatio = 0, Vector2 uvOffset = new Vector2(),
                                             bool near = false, bool lowres = false, float reflectivity = 0)
        {
            Debug.Assert(material != null);
            Debug.Assert(blendMaterial != null);

            if (string.IsNullOrEmpty(material) || !MyTransparentMaterials.ContainsMaterial(material))
            {
                material = "ErrorMaterial";
                color    = Vector4.One;
            }

            billboard.Material          = material;
            billboard.BlendMaterial     = blendMaterial;
            billboard.BlendTextureRatio = textureBlendRatio;

            quad.Point0.AssertIsValid();
            quad.Point1.AssertIsValid();
            quad.Point2.AssertIsValid();
            quad.Point3.AssertIsValid();


            //  Billboard vertexes
            billboard.Position0 = quad.Point0;
            billboard.Position1 = quad.Point1;
            billboard.Position2 = quad.Point2;
            billboard.Position3 = quad.Point3;

            billboard.UVOffset = uvOffset;
            billboard.UVSize   = Vector2.One;

            //  Distance for sorting
            //  IMPORTANT: Must be calculated before we do color and alpha misting, because we need distance there
            billboard.DistanceSquared = (float)Vector3D.DistanceSquared(MyRender11.Environment.Matrices.CameraPosition, origin);

            //  Color
            billboard.Color          = color;
            billboard.Reflectivity   = reflectivity;
            billboard.ColorIntensity = 1;

            billboard.Near     = near;
            billboard.Lowres   = lowres;
            billboard.ParentID = -1;

            //  Alpha depends on distance to camera. Very close bilboards are more transparent, so player won't see billboard errors or rotating billboards
            var mat = MyTransparentMaterials.GetMaterial(billboard.Material);

            if (mat.AlphaMistingEnable)
            {
                billboard.Color *= MathHelper.Clamp(((float)Math.Sqrt(billboard.DistanceSquared) - mat.AlphaMistingStart) / (mat.AlphaMistingEnd - mat.AlphaMistingStart), 0, 1);
            }

            billboard.Color *= mat.Color;
            billboard.SoftParticleDistanceScale = softParticleDistanceScale;

            billboard.ContainedBillboards.Clear();
        }
        internal static void DrawFrustum(BoundingFrustum frustum, Color color, float alpha)
        {
            var corners = frustum.GetCorners();

            Draw6FacedConvexZ(corners, color, alpha);
        }
Example #50
0
        static void DrawVideo(uint id, Rectangle rect, Color color, MyVideoRectangleFitMode fitMode)
        {
            MyVideoPlayerDx9 video;

            if (m_videos.TryGetValue(id, out video))
            {
                Rectangle dst         = rect;
                Rectangle src         = new Rectangle(0, 0, video.VideoWidth, video.VideoHeight);
                var       videoSize   = new Vector2(video.VideoWidth, video.VideoHeight);
                float     videoAspect = videoSize.X / videoSize.Y;
                float     rectAspect  = (float)rect.Width / (float)rect.Height;

                // Automatic decision based on ratios.
                if (fitMode == MyVideoRectangleFitMode.AutoFit)
                {
                    fitMode = (videoAspect > rectAspect) ? MyVideoRectangleFitMode.FitHeight : MyVideoRectangleFitMode.FitWidth;
                }

                float scaleRatio = 0.0f;
                switch (fitMode)
                {
                case MyVideoRectangleFitMode.None:
                    break;

                case MyVideoRectangleFitMode.FitWidth:
                    scaleRatio = (float)dst.Width / videoSize.X;
                    dst.Height = (int)(scaleRatio * videoSize.Y);
                    if (dst.Height > rect.Height)
                    {
                        var diff = dst.Height - rect.Height;
                        dst.Height  = rect.Height;
                        diff        = (int)(diff / scaleRatio);
                        src.Y      += (int)(diff * 0.5f);
                        src.Height -= diff;
                    }
                    break;

                case MyVideoRectangleFitMode.FitHeight:
                    scaleRatio = (float)dst.Height / videoSize.Y;
                    dst.Width  = (int)(scaleRatio * videoSize.X);
                    if (dst.Width > rect.Width)
                    {
                        var diff = dst.Width - rect.Width;
                        dst.Width  = rect.Width;
                        diff       = (int)(diff / scaleRatio);
                        src.X     += (int)(diff * 0.5f);
                        src.Width -= diff;
                    }
                    break;
                }
                dst.X = rect.Left + (rect.Width - dst.Width) / 2;
                dst.Y = rect.Top + (rect.Height - dst.Height) / 2;

                Texture texture = video.OutputFrame;

                // Draw upside down
                VRageMath.RectangleF destination = new VRageMath.RectangleF(dst.X, dst.Y, dst.Width, -dst.Height);
                VRageMath.Rectangle? source      = src;
                Vector2 origin = new Vector2(src.Width / 2 * 0, src.Height);
                MyRender.DrawSprite(texture, null, ref destination, false, ref source, color, Vector2.UnitX, ref origin, VRageRender.Graphics.SpriteEffects.None, 0f);
            }
        }
Example #51
0
 internal MyVertexFormatPositionPackedColor(Vector3 position, Color color)
 {
     Position = new HalfVector4(position.X, position.Y, position.Z, 1);
     Color = new Byte4(color.PackedValue);
 }
Example #52
0
 static void DrawVideo(uint id, Rectangle rect, Color color, MyVideoRectangleFitMode fitMode)
 {
     Debug.Assert(false);
 }
        //  Add billboard for one frame only. This billboard isn't particle (it doesn't survive this frame, doesn't have update/draw methods, etc).
        //  It's used by other classes when they want to draw some billboard (e.g. rocket thrusts, reflector glare).
        public static void AddPointBillboard(string material,
            Color color, Vector3D origin, float radius, float angle, int priority = 0, bool colorize = false, bool near = false, bool lowres = false, int customViewProjection = -1,bool cullwithStencil = false)
        {
            Debug.Assert(material != null);

            if (!IsEnabled) return;

            origin.AssertIsValid();
            angle.AssertIsValid();

            MyQuadD quad;
            if (MyUtils.GetBillboardQuadAdvancedRotated(out quad, origin, radius, angle, MyRenderCamera.Position) != false)
            {
                VRageRender.MyBillboard billboard = m_billboardOncePool.Allocate();
                if (billboard == null)
                    return;

                billboard.CullWithStencil = cullwithStencil;
                billboard.Priority = priority;
                billboard.CustomViewProjection = customViewProjection;
                CreateBillboard(billboard, ref quad, material, ref color, ref origin, colorize, near, lowres);

                // TODO: OP! Nothing should add into BillboardsRead, especially when it may be used for more than one rendering frame
                m_billboardsOnce.Add(billboard);
            }
        }
Example #54
0
 public void ClearBackbuffer(VRageMath.Color clearColor)
 {
     MyRender11.ClearBackbuffer(clearColor);
 }
        //  Add billboard for one frame only. This billboard isn't particle (it doesn't survive this frame, doesn't have update/draw methods, etc).
        //  It's used by other classes when they want to draw some billboard (e.g. rocket thrusts, reflector glare).
        public static void AddLineBillboard(string material,
            Color color, Vector3D origin, Vector3 directionNormalized, float length, float thickness, int priority = 0, bool near = false, int customViewProjection = -1)
        {
            Debug.Assert(material != null);

            if (!IsEnabled) return;

            origin.AssertIsValid();
            length.AssertIsValid();
            MyDebug.AssertDebug(length > 0);
            MyDebug.AssertDebug(thickness > 0);

            VRageRender.MyBillboard billboard = m_billboardOncePool.Allocate();
            if (billboard == null)
                return;

            billboard.Priority = priority;
            billboard.CustomViewProjection = customViewProjection;

            MyPolyLineD polyLine;
            polyLine.LineDirectionNormalized = directionNormalized;
            polyLine.Point0 = origin;
            polyLine.Point1 = origin + directionNormalized * length;
            polyLine.Thickness = thickness;

            MyQuadD quad;
            MyUtilsRender9.GetPolyLineQuad(out quad, ref polyLine);

            CreateBillboard(billboard, ref quad, material, ref color, ref origin, false, near);

            m_billboardsOnce.Add(billboard);
        }
Example #56
0
 internal void AddFrustum(BoundingFrustum bf, Color color)
 {
     Add6FacedConvex(bf.GetCorners(), color);
 }
 public static void CreateBillboard(VRageRender.MyBillboard billboard, ref MyQuadD quad, string material, string blendMaterial, float textureBlendRatio,
     ref Color color, ref Vector3D origin, bool colorize = false, bool near = false, bool lowres = false)
 {
     Debug.Assert(material != null);
     CreateBillboard(billboard, ref quad, material, blendMaterial, textureBlendRatio, ref color, ref origin, Vector2.Zero, colorize, near, lowres);
 }
Example #58
0
 internal void Add(Vector3 from, Vector3 to, Color colorFrom, Color?colorTo = null)
 {
     List.Add(new MyVertexFormatPositionColor(from, new Byte4(colorFrom.PackedValue)));
     List.Add(new MyVertexFormatPositionColor(to, colorTo.HasValue ? new Byte4(colorTo.Value.PackedValue) : new Byte4(colorFrom.PackedValue)));
 }
        static void DrawVertexBuffer(Texture depthForParticlesRT, List<MyBillboard> billboards)
        {
            //  This is important for optimalization (although I don't know when it can happen to have zero billboards), but
            //  also that loop below needs it - as it assumes we are rendering at least one billboard.
            if (billboards.Count == 0)
                return;

            Device device = MyRender.GraphicsDevice;
            Surface oldTargets = null;

            DepthStencilState previousState = null;
            if (MyRender.Settings.VisualizeOverdraw)
            {
                oldTargets = device.GetRenderTarget(0);

                //We borrow lod0normals to render stencil
                MyRender.SetRenderTarget(MyRender.GetRenderTarget(MyRenderTargets.Auxiliary0), null);
                device.Clear(ClearFlags.Target | ClearFlags.Stencil, new ColorBGRA(0), 1.0f, 0);

                previousState = MyStateObjects.StencilMask_AlwaysIncrement_DepthStencilState;
                MyStateObjects.StencilMask_AlwaysIncrement_DepthStencilState.Apply();
            }
            else
            {
                previousState = DepthStencilState.None;
                DepthStencilState.None.Apply();
            }

            //  Draw particles without culling. It's because how we calculate left/up vector, we can have problems in back camera. (yes, that can be solved, but why bother...)
            //  Also I guess that drawing without culling may be faster - as GPU doesn't have to check it
            // No it's not, correct culling is faster: http://msdn.microsoft.com/en-us/library/windows/desktop/bb204882(v=vs.85).aspx
            RasterizerState.CullNone.Apply();

            MyEffectTransparentGeometry effect = MyRender.GetEffect(MyEffects.TransparentGeometry) as MyEffectTransparentGeometry;

            effect.SetWorldMatrix(Matrix.Identity);

            Matrix viewMatrix = MyRenderCamera.ViewMatrixAtZero;
            effect.SetViewMatrix(ref viewMatrix);

            effect.SetProjectionMatrix(ref MyRenderCamera.ProjectionMatrix);

            Viewport originalViewport = MyRender.GraphicsDevice.Viewport;

            effect.SetDepthsRT(depthForParticlesRT);
            effect.SetHalfPixel(depthForParticlesRT.GetLevelDescription(0).Width, depthForParticlesRT.GetLevelDescription(0).Height);
            effect.SetScale(MyRender.GetScaleForViewport(depthForParticlesRT));

            // Later we can interpolate between Main and Aux
            effect.SetEnvironmentMap(MyRender.GetRenderTargetCube(MyRenderTargets.EnvironmentCube));

            //For struct size checks
            //int stride = MyVertexFormatTransparentGeometry.VertexDeclaration.VertexStride;
            //int s = Marshal.SizeOf(new MyVertexFormatTransparentGeometry());


            //  We iterate over all sorted billboards, and seach for when texture/shader has changed.
            //  We try to draw as many billboards as possible (using the same texture), but because we are rendering billboards
            //  sorted by depth, we still need to switch sometimes. Btw: I have observed, that most time consuming when drawing particles
            //  is device.DrawUserPrimitives(), even if I call it for the whole list of billboards (without this optimization). I think, it's
            //  because particles are pixel-bound (I do a lot of light calculation + there is blending, which is always slow).
            MyTransparentMaterial lastMaterial = MyTransparentMaterials.GetMaterial(billboards[0].Material);
            MyBillboard lastBillboard = billboards[0];
            MyTransparentMaterial lastBlendMaterial = lastBillboard.BlendMaterial != null ? MyTransparentMaterials.GetMaterial(lastBillboard.BlendMaterial) : null;


            bool ignoreDepth = false;
            Matrix projectionMatrix = MyRenderCamera.ProjectionMatrix;
            Matrix invProjectionMatrix = Matrix.Invert(projectionMatrix);
            effect.SetInverseDefaultProjectionMatrix(ref invProjectionMatrix);

            if (lastBillboard.CustomViewProjection != -1)
            {
                SetupCustomViewProjection(effect, ref originalViewport, lastBillboard, ref ignoreDepth, ref projectionMatrix);
            }

            // 0.05% of billboard is blended
            const float softColorizeSize = 0.05f;

            device.VertexDeclaration = MyVertexFormatTransparentGeometry.VertexDeclaration;
            device.SetStreamSource(0, m_vertexBuffer, 0, MyVertexFormatTransparentGeometry.Stride);
            device.Indices = m_indexBuffer;

            MyRender.GetShadowRenderer().SetupShadowBaseEffect(effect);

            MyEffectTransparentGeometry effect2 = MyRender.GetEffect(MyEffects.TransparentGeometry) as MyEffectTransparentGeometry;
            effect2.SetShadowBias(0.001f);

            MyLights.UpdateEffectReflector(effect2.Reflector, false);
            MyLights.UpdateEffect(effect2, false);


            int geomCount = billboards.Count;
            int it = 0;
            int cnt = 0;

            while (geomCount > 0)
            {
                if (geomCount > RENDER_BUFFER_SIZE)
                {
                    geomCount -= RENDER_BUFFER_SIZE;
                    cnt = RENDER_BUFFER_SIZE;
                }
                else
                {
                    cnt = geomCount;
                    geomCount = 0;
                }

                int indexFrom = it * RENDER_BUFFER_SIZE + 1;
                cnt = cnt + indexFrom - 1;
                for (int i = indexFrom; i <= cnt; i++)
                {
                    //  We need texture from billboard that's before the current billboard (because we always render "what was")
                    MyBillboard billboard = billboards[i - 1];
                    MyTransparentMaterial blendMaterialProperties = billboard.BlendMaterial != null ? MyTransparentMaterials.GetMaterial(billboard.BlendMaterial) : MyTransparentMaterials.GetMaterial(billboard.Material);
                    MyTransparentMaterial lastBlendMaterialProperties = lastBlendMaterial == null ? blendMaterialProperties : lastBlendMaterial;

                    bool colorizeChanged = EnableColorize && lastBillboard.EnableColorize != billboard.EnableColorize;
                    bool nearChanged = lastBillboard.Near != billboard.Near;
                    bool sizeChanged = EnableColorize && billboard.EnableColorize && lastBillboard.Size != billboard.Size;
                    bool blendTextureChanged = false;
                    bool projectionChanged = lastBillboard.CustomViewProjection != billboard.CustomViewProjection;
                    bool cullStencilChanges = lastBillboard.CullWithStencil != billboard.CullWithStencil;

                    if (lastBlendMaterial != (billboard.BlendMaterial != null ? MyTransparentMaterials.GetMaterial(billboard.BlendMaterial) : null) && billboard.BlendTextureRatio > 0)
                    {
                        if ((lastBlendMaterialProperties.UseAtlas) && (blendMaterialProperties.UseAtlas))
                            blendTextureChanged = false;
                        else
                            blendTextureChanged = true;
                    }

                    //bool blendTextureChanged = lastBlendTexture != billboard.BlendTexture;
                    bool billboardChanged = colorizeChanged || sizeChanged || blendTextureChanged || nearChanged || projectionChanged || cullStencilChanges;

                    MyTransparentMaterial actMaterialProperties = MyTransparentMaterials.GetMaterial(billboard.Material);
                    MyTransparentMaterial lastMaterialProperties = lastMaterial;

                    billboardChanged |= (actMaterialProperties.CanBeAffectedByOtherLights != lastMaterialProperties.CanBeAffectedByOtherLights)
                                    || (actMaterialProperties.IgnoreDepth != lastMaterialProperties.IgnoreDepth);


                    if (projectionChanged)
                    {
                        SetupCustomViewProjection(effect, ref originalViewport, lastBillboard, ref ignoreDepth, ref projectionMatrix);
                    }

                    if (!billboardChanged)
                    {
                        if (MyTransparentMaterials.GetMaterial(billboard.Material) != lastMaterial)
                        {
                            if (actMaterialProperties.UseAtlas && lastMaterialProperties.UseAtlas)
                                billboardChanged = false;
                            else
                                billboardChanged = true;
                        }
                    }

                    //  If texture is different than the last one, or if we reached end of billboards
                    if ((i == cnt) || billboardChanged)
                    {
                        //  We don't need to do this when we reach end of billboards - it's needed only if we do next iteration of possible billboards
                        if ((i != cnt) || billboardChanged)
                        {
                            if ((i - indexFrom) > 0)
                            {
                                int firstIndex = (indexFrom - 1) * MyTransparentGeometryConstants.INDICES_PER_TRANSPARENT_GEOMETRY; //MyTransparentGeometryConstants.VERTICES_PER_TRANSPARENT_GEOMETRY;

                                SetupCustomViewProjection(effect, ref originalViewport, lastBillboard, ref ignoreDepth, ref projectionMatrix);

                                SetupEffect(ref lastMaterial, lastBlendMaterialProperties, EnableColorize && lastBillboard.EnableColorize, lastBillboard.Size * softColorizeSize, lastBillboard.Near, ignoreDepth, ref projectionMatrix);

                                effect.Begin();
                                DrawBuffer(firstIndex, (i - indexFrom) * MyTransparentGeometryConstants.TRIANGLES_PER_TRANSPARENT_GEOMETRY);
                                effect.End();

                                MyPerformanceCounter.PerCameraDrawWrite.BillboardsDrawCalls++;
                            }

                            lastMaterial = MyTransparentMaterials.GetMaterial(billboard.Material);
                            lastBillboard = billboard;
                            lastBlendMaterial = billboard.BlendMaterial != null ? MyTransparentMaterials.GetMaterial(billboard.BlendMaterial) : null;
                            indexFrom = i;
                        }


                        if ((i == cnt) && (i - indexFrom + 1 != 0))
                        {
                            lastMaterial = MyTransparentMaterials.GetMaterial(lastBillboard.Material);
                            blendMaterialProperties = lastBillboard.BlendMaterial == null ? MyTransparentMaterials.GetMaterial(lastBillboard.Material) : MyTransparentMaterials.GetMaterial(lastBillboard.BlendMaterial);
                            int firstIndex = (indexFrom - 1) * MyTransparentGeometryConstants.INDICES_PER_TRANSPARENT_GEOMETRY;

                            SetupCustomViewProjection(effect, ref originalViewport, lastBillboard, ref ignoreDepth, ref projectionMatrix);

                            SetupEffect(ref lastMaterial, blendMaterialProperties, EnableColorize && billboard.EnableColorize, lastBillboard.Size * softColorizeSize, lastBillboard.Near, ignoreDepth, ref projectionMatrix);

                            if (billboard.CullWithStencil)
                            {
                                DepthStencilState.BackgroundObjects.Apply();
                            }
                            effect.Begin();
                            DrawBuffer(firstIndex, (i - indexFrom + 1) * MyTransparentGeometryConstants.TRIANGLES_PER_TRANSPARENT_GEOMETRY);
                            effect.End();

                            if (billboard.CullWithStencil)
                            {
                                previousState.Apply();
                            }
                            MyPerformanceCounter.PerCameraDrawWrite.BillboardsDrawCalls++;
                        }
                    }
                }

                it++;
            }

            device.SetStreamSource(0, null, 0, 0);

            MyPerformanceCounter.PerCameraDrawWrite.BillboardsInFrustum += billboards.Count;

            // Visualize overdraw of particles. More overdraws = bigger performance issue.
            if (MyRender.Settings.VisualizeOverdraw)
            {
                if (m_overDrawColorsAnim == null)
                {
                    m_overDrawColorsAnim = new MyAnimatedPropertyVector4();
                    m_overDrawColorsAnim.AddKey(0.0f, new Vector4(0.0f, 1.0f, 0.0f, 1.0f));
                    m_overDrawColorsAnim.AddKey(0.25f, new Vector4(1.0f, 1.0f, 0.0f, 1.0f));
                    m_overDrawColorsAnim.AddKey(0.75f, new Vector4(0.0f, 0.0f, 1.0f, 1.0f));
                    m_overDrawColorsAnim.AddKey(1.0f, new Vector4(1.0f, 0.0f, 0.0f, 1.0f));
                }

                //Space without particles is black
                device.Clear(ClearFlags.Target, new ColorBGRA(0), 1.0f, 0);


                for (int referenceStencil = 1; referenceStencil < PARTICLES_OVERDRAW_MAX; referenceStencil++)
                {
                    DepthStencilState ds = new DepthStencilState()
                    {
                        StencilEnable = true,
                        ReferenceStencil = referenceStencil,
                        StencilFunction = Compare.LessEqual,
                    };

                    ds.Apply(false);


                    float diff = (float)(referenceStencil - 1) / (PARTICLES_OVERDRAW_MAX - 1);
                    Vector4 referenceColorV4;
                    m_overDrawColorsAnim.GetInterpolatedValue<Vector4>(diff, out referenceColorV4);
                    Color referenceColor = new Color(referenceColorV4);

                    MyRender.BeginSpriteBatch(BlendState.Opaque, null, null);
                    MyRender.DrawSprite(MyRender.BlankTexture, new Rectangle(0, 0, MyRenderCamera.Viewport.Width, MyRenderCamera.Viewport.Height), referenceColor);
                    MyRender.EndSpriteBatch();
                }

                DepthStencilState.None.Apply();

                int leftStart = MyRenderCamera.Viewport.Width / 4;
                int topStart = (int)(MyRenderCamera.Viewport.Height * 0.75f);

                int size = MyRenderCamera.Viewport.Width - 2 * leftStart;
                int sizeY = (int)(MyRenderCamera.Viewport.Width / 32.0f);
                int sizeStep = size / PARTICLES_OVERDRAW_MAX;

                MyRender.BeginSpriteBatch(null, null, null);

                for (int i = 0; i < PARTICLES_OVERDRAW_MAX; i++)
                {
                    float diff = (float)(i - 1) / (PARTICLES_OVERDRAW_MAX - 1);
                    Vector4 referenceColorV4;
                    m_overDrawColorsAnim.GetInterpolatedValue<Vector4>(diff, out referenceColorV4);
                    Color referenceColor = new Color(referenceColorV4);

                    MyRender.DrawSprite(MyRender.BlankTexture, new Rectangle(leftStart + i * sizeStep, topStart, sizeStep, sizeY), referenceColor);
                }

                MyDebugDraw.DrawText(new Vector2((float)leftStart, (float)(topStart + sizeY)), new System.Text.StringBuilder("1"), Color.White, 1.0f, false);
                MyDebugDraw.DrawText(new Vector2((float)leftStart + size, (float)(topStart + sizeY)), new System.Text.StringBuilder(">" + PARTICLES_OVERDRAW_MAX.ToString()), Color.White, 1.0f, false);

                MyRender.EndSpriteBatch();

                device.SetRenderTarget(0, oldTargets);
                oldTargets.Dispose();

                MyRender.Blit(MyRender.GetRenderTarget(MyRenderTargets.Auxiliary0), false);
            }

            //  Restore to 'opaque', because that's the usual blend state
            BlendState.Opaque.Apply();
        }
Example #60
0
        internal void AddCone(Vector3 translation, Vector3 directionVec, Vector3 baseVec, int tessalation, Color color)
        {
            var axis = directionVec;

            axis.Normalize();

            var apex = translation + directionVec;

            var steps    = tessalation;
            var stepsRcp = (float)(Math.PI * 2 / steps);

            for (int i = 0; i < 32; i++)
            {
                float a0 = i * stepsRcp;
                float a1 = (i + 1) * stepsRcp;

                var A = translation + Vector3.Transform(baseVec, Matrix.CreateFromAxisAngle(axis, a0));
                var B = translation + Vector3.Transform(baseVec, Matrix.CreateFromAxisAngle(axis, a1));

                Add(A, B, color);
                Add(A, apex, color);
            }
        }