Пример #1
0
 public SelectColorBox(TextBoxEnterEvent e, Color c)
     : base("", "", e, -1, Keys.Enter)
 {
     this.size = new Vector2(320, 256);
     Center();
     r = new ColorDial(this.position + new Vector2((SPACE / (BARS + 1)) * 1 + 0 * (this.size.X - SPACE) / BARS , 8), new Vector2((this.size.X - SPACE) / BARS, this.size.Y - 48), Color.Red, c.ToVector4().X);
     g = new ColorDial(this.position + new Vector2((SPACE / (BARS + 1)) * 2 + 1 * (this.size.X - SPACE) / BARS, 8), new Vector2((this.size.X - SPACE) / BARS, this.size.Y - 48), Color.Green, c.ToVector4().Y);
     b = new ColorDial(this.position + new Vector2((SPACE / (BARS + 1)) * 3 + 2 * (this.size.X - SPACE) / BARS, 8), new Vector2((this.size.X - SPACE) / BARS, this.size.Y - 48), Color.Blue, c.ToVector4().Z);
     a = new ColorDial(this.position + new Vector2((SPACE / (BARS + 1)) * 4 + 3 * (this.size.X - SPACE) / BARS, 8), new Vector2((this.size.X - SPACE) / BARS, this.size.Y - 48), Color.Gray, c.ToVector4().W);
 }
        public static Color MultiplyBlend(Color a, Color b)
        {
            Vector4 av = a.ToVector4();
            Vector4 bv = b.ToVector4();

            return new Color(av * bv);
        }
Пример #3
0
		public Triangle( Vector3 p1, Vector3 p2, Vector3 p3, Color color ) {
			myColor = color.ToVector4();
			InitEffect();
			SetUpVertices( p1, p2, p3, color );
			SetUpIndices();
			Update();
		}
Пример #4
0
 //public void BeginWire()
 //{
 //    graphics.RasterizerState = wire;
 //}
 void SetStates(Color color, Vector2 targetSize)
 {
     graphics.RasterizerState = wire;
     effectColor.SetValue(color.ToVector4());
     effectSize.SetValue(new Vector2(1f / targetSize.X, 1f / targetSize.Y));
     effect.CurrentTechnique.Passes[0].Apply();
 }
Пример #5
0
        public static Color Multiply(Color color1, Color color2)
        {
            Vector4 v1 = color1.ToVector4();
            Vector4 v2 = color2.ToVector4();

            return new Color(v1.X * v2.X, v1.Y * v2.Y, v1.Z * v2.Z, v1.W * v2.W);
        }
Пример #6
0
 public BlockVertex(Vector3 position, HalfVector2 blockTextureCoordinate, HalfVector4 light, Color tint)
 {
     m_position = position;
     m_blockTextureCoordinate = blockTextureCoordinate;
     m_light = light;
     m_tint = new HalfVector4(tint.ToVector4());
 }
Пример #7
0
        public void initialize( string name, Vector3 position, Vector3 direction, Color color, float scaleModifier = 1.0f, int nParticlesModifier = 0, float lifetimeModifier = 0.0f)
        {
            particles.Clear();
            data = ParticleManager.Instance.getBaseParticleSystemData(name);
            this.position = position;
            this.direction = direction;

            // modify the base data with the parameters
            if (nParticlesModifier != 0)
            {
                data.nParticles = nParticlesModifier;
            }
            if (lifetimeModifier != 0.0f)
            {
                data.systemLife = lifetimeModifier;
                data.particlesLife = lifetimeModifier;
            }

            data.size *= scaleModifier;
            data.sizeIni *= scaleModifier;
            data.sizeEnd *= scaleModifier;
            data.positionVarianceMin *= scaleModifier;
            data.positionVarianceMax *= scaleModifier;
            data.directionVarianceMin *= scaleModifier;
            data.directionVarianceMax *= scaleModifier;
            data.accelerationVarianceMin *= scaleModifier;
            data.accelerationVarianceMax *= scaleModifier;
            data.color = new Color(data.color.ToVector4() * color.ToVector4());

            // get an aproximate number of the simultaneous particles that will have the system
            float spawnRatio = data.particlesLife / (float)data.nParticles;
            particles.Capacity = data.nParticles;

            switch(data.type)
            {
                case ParticleSystemData.tParticleSystem.Burst:
                    for(int i=0; i<data.nParticles; i++)
                    {
                        Particle p = new Particle();
                        p.isDead = true;
                        initializeParticle(p);
                        particles.Add(p);
                    }
                    break;
                case ParticleSystemData.tParticleSystem.Fountain:
                    for(int i=0; i<data.nParticles; i++)
                    {
                        Particle p = new Particle();
                        // we want particles prepared to be spawned with the spawnRatio ratio, so we set'em all alive but invisible
                        p.life = 1.3f + spawnRatio * i;
                        p.isDead = false;
                        p.color *= 0;
                        particles.Add(p);
                    }
                    break;
                default:
                    break;
            }
        }
Пример #8
0
 public structVertex(Vector4 CoordVertex, Vector2 CoordTex, Vector4 Normale, Color Couleur, Vector4 Tangent)
 {
     this.CoordTex = CoordTex;
     this.CoordVertex = CoordVertex;
     this.Normale = Normale;
     this.Couleur = Couleur.ToVector4();
     this.Tangent = Tangent;
 }
Пример #9
0
 public Spark(Texture2D Texture, int From, int To, float Time, Color color)
 {
     start = From;
     end = To;
     time = Time;
     parameter = 0.0f;
     Color = color.ToVector4();
 }
Пример #10
0
        public Vector4 Color;        // COLOR;

        public SpriteVertex(Vector3 pos, Vector2 size, float rotation = 0, int textureIndex = 0, Color?color = null)
        {
            this.Pos          = pos;
            this.Size         = size;
            this.Rotation     = rotation;
            this.TextureIndex = textureIndex;
            this.Color        = color?.ToVector4() ?? SharpDX.Color.White.ToVector4();
        }
Пример #11
0
        public override Color GetColor(Player player, Color lightColor)
        {
            bool lighting = true;
            Color color = _colorProcessor(player, player.hairColor, ref lighting);
            if (lighting)
                return new Color(color.ToVector4() * lightColor.ToVector4());

            return color;
        }
		public override Color GetColor(Player player, Color lightColor)
		{
			bool flag = true;
			Color result = this._colorProcessor(player, player.hairColor, ref flag);
			if (flag)
			{
				return new Color(result.ToVector4() * lightColor.ToVector4());
			}
			return result;
		}
Пример #13
0
        /// <summary>
        /// Drawn text using given font, position and color
        /// </summary>
        public void DrawText(FontType font, String text, Vector2 position, Color color, bool dropShadow)
        {
            if (mIsTextModeActive)
            {
                if (dropShadow)
                    mSpriteBatch.DrawString(Fonts[(int)font], text, position + mDropShadowOffset, new Color(color.ToVector4() * new Vector4(0, 0, 0, 1)));

                mSpriteBatch.DrawString(Fonts[(int)font], text, position, color);
            }
        }
        //  Add 3d line into cache, so then we can draw many lines at once - by calling DrawLinesFromCache()
        public static void AddLine(Vector3 pointFrom, Vector3 pointTo, Color colorFrom, Color colorTo)
        {
            MyCommonDebugUtils.AssertDebug(IsFull(0) == false);

            if (m_linesCount + 2 >= MyDebugDrawCachedLinesConstants.MAX_LINES_IN_CACHE)
                return;

            m_verticesLine[m_linesCount * 2 + 0].Position = pointFrom;
            m_verticesLine[m_linesCount * 2 + 0].Color = colorFrom.ToVector4();
            m_verticesLine[m_linesCount * 2 + 1].Position = pointTo;
            m_verticesLine[m_linesCount * 2 + 1].Color = colorTo.ToVector4();
            m_linesCount++;
        }
Пример #15
0
        public static Texture2D Create(GraphicsDevice graphicsDevice, int width = 1, int height = 1, Color color = new Color())
        {
            var texture = new Texture2D(graphicsDevice,
                                        width,
                                        height);

            var colors = new Color[width * height];
            for (var i = 0; i < colors.Length; i++) colors[i] = new Color(color.ToVector4());

            texture.SetData(colors);

            return texture;
        }
Пример #16
0
        //int colormixer = NewImage(1, 1);
        Color ColorMorph(Color col1, Color col2, int step, int totalsteps)
        {
            float factor = step / (float)totalsteps;
            var vcol1 = col1.ToVector4();
            var vcol2 = col2.ToVector4();
            var result = vcol1 * (1-factor) + vcol2 * factor;
            result.W = 1;
            return new Color(result);

            //SetPixel(0, 0, col1, colormixer);
            //SetLucent(100 - (step * 100 / totalsteps));
            //SetPixel(0, 0, col2, colormixer);
            //SetLucent(0);
            //return GetPixel(0, 0, colormixer);
        }
Пример #17
0
        public void SetElement(int i, Vector2 start, Vector2 end, Color color, float radius)
        {
            Debug.Assert(i < Count);

            positionData[i] = new Vector4(start.X, start.Y, end.X, end.Y);
            colorData[i] = color.ToVector4();

            switch(i%4)
            {
                case 0: radiusData[i/4].X = radius; break;
                case 1: radiusData[i/4].Y = radius; break;
                case 2: radiusData[i/4].Z = radius; break;
                case 3: radiusData[i/4].W = radius; break;
            }
        }
Пример #18
0
        public static void render(this Texture texture, Matrix worldMatrix, Color color, bool customUVs = false)
        {
            fxWVP.SetValue(worldMatrix * Camera2D.view * Camera2D.projection);
            fxTexture.SetValue(texture);
            fxColor.SetValue(color.ToVector4());
            quadEffect.Techniques[0].Passes[0].Apply();

            if (customUVs)
            {
                GraphicsManager.Instance.graphicsDevice.DrawUserIndexedPrimitives<VertexPositionTexture>(
                    PrimitiveType.TriangleList, vertexUVs, 0, 4, index, 0, 2);
            }
            else
            {
                GraphicsManager.Instance.graphicsDevice.DrawUserIndexedPrimitives<VertexPositionTexture>(
                    PrimitiveType.TriangleList, vertex, 0, 4, index, 0, 2);
            }
        }
Пример #19
0
        public Progressbar ( string name, Vector2 position, Color color, int width, int value, bool bContinuous )
        {
            Type = ControlType.ProgressBar;
            this.name = name;
            //this.origin = position;
            this.position = position;
            this.width = width;
            this.value = value;
            this.color = color.ToVector4();

            if (bContinuous)
                style = Style.Continuous;
            else
                style = Style.Blocks;

            numberOfBlocks = width / blockWidth + 1;
            max = 100;

            CreateTextures();
        }
Пример #20
0
        public HslColor(Color rgba)
        {
            Vector4 v4 = rgba.ToVector4();

            double min = Math.Min(Math.Min(v4.X, v4.Y), v4.Z);
            double max = Math.Max(Math.Max(v4.X, v4.Y), v4.Z);

            L = (min + max) / 2.0;
            H = double.NaN;

            if (min == max)
            {
                S = 0;
                H = 0;
            }
            else if (L < 0.5)
            {
                S = (max - min) / (max + min);
            }
            else
            {
                S = (max - min) / (2.0 - max - min);
            }

            if (H == double.NaN)
            {
                if (v4.X == max)
                {
                    H = ((v4.Y - v4.Z) / (max - min)) / 6.0;
                }
                else if (v4.Y == max)
                {
                    H = (2.0 + (v4.Z - v4.X) / (max - min)) / 6.0;
                }
                else
                {
                    H = (4.0 + (v4.X - v4.Y) / (max - min)) / 6.0;
                }
            }
        }
Пример #21
0
 public static void ColorKey(TextureContent texture, Color colorKey)
 {
     foreach (MipmapChain chain in texture.Faces)
     {
         foreach (BitmapContent content in chain)
         {
             var content3 = content as PixelBitmapContent<Color>;
             if (content3 == null)
             {
                 var content2 = content as PixelBitmapContent<Vector4>;
                 if (content2 == null)
                 {
                     throw new NotSupportedException();
                 }
                 content2.ReplaceColor(colorKey.ToVector4(), Vector4.Zero);
             }
             else
             {
                 content3.ReplaceColor(colorKey, Color.Transparent);
             }
         }
     }
 }
Пример #22
0
 public PillarShader(Color primaryColor, Color secondaryColor)
 {
     this.\u002Ector();
     this._primaryColor   = primaryColor.ToVector4();
     this._secondaryColor = secondaryColor.ToVector4();
 }
Пример #23
0
 public QueenBeeShader(Color primaryColor, Color secondaryColor) : base()
 {
     this._primaryColor   = primaryColor.ToVector4();
     this._secondaryColor = secondaryColor.ToVector4();
 }
Пример #24
0
 public void set_sprite_batch_effects(Effect effect)
 {
     effect.Parameters["color_shift"].SetValue(Unit_Color.ToVector4());
     effect.Parameters["opacity"].SetValue(Opacity / 255f);
     //effect.Parameters["color_shift"].SetValue(new Vector4(0.5f, 0.5f, 0.5f, 0.5f));
 }
Пример #25
0
        public void DrawAvatarMesh(GraphicsDevice device, WorldState state, Matrix world, Color baseCol)
        {
            var effect    = WorldContent.AvatarEffect;
            var technique = effect.CurrentTechnique;
            var room      = (Room > 65530 || Room == 0) ? Room : blueprint.Rooms[Room].Base;

            foreach (var pass in technique.Passes)
            {
                effect.Parameters["ObjectID"].SetValue(ObjectID / 65535f);
                effect.Parameters["Level"].SetValue(ALevel + 0.0001f);
                var roomLights = blueprint?.RoomColors;
                if (roomLights != null)
                {
                    var col = ((WorldConfig.Current.AdvancedLighting) ? new Vector4(1) : PowColorVec(roomLights[room].ToVector4(), 1 / 2.2f)) * baseCol.ToVector4();
                    effect.Parameters["AmbientLight"].SetValue(col);
                }
                effect.Parameters["World"].SetValue(world);
                pass.Apply();

                Avatar.DrawGeometry(device, effect);
            }
        }
Пример #26
0
        public SerializatorWrapper()
        {
            serializator.Add(typeof(Matrix),
                             (x, a, b) =>
            {
                Matrix v = (Matrix)a;
                b.BeginType(x, typeof(Matrix).AssemblyQualifiedName);
                b.Serialize("m11", v.M11);
                b.Serialize("m12", v.M12);
                b.Serialize("m13", v.M13);
                b.Serialize("m14", v.M14);
                b.Serialize("m21", v.M21);
                b.Serialize("m22", v.M22);
                b.Serialize("m23", v.M23);
                b.Serialize("m24", v.M24);
                b.Serialize("m31", v.M31);
                b.Serialize("m32", v.M32);
                b.Serialize("m33", v.M33);
                b.Serialize("m34", v.M34);
                b.Serialize("m41", v.M41);
                b.Serialize("m42", v.M42);
                b.Serialize("m43", v.M43);
                b.Serialize("m44", v.M44);
                b.EndType(x);
            }
                             );

            serializator.Add(typeof(Vector3),
                             (x, a, b) =>
            {
                Vector3 v = (Vector3)a;
                b.BeginType(x, typeof(Vector3).AssemblyQualifiedName);
                b.Serialize("x", v.X);
                b.Serialize("y", v.Y);
                b.Serialize("z", v.Z);
                b.EndType(x);
            }
                             );

            serializator.Add(typeof(Quaternion),
                             (x, a, b) =>
            {
                Quaternion v = (Quaternion)a;
                b.BeginType(x, typeof(Quaternion).AssemblyQualifiedName);
                b.Serialize("x", v.X);
                b.Serialize("y", v.Y);
                b.Serialize("z", v.Z);
                b.Serialize("w", v.W);
                b.EndType(x);
            }
                             );

            serializator.Add(typeof(Vector4),
                             (x, a, b) =>
            {
                Vector4 v = (Vector4)a;
                b.BeginType(x, typeof(Vector4).AssemblyQualifiedName);
                b.Serialize("x", v.X);
                b.Serialize("y", v.Y);
                b.Serialize("z", v.Z);
                b.Serialize("w", v.W);
                b.EndType(x);
            }
                             );
            serializator.Add(typeof(Color),
                             (x, a, b) =>
            {
                Color v = (Color)a;
                b.BeginType(x, typeof(Vector2).AssemblyQualifiedName);
                Vector4 c = v.ToVector4();
                b.Serialize("x", c.X);
                b.Serialize("y", c.Y);
                b.Serialize("z", c.Z);
                b.Serialize("w", c.W);
                b.EndType(x);
            }
                             );


            serializator.Add(typeof(Vector2),
                             (x, a, b) =>
            {
                Vector2 v = (Vector2)a;
                b.BeginType(x, typeof(Vector2).AssemblyQualifiedName);
                b.Serialize("x", v.X);
                b.Serialize("y", v.Y);
                b.EndType(x);
            }
                             );

            desserializador.Add(typeof(Color),
                                (a) =>
            {
                Vector4 v = new Vector4();
                v.X       = Convert.ToSingle(a.Element("x").Value);
                v.Y       = Convert.ToSingle(a.Element("y").Value);
                v.Z       = Convert.ToSingle(a.Element("z").Value);
                v.W       = Convert.ToSingle(a.Element("w").Value);
                return(new Color(v));
            }
                                );

            desserializador.Add(typeof(Vector3),
                                (a) =>
            {
                Vector3 v = new Vector3();
                v.X       = Convert.ToSingle(a.Element("x").Value);
                v.Y       = Convert.ToSingle(a.Element("y").Value);
                v.Z       = Convert.ToSingle(a.Element("z").Value);
                return(v);
            }
                                );

            desserializador.Add(typeof(Vector2),
                                (a) =>
            {
                Vector2 v = new Vector2();
                v.X       = Convert.ToSingle(a.Element("x").Value);
                v.Y       = Convert.ToSingle(a.Element("y").Value);
                return(v);
            }
                                );

            desserializador.Add(typeof(Vector4),
                                (a) =>
            {
                Vector4 v = new Vector4();
                v.X       = Convert.ToSingle(a.Element("x").Value);
                v.Y       = Convert.ToSingle(a.Element("y").Value);
                v.Z       = Convert.ToSingle(a.Element("z").Value);
                v.W       = Convert.ToSingle(a.Element("w").Value);
                return(v);
            }
                                );
            desserializador.Add(typeof(Quaternion),
                                (a) =>
            {
                Quaternion v = new Quaternion();
                v.X          = Convert.ToSingle(a.Element("x").Value);
                v.Y          = Convert.ToSingle(a.Element("y").Value);
                v.Z          = Convert.ToSingle(a.Element("z").Value);
                v.W          = Convert.ToSingle(a.Element("w").Value);
                return(v);
            }
                                );

            desserializador.Add(typeof(Matrix),
                                (a) =>
            {
                Matrix v = new Matrix();
                v.M11    = Convert.ToSingle(a.Element("m11").Value);
                v.M12    = Convert.ToSingle(a.Element("m12").Value);
                v.M13    = Convert.ToSingle(a.Element("m13").Value);
                v.M14    = Convert.ToSingle(a.Element("m14").Value);

                v.M21 = Convert.ToSingle(a.Element("m21").Value);
                v.M22 = Convert.ToSingle(a.Element("m22").Value);
                v.M23 = Convert.ToSingle(a.Element("m23").Value);
                v.M24 = Convert.ToSingle(a.Element("m24").Value);

                v.M31 = Convert.ToSingle(a.Element("m31").Value);
                v.M32 = Convert.ToSingle(a.Element("m32").Value);
                v.M33 = Convert.ToSingle(a.Element("m33").Value);
                v.M34 = Convert.ToSingle(a.Element("m34").Value);

                v.M41 = Convert.ToSingle(a.Element("m41").Value);
                v.M42 = Convert.ToSingle(a.Element("m42").Value);
                v.M43 = Convert.ToSingle(a.Element("m43").Value);
                v.M44 = Convert.ToSingle(a.Element("m44").Value);

                return(v);
            }
                                );
        }
Пример #27
0
 public UnderworldShader(Color backColor, Color frontColor, float speed) : base()
 {
     this._backColor  = backColor.ToVector4();
     this._frontColor = frontColor.ToVector4();
     this._speed      = speed;
 }
Пример #28
0
        /// <summary>
        /// Draw a list of Lines.
        /// </summary>
        /// <remarks>
        /// Set globalRadius = 0 to use the radius stored in each Line.
        /// Set globalColor to Color.TransparentBlack to use the color stored in each Line.
        /// </remarks>
        public void Draw(List <Line> lineList, float globalRadius, Color globalColor, Matrix viewMatrix, Matrix projMatrix,
                         float time, string techniqueName)
        {
            Vector4 lineColor;
            bool    uniqueColors = false;

            if (techniqueName == null)
            {
                effect.CurrentTechnique = effect.Techniques[0];
            }
            else
            {
                effect.CurrentTechnique = effect.Techniques[techniqueName];
            }
            effect.Begin();
            EffectPass pass = effect.CurrentTechnique.Passes[0];

            GraphicsDevice.VertexDeclaration = vdecl;
            GraphicsDevice.Vertices[0].SetSource(vb, 0, bytesPerVertex);
            GraphicsDevice.Indices = ib;

            pass.Begin();

            timeParameter.SetValue(time);
            if (globalColor == Color.TransparentBlack)
            {
                uniqueColors = true;
            }
            else
            {
                lineColor = globalColor.ToVector4();
                lineColorParameter.SetValue(lineColor);
            }
            if (globalRadius != 0)
            {
                radiusParameter.SetValue(globalRadius);
            }

            foreach (Line line in lineList)
            {
                Matrix worldViewProjMatrix = line.WorldMatrix() * viewMatrix * projMatrix;
                wvpMatrixParameter.SetValue(worldViewProjMatrix);
                lengthParameter.SetValue(line.rho);
                rotationParameter.SetValue(line.theta);
                if (globalRadius == 0)
                {
                    radiusParameter.SetValue(line.radius);
                }
                if (uniqueColors)
                {
                    lineColor = line.color.ToVector4();
                    lineColorParameter.SetValue(lineColor);
                }
                effect.CommitChanges();
                GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, numVertices, 0, numPrimitives);
                numLinesDrawn++;
            }
            pass.End();

            effect.End();
        }
Пример #29
0
 public override Color OnTileColor(Color inColor)
 {
     float intensity = this.GetIntensity();
     return new Color(Vector4.Lerp(new Vector4(0.5f, 0.8f, 1f, 1f), inColor.ToVector4(), 1f - intensity));
 }
Пример #30
0
        public override Color OnTileColor(Color inColor)
        {
            Vector4 value = inColor.ToVector4();

            return(new Color(Vector4.Lerp(value, Vector4.One, Intensity * 0.5f)));
        }
Пример #31
0
        public void RenderLightMap(GraphicsDevice graphics, SpriteBatch spriteBatch, Camera cam, RenderTarget2D backgroundObstructor = null)
        {
            if (!LightingEnabled)
            {
                return;
            }

            if (Math.Abs(currLightMapScale - GameMain.Config.LightMapScale) > 0.01f)
            {
                //lightmap scale has changed -> recreate render targets
                CreateRenderTargets(graphics);
            }

            Matrix spriteBatchTransform = cam.Transform * Matrix.CreateScale(new Vector3(GameMain.Config.LightMapScale, GameMain.Config.LightMapScale, 1.0f));
            Matrix transform            = cam.ShaderTransform
                                          * Matrix.CreateOrthographic(GameMain.GraphicsWidth, GameMain.GraphicsHeight, -1, 1) * 0.5f;

            bool highlightsVisible = UpdateHighlights(graphics, spriteBatch, spriteBatchTransform, cam);

            Rectangle viewRect = cam.WorldView;

            viewRect.Y -= cam.WorldView.Height;
            //check which lights need to be drawn
            activeLights.Clear();
            foreach (LightSource light in lights)
            {
                if (!light.Enabled)
                {
                    continue;
                }
                if ((light.Color.A < 1 || light.Range < 1.0f) && !light.LightSourceParams.OverrideLightSpriteAlpha.HasValue)
                {
                    continue;
                }
                if (light.ParentBody != null)
                {
                    light.Position = light.ParentBody.DrawPosition;
                    if (light.ParentSub != null)
                    {
                        light.Position -= light.ParentSub.DrawPosition;
                    }
                }

                float range = light.LightSourceParams.TextureRange;
                if (light.LightSprite != null)
                {
                    float spriteRange = Math.Max(
                        light.LightSprite.size.X * light.SpriteScale.X * (0.5f + Math.Abs(light.LightSprite.RelativeOrigin.X - 0.5f)),
                        light.LightSprite.size.Y * light.SpriteScale.Y * (0.5f + Math.Abs(light.LightSprite.RelativeOrigin.Y - 0.5f)));
                    range = Math.Max(spriteRange, range);
                }
                if (!MathUtils.CircleIntersectsRectangle(light.WorldPosition, range, viewRect))
                {
                    continue;
                }
                activeLights.Add(light);
            }

            //draw light sprites attached to characters
            //render into a separate rendertarget using alpha blending (instead of on top of everything else with alpha blending)
            //to prevent the lights from showing through other characters or other light sprites attached to the same character
            //---------------------------------------------------------------------------------------------------
            graphics.SetRenderTarget(LimbLightMap);
            graphics.Clear(Color.Black);
            graphics.BlendState = BlendState.NonPremultiplied;
            spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.NonPremultiplied, transformMatrix: spriteBatchTransform);
            foreach (LightSource light in activeLights)
            {
                if (light.IsBackground || light.CurrentBrightness <= 0.0f)
                {
                    continue;
                }
                //draw limb lights at this point, because they were skipped over previously to prevent them from being obstructed
                if (light.ParentBody?.UserData is Limb limb && !limb.Hide)
                {
                    light.DrawSprite(spriteBatch, cam);
                }
            }
            spriteBatch.End();

            //draw background lights
            //---------------------------------------------------------------------------------------------------
            graphics.SetRenderTarget(LightMap);
            graphics.Clear(AmbientLight);
            graphics.BlendState = BlendState.Additive;
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive, transformMatrix: spriteBatchTransform);
            Level.Loaded?.BackgroundCreatureManager?.DrawLights(spriteBatch, cam);
            foreach (LightSource light in activeLights)
            {
                if (!light.IsBackground || light.CurrentBrightness <= 0.0f)
                {
                    continue;
                }
                light.DrawSprite(spriteBatch, cam);
                light.DrawLightVolume(spriteBatch, lightEffect, transform);
            }
            GameMain.ParticleManager.Draw(spriteBatch, true, null, Particles.ParticleBlendState.Additive);
            spriteBatch.End();

            //draw a black rectangle on hulls to hide background lights behind subs
            //---------------------------------------------------------------------------------------------------

            if (backgroundObstructor != null)
            {
                spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied);
                spriteBatch.Draw(backgroundObstructor, new Rectangle(0, 0,
                                                                     (int)(GameMain.GraphicsWidth * currLightMapScale), (int)(GameMain.GraphicsHeight * currLightMapScale)), Color.Black);
                spriteBatch.End();
            }

            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Opaque, transformMatrix: spriteBatchTransform);
            Dictionary <Hull, Rectangle> visibleHulls = GetVisibleHulls(cam);

            foreach (KeyValuePair <Hull, Rectangle> hull in visibleHulls)
            {
                GUI.DrawRectangle(spriteBatch,
                                  new Vector2(hull.Value.X, -hull.Value.Y),
                                  new Vector2(hull.Value.Width, hull.Value.Height),
                                  hull.Key.AmbientLight == Color.TransparentBlack ? Color.Black : hull.Key.AmbientLight.Multiply(hull.Key.AmbientLight.A / 255.0f), true);
            }
            spriteBatch.End();

            SolidColorEffect.CurrentTechnique = SolidColorEffect.Techniques["SolidColor"];
            SolidColorEffect.Parameters["color"].SetValue(AmbientLight.ToVector4());
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, transformMatrix: spriteBatchTransform, effect: SolidColorEffect);
            Submarine.DrawDamageable(spriteBatch, null);
            spriteBatch.End();

            graphics.BlendState = BlendState.Additive;


            //draw the focused item and character to highlight them,
            //and light sprites (done before drawing the actual light volumes so we can make characters obstruct the highlights and sprites)
            //---------------------------------------------------------------------------------------------------
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive, transformMatrix: spriteBatchTransform);
            foreach (LightSource light in activeLights)
            {
                //don't draw limb lights at this point, they need to be drawn after lights have been obstructed by characters
                if (light.IsBackground || light.ParentBody?.UserData is Limb || light.CurrentBrightness <= 0.0f)
                {
                    continue;
                }
                light.DrawSprite(spriteBatch, cam);
            }
            spriteBatch.End();

            if (highlightsVisible)
            {
                spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive);
                spriteBatch.Draw(HighlightMap, Vector2.Zero, Color.White);
                spriteBatch.End();
            }

            //draw characters to obstruct the highlighted items/characters and light sprites
            //---------------------------------------------------------------------------------------------------

            SolidColorEffect.CurrentTechnique = SolidColorEffect.Techniques["SolidVertexColor"];
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, effect: SolidColorEffect, transformMatrix: spriteBatchTransform);
            foreach (Character character in Character.CharacterList)
            {
                if (character.CurrentHull == null || !character.Enabled || !character.IsVisible)
                {
                    continue;
                }
                if (Character.Controlled?.FocusedCharacter == character)
                {
                    continue;
                }
                Color lightColor = character.CurrentHull.AmbientLight == Color.TransparentBlack ?
                                   Color.Black :
                                   character.CurrentHull.AmbientLight.Multiply(character.CurrentHull.AmbientLight.A / 255.0f).Opaque();
                foreach (Limb limb in character.AnimController.Limbs)
                {
                    if (limb.DeformSprite != null)
                    {
                        continue;
                    }
                    limb.Draw(spriteBatch, cam, lightColor);
                }
            }
            spriteBatch.End();

            DeformableSprite.Effect.CurrentTechnique = DeformableSprite.Effect.Techniques["DeformShaderSolidVertexColor"];
            DeformableSprite.Effect.CurrentTechnique.Passes[0].Apply();
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, transformMatrix: spriteBatchTransform);
            foreach (Character character in Character.CharacterList)
            {
                if (character.CurrentHull == null || !character.Enabled || !character.IsVisible)
                {
                    continue;
                }
                if (Character.Controlled?.FocusedCharacter == character)
                {
                    continue;
                }
                Color lightColor = character.CurrentHull.AmbientLight == Color.TransparentBlack ?
                                   Color.Black :
                                   character.CurrentHull.AmbientLight.Multiply(character.CurrentHull.AmbientLight.A / 255.0f).Opaque();
                foreach (Limb limb in character.AnimController.Limbs)
                {
                    if (limb.DeformSprite == null)
                    {
                        continue;
                    }
                    limb.Draw(spriteBatch, cam, lightColor);
                }
            }
            spriteBatch.End();
            DeformableSprite.Effect.CurrentTechnique = DeformableSprite.Effect.Techniques["DeformShader"];
            graphics.BlendState = BlendState.Additive;

            //draw the actual light volumes, additive particles, hull ambient lights and the halo around the player
            //---------------------------------------------------------------------------------------------------
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive, transformMatrix: spriteBatchTransform);

            spriteBatch.Draw(LimbLightMap, new Rectangle(cam.WorldView.X, -cam.WorldView.Y, cam.WorldView.Width, cam.WorldView.Height), Color.White);

            foreach (ElectricalDischarger discharger in ElectricalDischarger.List)
            {
                discharger.DrawElectricity(spriteBatch);
            }

            foreach (LightSource light in activeLights)
            {
                if (light.IsBackground || light.CurrentBrightness <= 0.0f)
                {
                    continue;
                }
                light.DrawLightVolume(spriteBatch, lightEffect, transform);
            }

            lightEffect.World = transform;

            GameMain.ParticleManager.Draw(spriteBatch, false, null, Particles.ParticleBlendState.Additive);

            if (Character.Controlled != null)
            {
                DrawHalo(Character.Controlled);
            }
            else
            {
                foreach (Character character in Character.CharacterList)
                {
                    if (character.Submarine == null || character.IsDead || !character.IsHuman)
                    {
                        continue;
                    }
                    DrawHalo(character);
                }
            }

            void DrawHalo(Character character)
            {
                if (character == null || character.Removed)
                {
                    return;
                }
                Vector2 haloDrawPos = character.DrawPosition;

                haloDrawPos.Y = -haloDrawPos.Y;

                //ambient light decreases the brightness of the halo (no need for a bright halo if the ambient light is bright enough)
                float ambientBrightness = (AmbientLight.R + AmbientLight.B + AmbientLight.G) / 255.0f / 3.0f;
                Color haloColor         = Color.White.Multiply(0.3f - ambientBrightness);

                if (haloColor.A > 0)
                {
                    float scale = 512.0f / LightSource.LightTexture.Width;
                    spriteBatch.Draw(
                        LightSource.LightTexture, haloDrawPos, null, haloColor, 0.0f,
                        new Vector2(LightSource.LightTexture.Width, LightSource.LightTexture.Height) / 2, scale, SpriteEffects.None, 0.0f);
                }
            }

            spriteBatch.End();

            //draw the actual light volumes, additive particles, hull ambient lights and the halo around the player
            //---------------------------------------------------------------------------------------------------

            graphics.SetRenderTarget(null);
            graphics.BlendState = BlendState.NonPremultiplied;
        }
Пример #32
0
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        public static Color GetColorWithAlpha(Color col, float alpha)
        {
            var c = col.ToVector4();

            return(new Color(c * new Vector4(Vector3.One, alpha)));
        }
Пример #33
0
 /// <summary>
 /// Draws a texture to the UIElement. This method will deal with
 /// the matrix calculations
 /// </summary>
 /// <param name="batch"></param>
 /// <param name="texture"></param>
 /// <param name="from"></param>
 /// <param name="to"></param>
 /// <param name="scale"></param>
 /// <param name="blend"></param>
 public void DrawLocalTexture(SpriteBatch batch, Texture2D texture, Nullable <Rectangle> from, Vector2 to, Vector2 scale, Color blend)
 {
     //if (!m_IsInvalidated)
     //{
     batch.Draw(texture, FlooredLocalPoint(to), from, new Color(_BlendColor.ToVector4() * blend.ToVector4()), 0.0f,
                new Vector2(0.0f, 0.0f), _Scale * scale, SpriteEffects.None, 0.0f);
     //}
 }
Пример #34
0
 void addNode(float size, Color color, Vector3 position)
 {
     addParticle(position, size, color.ToVector4(), 1.0f);
 }
Пример #35
0
 Vector4 IVector4Converter <Color> .ToVector4(Color value)
 {
     return(value.ToVector4());
 }
Пример #36
0
        public void RegenTerrain(GraphicsDevice device, WorldState world, Blueprint blueprint)
        {
            if (VertexBuffer != null)
            {
                IndexBuffer.Dispose();
                BladeIndexBuffer.Dispose();
                VertexBuffer.Dispose();
            }

            /** Convert rectangle to world units **/
            var quads = Size.Width;

            var quadWidth  = WorldSpace.GetWorldFromTile((float)Size.Width / (float)quads);
            var quadHeight = WorldSpace.GetWorldFromTile((float)Size.Height / (float)quads);
            var numQuads   = quads * quads;

            TerrainVertex[] Geom         = new TerrainVertex[numQuads * 4];
            int[]           Indexes      = new int[numQuads * 6];
            int[]           BladeIndexes = new int[numQuads * 6];
            NumPrimitives = (numQuads * 2);

            int geomOffset   = 0;
            int indexOffset  = 0;
            int bindexOffset = 0;

            var offsetX = WorldSpace.GetWorldFromTile(Size.X);
            var offsetY = WorldSpace.GetWorldFromTile(Size.Y);

            for (var y = 0; y < quads; y++)
            {
                for (var x = 0; x < quads; x++)
                {
                    var tl = new Vector3(offsetX + (x * quadWidth), 0.0f, offsetY + (y * quadHeight));
                    var tr = new Vector3(tl.X + quadWidth, 0.0f, tl.Z);
                    var bl = new Vector3(tl.X, 0.0f, tl.Z + quadHeight);
                    var br = new Vector3(tl.X + quadWidth, 0.0f, tl.Z + quadHeight);

                    Indexes[indexOffset++] = geomOffset;
                    Indexes[indexOffset++] = (geomOffset + 1);
                    Indexes[indexOffset++] = (geomOffset + 2);

                    Indexes[indexOffset++] = (geomOffset + 2);
                    Indexes[indexOffset++] = (geomOffset + 3);
                    Indexes[indexOffset++] = geomOffset;

                    short tx = (short)(x + 1), ty = (short)(y + 1);

                    if (blueprint.GetFloor(tx, ty, 1).Pattern == 0 &&
                        (blueprint.GetWall(tx, ty, 1).Segments & (WallSegments.HorizontalDiag | WallSegments.VerticalDiag)) == 0)
                    {
                        BladeIndexes[bindexOffset++] = geomOffset;
                        BladeIndexes[bindexOffset++] = (geomOffset + 1);
                        BladeIndexes[bindexOffset++] = (geomOffset + 2);

                        BladeIndexes[bindexOffset++] = (geomOffset + 2);
                        BladeIndexes[bindexOffset++] = (geomOffset + 3);
                        BladeIndexes[bindexOffset++] = geomOffset;
                    }

                    Color tlCol = Color.Lerp(LightGreen, LightBrown, GrassState[y * quads + x]);
                    Color trCol = Color.Lerp(LightGreen, LightBrown, GrassState[y * quads + ((x + 1) % quads)]);
                    Color blCol = Color.Lerp(LightGreen, LightBrown, GrassState[((y + 1) % quads) * quads + x]);
                    Color brCol = Color.Lerp(LightGreen, LightBrown, GrassState[((y + 1) % quads) * quads + ((x + 1) % quads)]);

                    Geom[geomOffset++] = new TerrainVertex(tl, tlCol.ToVector4(), new Vector2(x * 64, y * 64), GrassState[y * quads + x]);
                    Geom[geomOffset++] = new TerrainVertex(tr, trCol.ToVector4(), new Vector2((x + 1) * 64, y * 64), GrassState[y * quads + ((x + 1) % quads)]);
                    Geom[geomOffset++] = new TerrainVertex(br, brCol.ToVector4(), new Vector2((x + 1) * 64, (y + 1) * 64), GrassState[((y + 1) % quads) * quads + ((x + 1) % quads)]);
                    Geom[geomOffset++] = new TerrainVertex(bl, blCol.ToVector4(), new Vector2(x * 64, (y + 1) * 64), GrassState[((y + 1) % quads) * quads + x]);
                }
            }

            var rand = new Random();

            VertexBuffer = new VertexBuffer(device, typeof(TerrainVertex), Geom.Length, BufferUsage.None);
            VertexBuffer.SetData(Geom);

            IndexBuffer = new IndexBuffer(device, IndexElementSize.ThirtyTwoBits, sizeof(int) * Indexes.Length, BufferUsage.None);
            IndexBuffer.SetData(Indexes);

            BladePrimitives = (bindexOffset / 3);

            BladeIndexBuffer = new IndexBuffer(device, IndexElementSize.ThirtyTwoBits, sizeof(int) * Indexes.Length, BufferUsage.None);
            BladeIndexBuffer.SetData(BladeIndexes);
            GeomLength = Geom.Length;
        }
Пример #37
0
 public override Color OnTileColor(Color inColor)
 {
     return(new Color(Vector4.Lerp(new Vector4(1f, 0.9f, 0.6f, 1f), inColor.ToVector4(), 1f - intensity)));
 }
Пример #38
0
 private Color MulColorByOverlay(Color c)
 {
     return Overlay == Color.White ? c : new Color(c.ToVector4() * Overlay.ToVector4());
 }
        /// <summary>
        /// Draw a list of Lines.
        /// </summary>
        public void Draw(List<RoundLine> roundLines, float lineRadius, Color lineColor, Matrix viewProjMatrix, 
            float time, string techniqueName)
        {
            device.SetVertexBuffer(vb);
            device.Indices = ib;

            viewProjMatrixParameter.SetValue(viewProjMatrix);
            timeParameter.SetValue(time);
            lineColorParameter.SetValue(lineColor.ToVector4());
            lineRadiusParameter.SetValue(lineRadius);
            blurThresholdParameter.SetValue(BlurThreshold);

            if (techniqueName == null)
                effect.CurrentTechnique = effect.Techniques[0];
            else
                effect.CurrentTechnique = effect.Techniques[techniqueName];
            EffectPass pass = effect.CurrentTechnique.Passes[0];
            pass.Apply();

            int iData = 0;
            int numInstancesThisDraw = 0;
            foreach (RoundLine roundLine in roundLines)
            {
                translationData[iData++] = roundLine.P0.X;
                translationData[iData++] = roundLine.P0.Y;
                translationData[iData++] = roundLine.Rho;
                translationData[iData++] = roundLine.Theta;
                numInstancesThisDraw++;

                if (numInstancesThisDraw == numInstances)
                {
                    instanceDataParameter.SetValue(translationData);
                    pass.Apply();
                    device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, numVertices, 0, numPrimitivesPerInstance * numInstancesThisDraw);
                    NumLinesDrawn += numInstancesThisDraw;
                    numInstancesThisDraw = 0;
                    iData = 0;
                }
            }
            if (numInstancesThisDraw > 0)
            {
                instanceDataParameter.SetValue(translationData);
                pass.Apply();
                device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, numVertices, 0, numPrimitivesPerInstance * numInstancesThisDraw);
                NumLinesDrawn += numInstancesThisDraw;
            }
        }
Пример #40
0
 public override void Draw(GameTime gametime)
 {
     m_playerHUD.SetPosition(new Vector2(m_frontCard.X + 46f, m_frontCard.Y + 64f));
     Camera.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.LinearClamp, null, null);
     Camera.Draw(Game.GenericTexture, new Rectangle(0, 0, 1320, 720), Color.Black * BackBufferOpacity);
     m_frontCard.Draw(Camera);
     m_backCard.Draw(Camera);
     m_cancelText.Draw(Camera);
     Camera.GraphicsDevice.SamplerStates[0] = SamplerState.PointClamp;
     if (Game.PlayerStats.IsDead)
     {
         m_tombStoneSprite.Position = new Vector2(m_frontCard.X + 240f, m_frontCard.Y + 280f);
         m_tombStoneSprite.Draw(Camera);
     }
     else
     {
         if (m_playerInAir)
         {
             m_playerSprite.Position = new Vector2(m_frontCard.X + 180f, m_frontCard.Y + 202f);
         }
         else
         {
             m_playerSprite.Position = new Vector2(m_frontCard.X + 160f,
                                                   m_frontCard.Y + 280f - (m_playerSprite.Bounds.Bottom - m_playerSprite.Y));
         }
         m_playerSprite.Draw(Camera);
         Game.ColourSwapShader.Parameters["desiredTint"].SetValue(
             m_playerSprite.GetChildAt(12).TextureColor.ToVector4());
         if (Game.PlayerStats.Class == 7 || Game.PlayerStats.Class == 15)
         {
             Game.ColourSwapShader.Parameters["Opacity"].SetValue(m_playerSprite.Opacity);
             Game.ColourSwapShader.Parameters["ColourSwappedOut1"].SetValue(m_skinColour1.ToVector4());
             Game.ColourSwapShader.Parameters["ColourSwappedIn1"].SetValue(m_lichColour1.ToVector4());
             Game.ColourSwapShader.Parameters["ColourSwappedOut2"].SetValue(m_skinColour2.ToVector4());
             Game.ColourSwapShader.Parameters["ColourSwappedIn2"].SetValue(m_lichColour2.ToVector4());
         }
         else if (Game.PlayerStats.Class == 3 || Game.PlayerStats.Class == 11)
         {
             Game.ColourSwapShader.Parameters["Opacity"].SetValue(m_playerSprite.Opacity);
             Game.ColourSwapShader.Parameters["ColourSwappedOut1"].SetValue(m_skinColour1.ToVector4());
             Game.ColourSwapShader.Parameters["ColourSwappedIn1"].SetValue(Color.Black.ToVector4());
             Game.ColourSwapShader.Parameters["ColourSwappedOut2"].SetValue(m_skinColour2.ToVector4());
             Game.ColourSwapShader.Parameters["ColourSwappedIn2"].SetValue(Color.Black.ToVector4());
         }
         else
         {
             Game.ColourSwapShader.Parameters["Opacity"].SetValue(1);
             Game.ColourSwapShader.Parameters["ColourSwappedOut1"].SetValue(m_skinColour1.ToVector4());
             Game.ColourSwapShader.Parameters["ColourSwappedIn1"].SetValue(m_skinColour1.ToVector4());
             Game.ColourSwapShader.Parameters["ColourSwappedOut2"].SetValue(m_skinColour2.ToVector4());
             Game.ColourSwapShader.Parameters["ColourSwappedIn2"].SetValue(m_skinColour2.ToVector4());
         }
         Camera.End();
         Camera.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, null, null,
                      Game.ColourSwapShader);
         m_playerSprite.GetChildAt(12).Draw(Camera);
         Camera.End();
         Camera.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, null);
         if (Game.PlayerStats.IsFemale)
         {
             m_playerSprite.GetChildAt(13).Draw(Camera);
         }
         m_playerSprite.GetChildAt(15).Draw(Camera);
     }
     m_spellIcon.Position = new Vector2(m_frontCard.X + 380f, m_frontCard.Y + 320f);
     m_spellIcon.Draw(Camera);
     Camera.End();
     base.Draw(gametime);
 }
Пример #41
0
        /* no depth 8000 buf 1M quad
         + 3495.1999
         + 3487.1994
         + 3428.1961
         + 3482.1992
         + 3469.1984
         + 3461.198
         + 3441.1968
         + 3487.1995
         + 3441.1969
         + 3490.1996
         * avg 3468.29838
         * qps 288325.827375902
         * 60fps 4805.43045626503
         * 30fps 9610.86091253006
         *
         * depth 8000 buf 1M quad
         + 1688.0965
         + 1686.0964
         + 1691.0967
         + 1744.0998
         + 1682.0962
         + 1665.0952
         + 1699.0972
         + 1682.0963
         + 1685.0963
         + 1710.0978
         * avg 1693.29684
         * qps 590563.908452106
         * 60fps 9842.7318075351
         * 30fps 19685.4636150702
         *
         * depth 2048 buf 1M quad
         + 2060.1178
         + 2058.1177
         + 2043.1169
         + 2053.1175
         + 2031.1161
         + 2032.1162
         + 2042.1168
         + 2043.1169
         + 2071.1185
         + 2021.1156
         * avg 2045.517
         * qps 488873.961937251
         * 60fps 8147.89936562085
         * 30fps 16295.7987312417
         *
         * depth 4096 buf 4096 quad
         + 9.0006
         + 8.0004
         + 9.0005
         + 7.0004
         + 8.0005
         + 7.0004
         + 13.0008
         + 13.0007
         + 8.0004
         + 12.0007
         * avg 9.40054
         * qps 435719.650147757
         * 60fps 7261.99416912929
         * 30fps 14523.9883382586
         */

        public void DrawSprite(Texture2D Tex, Rectangle area, Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, Color c0, Color c1, Color c2, Color c3, int rt90 = 0, int flips = 0)
        {
            if (q == BatchSize)
            {
                Flush();
            }
            float w  = Tex.Width;
            float h  = Tex.Height;
            var   uv = new Vector2[5];

            uv[0] = new Vector2(area.X / w, area.Y / h);
            uv[1] = new Vector2((area.X + area.Width) / w, area.Y / h);
            uv[2] = new Vector2((area.X + area.Width) / w, (area.Y + area.Height) / h);
            uv[3] = new Vector2(area.X / w, (area.Y + area.Height) / h);
            if ((flips & 1) != 0)
            { //flip horizontally
                w       = uv[0].X;
                h       = uv[3].X;
                uv[0].X = uv[1].X;
                uv[1].X = w;
                uv[3].X = uv[2].X;
                uv[2].X = h;
            }
            if ((flips & 2) != 0)
            { //flip vertically
                w       = uv[0].Y;
                h       = uv[1].Y;
                uv[0].Y = uv[3].Y;
                uv[3].Y = w;
                uv[1].Y = uv[2].Y;
                uv[2].Y = h;
            }
            for (var i = 0; i < (rt90 & 3); i++) //& 3 or % 4 should work
            {                                    //rotate clockwise
                uv[4] = uv[3];
                uv[3] = uv[2];
                uv[2] = uv[1];
                uv[1] = uv[0];
                uv[0] = uv[4];
            }

            //fx.Parameters["VertexA"].SetValue(p0);
            //fx.Parameters["VertexB"].SetValue(p1);
            //fx.Parameters["VertexC"].SetValue(p2);
            //fx.Parameters["VertexD"].SetValue(p3);
            quadBuf[q * 8].X     = p0.X;
            quadBuf[q * 8].Y     = p0.Y;
            quadBuf[q * 8].Z     = p1.X;
            quadBuf[q * 8].W     = p1.Y;
            quadBuf[q * 8 + 1].X = p2.X;
            quadBuf[q * 8 + 1].Y = p2.Y;
            quadBuf[q * 8 + 1].Z = p3.X;
            quadBuf[q * 8 + 1].W = p3.Y;

            //fx.Parameters["UVA"].SetValue(uv[0]);
            //fx.Parameters["UVB"].SetValue(uv[1]);
            //fx.Parameters["UVC"].SetValue(uv[2]);
            //fx.Parameters["UVD"].SetValue(uv[3]);
            quadBuf[q * 8 + 2].X = uv[0].X;
            quadBuf[q * 8 + 2].Y = uv[0].Y;
            quadBuf[q * 8 + 2].Z = uv[1].X;
            quadBuf[q * 8 + 2].W = uv[1].Y;
            quadBuf[q * 8 + 3].X = uv[2].X;
            quadBuf[q * 8 + 3].Y = uv[2].Y;
            quadBuf[q * 8 + 3].Z = uv[3].X;
            quadBuf[q * 8 + 3].W = uv[3].Y;

            //fx.Parameters["GouraudA"].SetValue(c0.ToVector4());
            //fx.Parameters["GouraudB"].SetValue(c1.ToVector4());
            //fx.Parameters["GouraudC"].SetValue(c2.ToVector4());
            //fx.Parameters["GouraudD"].SetValue(c3.ToVector4());
            var col = c0.ToVector4();

            quadBuf[q * 8 + 4].X = col.X;
            quadBuf[q * 8 + 4].Y = col.Y;
            quadBuf[q * 8 + 4].Z = col.Z;
            quadBuf[q * 8 + 4].W = col.W;
            col = c1.ToVector4();
            quadBuf[q * 8 + 5].X = col.X;
            quadBuf[q * 8 + 5].Y = col.Y;
            quadBuf[q * 8 + 5].Z = col.Z;
            quadBuf[q * 8 + 5].W = col.W;
            col = c2.ToVector4();
            quadBuf[q * 8 + 6].X = col.X;
            quadBuf[q * 8 + 6].Y = col.Y;
            quadBuf[q * 8 + 6].Z = col.Z;
            quadBuf[q * 8 + 6].W = col.W;
            col = c3.ToVector4();
            quadBuf[q * 8 + 7].X = col.X;
            quadBuf[q * 8 + 7].Y = col.Y;
            quadBuf[q * 8 + 7].Z = col.Z;
            quadBuf[q * 8 + 7].W = col.W;

            //fx.Parameters["Tex"].SetValue(Tex);
            //fx.CurrentTechnique.Passes[2].Apply();


            var pts = new Vector3[4];

            pts[0] = p0;
            pts[1] = p1;
            pts[2] = p2;
            pts[3] = p3;


            var center = AvgVertex3(p0, p1, p2, p3);

            clocker.center = center;
            System.Array.Sort(pts, clocker); //untwist

            var quadv = ((float)q) / BatchSize + 1f / (BatchSize * 2);

            q++;

            for (int i = 0; i < 4; i++)
            { //check for concave and draw the encompassing triangle
                var v0 = pts[i];
                var v1 = pts[(1 + i) % 4];
                var v2 = pts[(2 + i) % 4];
                var v3 = pts[(3 + i) % 4];
                if (ptInTriangle2D(v3, v0, v1, v2))
                {
                    //v3 is inside the triangle made by the others
                    verts[v].Position.X              = v0.X;
                    verts[v].Position.Y              = v0.Y;
                    verts[v].Position.Z              = v0.Z;
                    verts[v].TextureCoordinate.X     = 0;
                    verts[v].TextureCoordinate.Y     = quadv;
                    verts[v + 1].Position.X          = v1.X;
                    verts[v + 1].Position.Y          = v1.Y;
                    verts[v + 1].Position.Z          = v1.Z;
                    verts[v + 1].TextureCoordinate.X = 0;
                    verts[v + 1].TextureCoordinate.Y = quadv;
                    verts[v + 2].Position.X          = v2.X;
                    verts[v + 2].Position.Y          = v2.Y;
                    verts[v + 2].Position.Z          = v2.Z;
                    verts[v + 2].TextureCoordinate.X = 0;
                    verts[v + 2].TextureCoordinate.Y = quadv;
                    indecies[t * 3]     = (short)v;
                    indecies[t * 3 + 1] = (short)(v + 1);
                    indecies[t * 3 + 2] = (short)(v + 2);
                    v += 3;
                    t++;
                    return; //my work here is done
                }
            }

            verts[v].Position.X              = pts[0].X;
            verts[v].Position.Y              = pts[0].Y;
            verts[v].Position.Z              = pts[0].Z;
            verts[v].TextureCoordinate.X     = 0;
            verts[v].TextureCoordinate.Y     = quadv;
            verts[v + 1].Position.X          = pts[1].X;
            verts[v + 1].Position.Y          = pts[1].Y;
            verts[v + 1].Position.Z          = pts[1].Z;
            verts[v + 1].TextureCoordinate.X = 0;
            verts[v + 1].TextureCoordinate.Y = quadv;
            verts[v + 2].Position.X          = pts[2].X;
            verts[v + 2].Position.Y          = pts[2].Y;
            verts[v + 2].Position.Z          = pts[2].Z;
            verts[v + 2].TextureCoordinate.X = 0;
            verts[v + 2].TextureCoordinate.Y = quadv;
            verts[v + 3].Position.X          = pts[3].X;
            verts[v + 3].Position.Y          = pts[3].Y;
            verts[v + 3].Position.Z          = pts[3].Z;
            verts[v + 3].TextureCoordinate.X = 0;
            verts[v + 3].TextureCoordinate.Y = quadv;
            indecies[t * 3]     = (short)v;
            indecies[t * 3 + 1] = (short)(v + 1);
            indecies[t * 3 + 2] = (short)(v + 2);
            indecies[t * 3 + 3] = (short)v;
            indecies[t * 3 + 4] = (short)(v + 2);
            indecies[t * 3 + 5] = (short)(v + 3);
            v += 4;
            t += 2;
        }
        /// <summary>
        /// Render car model with this seperate method because we
        /// render it in 2 steps, first the solid stuff, then the alpha glass.
        /// We also rotate the wheels around :)
        /// </summary>
        /// <param name="shadowCarMode">In the shadow car mode we render
        /// everything (including wheels and glass) with a special ShadowCar
        /// shader, that is very transparent. Used for the shadow car when
        /// playing that shows how we drove the last time.</param>
        /// <param name="renderMatrix">Render matrix for the car</param>
        public void RenderCar(bool shadowCarMode, Matrix renderMatrix)
        {
            // Multiply object matrix by render matrix, result is used multiple
            // times here.
            renderMatrix = objectMatrix * renderMatrix;

            // Do we just want to render the shadow car? Then do this in a
            // simpified way here instead of messing with the already complicated
            // code below.
            if (shadowCarMode)
            {
                // Start shadow car shader
                ShaderEffect simpleShader = ShaderEffect.simple;
                simpleShader.Render(
                    "ShadowCar",
                    delegate
                    {
                        int wheelNumber = 0;
                        // And just render all meshes with it!
                        for (int meshNum = 0; meshNum < xnaModel.Meshes.Count; meshNum++)
                        {
                            ModelMesh mesh = xnaModel.Meshes[meshNum];

                            Matrix meshMatrix = transforms[mesh.ParentBone.Index];

                            // Only the wheels have 2 mesh parts (gummi and chrome)
                            if (mesh.MeshParts.Count == 2)
                            {
                                wheelNumber++;
                                meshMatrix =
                                    Matrix.CreateRotationX(
                                    // Rotate left 2 wheels forward, the other 2 backward!
                                    (wheelNumber == 2 || wheelNumber == 4 ? 1 : -1) *
                                    SpeedyRacerManager.Player.CarWheelPos) *
                                    meshMatrix;
                            } // if (mesh.MeshParts.Count)

                            // Assign world matrix
                            BaseGame.WorldMatrix =
                                meshMatrix *
                                renderMatrix;

                            // Set all matrices
                            simpleShader.SetParameters();
                            simpleShader.Update();

                            // And render (must be done without mesh.Draw, which would just
                            // use the original shaders for the model)
                            for (int partNum = 0; partNum < mesh.MeshParts.Count; partNum++)
                            {
                                ModelMeshPart part = mesh.MeshParts[partNum];
                                // Make sure vertex declaration is correct
                                BaseGame.Device.VertexDeclaration = part.VertexDeclaration;
                                // Set vertex buffer and index buffer
                                BaseGame.Device.Vertices[0].SetSource(
                                    mesh.VertexBuffer, part.StreamOffset, part.VertexStride);
                                BaseGame.Device.Indices = mesh.IndexBuffer;

                                // And render all primitives
                                BaseGame.Device.DrawIndexedPrimitives(
                                    PrimitiveType.TriangleList,
                                    part.BaseVertex, 0, part.NumVertices,
                                    part.StartIndex, part.PrimitiveCount);
                            } // for
                        } // for
                    });

                // And get outta here
                return;
            } // if

            // Usually use default color values
            Color carAmbientColor = new Color(100, 100, 100),
                carDiffuseColor = Material.DefaultDiffuseColor;
            EffectTechnique remCurrentTechnique = null;
            for (int alphaPass = 0; alphaPass < 2; alphaPass++)
            {
                int wheelNumber = 0;

                int effectParameterIndex = 0;
                int effectTechniqueIndex = 0;

                for (int meshNum = 0; meshNum < xnaModel.Meshes.Count; meshNum++)
                {
                    ModelMesh mesh = xnaModel.Meshes[meshNum];
                    bool dontRender = false;

                    for (int effectNum = 0; effectNum < mesh.Effects.Count; effectNum++)
                    {
                        Effect effect = mesh.Effects[effectNum];
                        if (effectNum == 0)
                            remCurrentTechnique = effect.CurrentTechnique;

                        // Find out if this is ReflectionSimpleGlass.fx,
                        // NormalMapping.fx will also use reflection, but the techniques
                        // are named in another way (SpecularWithReflection, etc.)
                        if (cachedIsReflectionSpecularTechnique[effectTechniqueIndex++])
                        {
                            if (alphaPass == 0)
                            {
                                dontRender = true;
                                effectParameterIndex += 7;
                                break;
                            } // if (alphaPass)

                            // Skip the first 3 effect parameters
                            effectParameterIndex += 3;
                        } // if (effect.CurrentTechnique.Name.Contains)
                        else
                        {
                            if (alphaPass == 1)
                            {
                                dontRender = true;
                                effectParameterIndex += 7;
                                break;
                            } // if (alphaPass)

                            // To improve performance we only have to set this when it changes!
                            // Doesn't do much, because this eats only 10% performance,
                            // 5-10% are the matrices below and most of the performance is
                            // just rendering the car with Draw!

                            // Skip texture, not used here.
                            effectParameterIndex++;

                            // Set ambient and diffuse colors
                            cachedEffectParameters[effectParameterIndex++].SetValue(
                                carAmbientColor.ToVector4());
                            cachedEffectParameters[effectParameterIndex++].SetValue(
                                carDiffuseColor.ToVector4());
                        } // else

                        Matrix meshMatrix = transforms[mesh.ParentBone.Index];

                        // Only the wheels have 2 mesh parts (gummi and chrome)
                        if (mesh.MeshParts.Count == 2)
                        {
                            wheelNumber++;
                            meshMatrix =
                                Matrix.CreateRotationX(
                                // Rotate left 2 wheels forward, the other 2 backward!
                                (wheelNumber == 2 || wheelNumber == 4 ? 1 : -1) *
                                SpeedyRacerManager.Player.CarWheelPos) *
                                meshMatrix;
                        } // if (mesh.MeshParts.Count)

                        // Assign world matrix
                        BaseGame.WorldMatrix =
                            meshMatrix *
                            renderMatrix;

                        // Set matrices
                        //effect.Parameters["world"].SetValue(
                        cachedEffectParameters[effectParameterIndex++].SetValue(
                            BaseGame.WorldMatrix);

                        // These values should only be set once every frame (see above)!
                        // to improve performance again, also we should access them
                        // with EffectParameter and not via name!
                        // But since we got only 1 car it doesn't matter so much ..
                        cachedEffectParameters[effectParameterIndex++].SetValue(
                            BaseGame.ViewProjectionMatrix);
                        cachedEffectParameters[effectParameterIndex++].SetValue(
                            BaseGame.InverseViewMatrix);
                        // Set light direction
                        cachedEffectParameters[effectParameterIndex++].SetValue(
                            BaseGame.LightDirection);
                    } // foreach (effect)

                    // Render
                    if (dontRender == false)
                        mesh.Draw();
                } // foreach (mesh)
            } // for (alphaPass)
        }
Пример #43
0
        /// <summary>
        /// Render the terrain
        /// </summary>
        /// <param name="device"></param>
        /// <param name="world"></param>
        public override void Draw(GraphicsDevice device, WorldState world)
        {
            if (VertexBuffer == null)
            {
                return;
            }
            Effect.Parameters["LightGreen"].SetValue(LightGreen.ToVector4());
            Effect.Parameters["DarkGreen"].SetValue(DarkGreen.ToVector4());
            Effect.Parameters["DarkBrown"].SetValue(DarkBrown.ToVector4());
            Effect.Parameters["LightBrown"].SetValue(LightBrown.ToVector4());
            Effect.Parameters["ScreenSize"].SetValue(new Vector2(device.Viewport.Width, device.Viewport.Height) / 2f);

            var offset = -world.WorldSpace.GetScreenOffset();

            world._3D.ApplyCamera(Effect);
            var worldmat = Matrix.Identity * Matrix.CreateTranslation(0, ((world.Zoom == WorldZoom.Far)?-5:((world.Zoom == WorldZoom.Medium)?-4:-3)) * (20 / 522f), 0);

            Effect.Parameters["World"].SetValue(worldmat);

            Effect.Parameters["DiffuseColor"].SetValue(new Vector4(world.OutsideColor.R / 255f, world.OutsideColor.G / 255f, world.OutsideColor.B / 255f, 1.0f));

            device.SetVertexBuffer(VertexBuffer);
            device.Indices = IndexBuffer;

            Effect.CurrentTechnique = Effect.Techniques["DrawBase"];
            foreach (var pass in Effect.CurrentTechnique.Passes)
            {
                pass.Apply();
                device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, NumPrimitives);
            }

            int   grassScale;
            float grassDensity;

            switch (world.Zoom)
            {
            case WorldZoom.Far:
                grassScale   = 4;
                grassDensity = 0.56f;
                break;

            case WorldZoom.Medium:
                grassScale   = 2;
                grassDensity = 0.50f;
                break;

            default:
                grassScale   = 1;
                grassDensity = 0.43f;
                break;
            }

            grassDensity *= GrassDensityScale;

            if (BladePrimitives > 0)
            {
                Effect.CurrentTechnique = Effect.Techniques["DrawBlades"];
                int grassNum = (int)Math.Ceiling(GrassHeight / (float)grassScale);

                var rts = device.GetRenderTargets();
                if (rts.Length > 1)
                {
                    device.SetRenderTarget((RenderTarget2D)rts[0].RenderTarget);
                }
                device.Indices = BladeIndexBuffer;
                for (int i = 0; i < grassNum; i++)
                {
                    Effect.Parameters["World"].SetValue(Matrix.Identity * Matrix.CreateTranslation(0, i * (20 / 522f) * grassScale, 0));
                    Effect.Parameters["GrassProb"].SetValue(grassDensity * ((grassNum - (i / (2f * grassNum))) / (float)grassNum));
                    offset += new Vector2(0, 1);
                    Effect.Parameters["ScreenOffset"].SetValue(offset);
                    foreach (var pass in Effect.CurrentTechnique.Passes)
                    {
                        pass.Apply();
                        device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, BladePrimitives);
                    }
                }
                device.SetRenderTargets(rts);
            }
        }
Пример #44
0
 //Set Color
 public void setColor(Color color)
 {
     this.color = color.ToVector4();
 }
Пример #45
0
        public static void DrawLine(SpriteBatch spriteBatch, Vector2 start, Vector2 end, Color color)
        {
            float   num            = Vector2.Distance(start, end);
            Vector2 vector         = (end - start) / num;
            Vector2 value          = start;
            Vector2 screenPosition = Main.screenPosition;
            float   rotation       = vector.ToRotation();

            for (float num2 = 0f; num2 <= num; num2 += 4f)
            {
                float num3 = num2 / num;
                spriteBatch.Draw(Main.blackTileTexture, value - screenPosition, null, new Color(new Vector4(num3, num3, num3, 1f) * color.ToVector4()), rotation, Vector2.Zero, 0.25f, SpriteEffects.None, 0f);
                value = start + num2 * vector;
            }
        }
Пример #46
0
 public static Color clone(this Color t)
 {
     return(new Color(t.ToVector4()));
 }
Пример #47
0
 public DirectionalLight(Vector3 dir, Color color)
 {
     Direction = dir;
     Color     = color.ToVector4();
 }
Пример #48
0
        /// <summary>
        /// Draws a filled Circle
        /// </summary>
        /// <param name="x">Position X</param>
        /// <param name="y">Position Y</param>
        /// <param name="rad">Radius</param>
        /// <param name="rotate">Rotation 0 - 360</param>
        /// <param name="type">Circle Type</param>
        /// <param name="smoothing">Smooth Antialiasing</param>
        /// <param name="resolution">Real smooth value</param>
        /// <param name="color">Color</param>
        public static void DrawCircleFilled(float x, float y, float rad, float rotate, CircleType type, bool smoothing, int resolution, Color color)
        {
            VertexBuffer vertices = new VertexBuffer(
                Drawing.Direct3DDevice, Utilities.SizeOf <Vector4>() * 2 * (resolution + 4), Usage.WriteOnly, VertexFormat.Diffuse | VertexFormat.PositionRhw, Pool.Default);

            double angle = rotate * Math.PI / 180d;
            double pi    = 0.0d;

            if (type == CircleType.Full)
            {
                pi = Math.PI;                                 // Full circle
            }
            if (type == CircleType.Half)
            {
                pi = Math.PI / 2d;                               // 1/2 circle
            }
            if (type == CircleType.Quarter)
            {
                pi = Math.PI / 4d;                               // 1/4 circle
            }
            List <Vector4> data = new List <Vector4>(new []
            {
                new Vector4(x, y, 0f, 1f), color.ToVector4()
            });

            for (int i = 1; i < resolution + 4; i++)
            {
                float x1 = (float)(x - rad * Math.Cos(pi * ((i - 1) / (resolution / 2.0f))));
                float y1 = (float)(y - rad * Math.Sin(pi * ((i - 1) / (resolution / 2.0f))));
                data.AddRange(new[]
                {
                    new Vector4(x1, y1, 0f, 1.0f), color.ToVector4()
                });
            }

            // Rotate matrix
            int res = 2 * resolution + 4;

            for (int i = 0; i < res; i = i + 2)
            {
                data[i] = new Vector4((float)(x + Math.Cos(angle) * (data[i].X - x) - Math.Sin(angle) * (data[i].Y - y)),
                                      (float)(y + Math.Sin(angle) * (data[i].X - x) + Math.Cos(angle) * (data[i].Y - y)),
                                      data[i].Z, data[i].W);
            }

            vertices.Lock(0, Utilities.SizeOf <Vector4>() * 2 * (resolution + 4), LockFlags.None).WriteRange(data.ToArray());
            vertices.Unlock();

            VertexElement[] vertexElements =
            {
                new VertexElement(
                    0,                                                                                       0, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.Position, 0),
                new VertexElement(
                    0,                                                                                      16, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.Color, 0),
                VertexElement.VertexDeclarationEnd
            };

            VertexDeclaration vertexDeclaration = new VertexDeclaration(Drawing.Direct3DDevice, vertexElements);

            if (smoothing)
            {
                Drawing.Direct3DDevice.SetRenderState(RenderState.MultisampleAntialias, true);
                Drawing.Direct3DDevice.SetRenderState(RenderState.AntialiasedLineEnable, true);
            }
            else
            {
                Drawing.Direct3DDevice.SetRenderState(RenderState.MultisampleAntialias, false);
                Drawing.Direct3DDevice.SetRenderState(RenderState.AntialiasedLineEnable, false);
            }

            var olddec = Drawing.Direct3DDevice.VertexDeclaration;

            Drawing.Direct3DDevice.SetStreamSource(0, vertices, 0, Utilities.SizeOf <Vector4>() * 2);
            Drawing.Direct3DDevice.VertexDeclaration = vertexDeclaration;
            Drawing.Direct3DDevice.DrawPrimitives(PrimitiveType.TriangleFan, 0, resolution);
            Drawing.Direct3DDevice.VertexDeclaration = olddec;

            vertexDeclaration.Dispose();
            vertices.Dispose();
        }
Пример #49
0
        public void CreateShootBullet(Vector3 InitPos, Vector3 DirBullet, Color BulletColor)
        {
            if (BulletID == 20)
                return;

            GeometryNode ShootBullet = new GeometryNode("ShootBullet" + BulletID++);

            ShootBullet.Model = BulletModel;

            BulletrMat.Diffuse = BulletColor.ToVector4();

            ShootBullet.Material = BulletrMat;
            ShootBullet.Physics.Interactable = true;
            ShootBullet.Physics.Collidable = true;
            ShootBullet.Physics.Shape = GoblinXNA.Physics.ShapeType.Box;
            ShootBullet.Physics.Mass = 60f;
            ShootBullet.Physics.MaterialName = "Bullet";
            ShootBullet.AddToPhysicsEngine = true;

            // Assign the initial velocity to this shooting box
            ShootBullet.Physics.InitialLinearVelocity = new Vector3(DirBullet.X * 80, DirBullet.Y * 80, DirBullet.Z * 50);

            TransformNode BulletTrans = new TransformNode();
            BulletTrans.Translation = InitPos;

            groundMarkerNode.AddChild(BulletTrans);
            BulletTrans.AddChild(ShootBullet);
        }
Пример #50
0
 public override Color OnTileColor(Color inColor)
 {
     return(new Color(Vector4.Lerp(inColor.ToVector4(), Vector4.One, this._fadeOpacity * 0.5f)));
 }
Пример #51
0
 public override Color OnTileColor(Color inColor)
 {
     Vector4 value = inColor.ToVector4();
     return new Color(Vector4.Lerp(value, Vector4.One, this._fadeOpacity * 0.5f));
 }
Пример #52
0
        public void LoadObjectPlacement(FbnBinary fbn)
        {
            if (fbn.HitTriggers != null)
            {
                LoadFieldItems(hitTriggersListBox, fbn.HitTriggers, "Hit trigger {0}",
                               (entry, name) => new SceneNode(name)
                {
                    Translation = entry.Center,
                    Drawable    = new CubePrimitive(sHitTriggerColor.ToVector4()),
                },
                               (entry, node) => node.Translation = entry.Center);
            }

            if (fbn.Entrances != null)
            {
                LoadFieldItems(entrancesListBox, fbn.Entrances, "Entrance {0}",
                               (entry, name) => new SceneNode(name)
                {
                    Translation = entry.Position,
                    Drawable    = new CubePrimitive(sEntranceColor.ToVector4())
                },
                               (entry, node) => node.Translation = entry.Position);
            }

            if (fbn.Block8Entries != null)
            {
                LoadFieldItems(type8EntriesListBox, fbn.Block8Entries, "Entry {0}", null, null);
            }

            if (fbn.Block9Entries != null)
            {
                LoadFieldItems(type9EntriesListBox, fbn.Block9Entries, "Entry {0}",
                               (entry, name) => new SceneNode(name)
                {
                    Translation = entry.Position,
                    Drawable    = new CubePrimitive(sBlock9EntryColor.ToVector4())
                },
                               (entry, node) => node.Translation = entry.Position);
            }

            if (fbn.Block10Entries != null)
            {
                LoadFieldItems(type10EntriesListBox, fbn.Block10Entries, "Entry {0}", null, null);
            }

            if (fbn.Block11Entries != null)
            {
                LoadFieldItems(type11EntriesListBox, fbn.Block11Entries, "Entry {0}", null, null);
            }

            if (fbn.MessageTriggers != null)
            {
                // TODO: handle multiple positions
                LoadFieldItems(msgTriggersListBox, fbn.MessageTriggers, "Message trigger {0}",
                               (entry, name) => new SceneNode(name)
                {
                    Translation = entry.Positions[0],
                    Drawable    = new CubePrimitive(sMessageTriggerColor.ToVector4())
                },
                               (entry, node) => node.Translation = entry.Positions[0]);
            }

            if (fbn.Block18Entries != null)
            {
                LoadFieldItems(type18EntriesListBox, fbn.Block18Entries, "Entry {0}",
                               (entry, name) => new SceneNode(name)
                {
                    Translation = entry.Position,
                    Drawable    = new CubePrimitive(sBlock18EntryColor.ToVector4())
                },
                               (entry, node) => node.Translation = entry.Position);
            }

            if (fbn.Block19Entries != null)
            {
                LoadFieldItems(type19EntriesListBox, fbn.Block19Entries, "Entry {0}",
                               (entry, name) => new SceneNode(name)
                {
                    Translation = entry.Center,
                    Drawable    = new CubePrimitive(sBlock19EntryColor.ToVector4())
                },
                               (entry, node) => node.Translation = entry.Center);
            }

            if (fbn.Block22Entries != null)
            {
                LoadFieldItems(type22EntriesListBox, fbn.Block22Entries, "Entry {0}",
                               (entry, name) => new SceneNode(name)
                {
                    Translation = entry.Center,
                    Drawable    = new CubePrimitive(sBlock22EntryColor.ToVector4())
                },
                               (entry, node) => node.Translation = entry.Center);
            }
        }
Пример #53
0
 public override Color OnTileColor(Color inColor)
 {
     return new Color(Vector4.Lerp(inColor.ToVector4(), Vector4.One, _fadeOpacity * 0.5f));
 }
Пример #54
0
 public FrostLegionShader(Color primaryColor, Color secondaryColor)
 {
     this.\u002Ector();
     this._primaryColor   = primaryColor.ToVector4();
     this._secondaryColor = secondaryColor.ToVector4();
 }
Пример #55
0
 /// <summary>
 /// Draws line between p0 and p1
 /// </summary>
 /// <param name="p0"></param>
 /// <param name="p1"></param>
 /// <param name="color"></param>
 public void DrawLine(Vector2 p0, Vector2 p1, Color color)
 {
     vertexDataAccum.Add(new LineVertex() { Pos = new Vector3(p0, 0), Color = color.ToVector4() });
     vertexDataAccum.Add(new LineVertex() { Pos = new Vector3(p1, 0), Color = color.ToVector4() });
     //DrawLine( p0, p1, color, Matrix.Identity );
 }
Пример #56
0
        private void Draw(SpriteBatch spriteBatch, bool editing, bool back = true, Effect damageEffect = null)
        {
            if (prefab.sprite == null)
            {
                return;
            }
            if (editing)
            {
                if (!HasBody && !ShowStructures)
                {
                    return;
                }
                if (HasBody && !ShowWalls)
                {
                    return;
                }
            }
            else if (HiddenInGame)
            {
                return;
            }

            Color color = IsHighlighted ? GUI.Style.Orange : spriteColor;

            if (IsSelected && editing)
            {
                //color = Color.Lerp(color, Color.Gold, 0.5f);
                color = spriteColor;

                Vector2 rectSize = rect.Size.ToVector2();
                if (BodyWidth > 0.0f)
                {
                    rectSize.X = BodyWidth;
                }
                if (BodyHeight > 0.0f)
                {
                    rectSize.Y = BodyHeight;
                }

                Vector2 bodyPos = WorldPosition + BodyOffset;

                GUI.DrawRectangle(spriteBatch, new Vector2(bodyPos.X, -bodyPos.Y), rectSize.X, rectSize.Y, BodyRotation, Color.White,
                                  thickness: Math.Max(1, (int)(2 / Screen.Selected.Cam.Zoom)));
            }

            Vector2 drawOffset = Submarine == null ? Vector2.Zero : Submarine.DrawPosition;

            float depth = GetDrawDepth();

            Vector2 textureOffset = this.textureOffset;

            if (FlippedX)
            {
                textureOffset.X = -textureOffset.X;
            }
            if (FlippedY)
            {
                textureOffset.Y = -textureOffset.Y;
            }

            if (back && damageEffect == null)
            {
                if (Prefab.BackgroundSprite != null)
                {
                    Vector2 dropShadowOffset = Vector2.Zero;
                    if (UseDropShadow)
                    {
                        dropShadowOffset = DropShadowOffset;
                        if (dropShadowOffset == Vector2.Zero)
                        {
                            if (Submarine == null)
                            {
                                dropShadowOffset = Vector2.UnitY * 10.0f;
                            }
                            else
                            {
                                dropShadowOffset = IsHorizontal ?
                                                   new Vector2(0.0f, Math.Sign(Submarine.HiddenSubPosition.Y - Position.Y) * 10.0f) :
                                                   new Vector2(Math.Sign(Submarine.HiddenSubPosition.X - Position.X) * 10.0f, 0.0f);
                            }
                        }
                        dropShadowOffset.Y = -dropShadowOffset.Y;
                    }

                    SpriteEffects oldEffects = Prefab.BackgroundSprite.effects;
                    Prefab.BackgroundSprite.effects ^= SpriteEffects;

                    Point backGroundOffset = new Point(
                        MathUtils.PositiveModulo((int)-textureOffset.X, Prefab.BackgroundSprite.SourceRect.Width),
                        MathUtils.PositiveModulo((int)-textureOffset.Y, Prefab.BackgroundSprite.SourceRect.Height));

                    Prefab.BackgroundSprite.DrawTiled(
                        spriteBatch,
                        new Vector2(rect.X + drawOffset.X, -(rect.Y + drawOffset.Y)),
                        new Vector2(rect.Width, rect.Height),
                        color: Prefab.BackgroundSpriteColor,
                        textureScale: TextureScale * Scale,
                        startOffset: backGroundOffset,
                        depth: Math.Max(Prefab.BackgroundSprite.Depth + (ID % 255) * 0.000001f, depth + 0.000001f));

                    if (UseDropShadow)
                    {
                        Prefab.BackgroundSprite.DrawTiled(
                            spriteBatch,
                            new Vector2(rect.X + drawOffset.X, -(rect.Y + drawOffset.Y)) + dropShadowOffset,
                            new Vector2(rect.Width, rect.Height),
                            color: Color.Black * 0.5f,
                            textureScale: TextureScale * Scale,
                            startOffset: backGroundOffset,
                            depth: (depth + Prefab.BackgroundSprite.Depth) / 2.0f);
                    }

                    Prefab.BackgroundSprite.effects = oldEffects;
                }
            }

            if (back == depth > 0.5f)
            {
                SpriteEffects oldEffects = prefab.sprite.effects;
                prefab.sprite.effects ^= SpriteEffects;

                for (int i = 0; i < Sections.Length; i++)
                {
                    if (damageEffect != null)
                    {
                        float newCutoff = MathHelper.Lerp(0.0f, 0.65f, Sections[i].damage / Prefab.Health);

                        if (Math.Abs(newCutoff - Submarine.DamageEffectCutoff) > 0.01f || color != Submarine.DamageEffectColor)
                        {
                            damageEffect.Parameters["aCutoff"].SetValue(newCutoff);
                            damageEffect.Parameters["cCutoff"].SetValue(newCutoff * 1.2f);
                            damageEffect.Parameters["inColor"].SetValue(color.ToVector4());

                            damageEffect.CurrentTechnique.Passes[0].Apply();

                            Submarine.DamageEffectCutoff = newCutoff;
                            Submarine.DamageEffectColor  = color;
                        }
                    }

                    Point sectionOffset = new Point(
                        Math.Abs(rect.Location.X - Sections[i].rect.Location.X),
                        Math.Abs(rect.Location.Y - Sections[i].rect.Location.Y));

                    if (FlippedX && IsHorizontal)
                    {
                        sectionOffset.X = Sections[i].rect.Right - rect.Right;
                    }
                    if (FlippedY && !IsHorizontal)
                    {
                        sectionOffset.Y = (rect.Y - rect.Height) - (Sections[i].rect.Y - Sections[i].rect.Height);
                    }

                    sectionOffset.X += MathUtils.PositiveModulo((int)-textureOffset.X, prefab.sprite.SourceRect.Width);
                    sectionOffset.Y += MathUtils.PositiveModulo((int)-textureOffset.Y, prefab.sprite.SourceRect.Height);

                    prefab.sprite.DrawTiled(
                        spriteBatch,
                        new Vector2(Sections[i].rect.X + drawOffset.X, -(Sections[i].rect.Y + drawOffset.Y)),
                        new Vector2(Sections[i].rect.Width, Sections[i].rect.Height),
                        color: color,
                        startOffset: sectionOffset,
                        depth: depth,
                        textureScale: TextureScale * Scale);
                }

                foreach (var decorativeSprite in Prefab.DecorativeSprites)
                {
                    if (!spriteAnimState[decorativeSprite].IsActive)
                    {
                        continue;
                    }
                    float   rotation = decorativeSprite.GetRotation(ref spriteAnimState[decorativeSprite].RotationState);
                    Vector2 offset   = decorativeSprite.GetOffset(ref spriteAnimState[decorativeSprite].OffsetState) * Scale;
                    decorativeSprite.Sprite.Draw(spriteBatch, new Vector2(DrawPosition.X + offset.X, -(DrawPosition.Y + offset.Y)), color,
                                                 rotation, decorativeSprite.Scale * Scale, prefab.sprite.effects,
                                                 depth: Math.Min(depth + (decorativeSprite.Sprite.Depth - prefab.sprite.Depth), 0.999f));
                }
                prefab.sprite.effects = oldEffects;
            }

            if (GameMain.DebugDraw && Screen.Selected.Cam.Zoom > 0.5f)
            {
                if (Bodies != null)
                {
                    for (int i = 0; i < Bodies.Count; i++)
                    {
                        Vector2 pos = FarseerPhysics.ConvertUnits.ToDisplayUnits(Bodies[i].Position);
                        if (Submarine != null)
                        {
                            pos += Submarine.Position;
                        }
                        pos.Y = -pos.Y;
                        GUI.DrawRectangle(spriteBatch,
                                          pos,
                                          FarseerPhysics.ConvertUnits.ToDisplayUnits(bodyDebugDimensions[i].X),
                                          FarseerPhysics.ConvertUnits.ToDisplayUnits(bodyDebugDimensions[i].Y),
                                          -Bodies[i].Rotation, Color.White);
                    }
                }

                if (SectionCount > 0 && HasBody)
                {
                    for (int i = 0; i < SectionCount; i++)
                    {
                        if (GetSection(i).damage > 0)
                        {
                            var textPos = SectionPosition(i, true);
                            textPos.Y = -textPos.Y;
                            GUI.DrawString(spriteBatch, textPos, "Damage: " + (int)((GetSection(i).damage / Health) * 100f) + "%", Color.Yellow);
                        }
                    }
                }
            }
        }
Пример #57
0
 public static Color Between(Color col1, Color col2, float val)
 {
     Vector4 v1 = col1.ToVector4(), v2 = col2.ToVector4();
     return new Color(v1 + ((v2 - v1) * val));
 }
Пример #58
0
        public override Color OnTileColor(Color inColor)
        {
            float intensity = this.GetIntensity();

            return(new Color(Vector4.Lerp(new Vector4(0.5f, 0.5f, .5f, 1f), inColor.ToVector4(), 1f - intensity)));
        }
Пример #59
0
 /// <summary>
 /// Multiplies the the specified <see cref="Color"/> with this <see cref="Color"/>.
 /// </summary>
 /// <param name="a">A.</param>
 /// <param name="colour">The colour.</param>
 /// <returns>This <see cref="Color"/> multiplied with the specified <see cref="Color"/>.</returns>
 public static Color Multiply(this Color a, Color colour)
 {
     var aVec = a.ToVector4();
     var bVec = colour.ToVector4();
     return new Color(aVec * bVec);
 }
Пример #60
0
        private void InternalDraw(GraphicsDevice device, Effect effect, int scale, bool useDepth)
        {
            effect.Parameters["BaseTex"].SetValue(Tex);
            effect.Parameters["IndoorsTex"].SetValue(Indoors);

            var fade = FadeProgress ?? 0f;

            effect.Parameters["Color"].SetValue(Tint.ToVector4() * (1 - Math.Abs(fade)));
            effect.Parameters["TimeRate"].SetValue(Math.Max(1, TimeRate) * 0.001f / FSOEnvironment.RefreshRate);

            //Parameters:
            //miny, yrange, fall speed, fall speed variation
            //wind x, wind z, wind variation
            //minx, xrange, minz, zrange
            switch (Mode)
            {
            case ParticleType.SNOW:
                effect.Parameters["Parameters1"].SetValue(new Vector4(Volume.Min.Y, Volume.Max.Y - Volume.Min.Y, 1f, 0.2f));
                effect.Parameters["Parameters2"].SetValue(new Vector4(30f, 10f, 10f, 100f));
                effect.Parameters["Parameters3"].SetValue(new Vector4(Volume.Min.X, Volume.Max.X - Volume.Min.X, Volume.Min.Z, Volume.Max.Z - Volume.Min.Z));
                break;

            case ParticleType.RAIN:
                effect.Parameters["Parameters1"].SetValue(new Vector4(Volume.Min.Y, Volume.Max.Y - Volume.Min.Y, 0.20f, 0.01f));     //0.1f
                effect.Parameters["Parameters2"].SetValue(new Vector4(30f, 10f, 10f, ((FSOEnvironment.Enable3D || Indoors == null)? 0.3f:1f)));
                effect.Parameters["Parameters3"].SetValue(new Vector4(Volume.Min.X, Volume.Max.X - Volume.Min.X, Volume.Min.Z, Volume.Max.Z - Volume.Min.Z));
                break;

            //(deltax, deltay, deltaz, gravity)
            //(deltavar, rotdeltavar, size, sizevel)
            //(duration, fadein, fadeout, sizevar)
            case ParticleType.GENERIC_BOX:
                if (Resource.Parameters == null)
                {
                    Resource.BakeParameters();
                }
                var p = Resource.Parameters;
                effect.Parameters["Parameters1"].SetValue(p[0]);
                effect.Parameters["Parameters2"].SetValue(p[1]);
                effect.Parameters["Parameters3"].SetValue(p[2]);
                effect.Parameters["Parameters4"].SetValue(p[3]);

                effect.Parameters["Frequency"].SetValue(Resource.Frequency);
                effect.Parameters["StopTime"].SetValue(StopTime);
                break;
            }

            effect.CurrentTechnique = effect.Techniques[(int)Mode * 2 + (useDepth?0:1)];

            device.BlendState        = Mode == ParticleType.RAIN ? BlendState.Additive : BlendState.AlphaBlend;
            device.DepthStencilState = useDepth?DepthStencilState.DepthRead:DepthStencilState.None;

            device.SetVertexBuffer(Vertices);
            device.Indices = Indices;

            for (int i = 0; i < scale; i++)
            {
                effect.Parameters["Time"].SetValue(Time + i);
                effect.CurrentTechnique.Passes[0].Apply();
                device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, Primitives);
            }

            device.BlendState        = BlendState.NonPremultiplied;
            device.DepthStencilState = DepthStencilState.Default;
        }