0
\$\begingroup\$

I am building a top down 2D space shooter game with sandbox elements. I am working on the shield for the spaceship now and am not having luck. I am attempting to make a distortion effect shader, but things are not working right.

I either:

  • do not get my spaceship to draw on the screen,
  • spaceship draws but no distortion, or
  • getting random null reference exceptions with the effects.Parameters when setting a value.

Here is my current shader:

sampler inputTexture : register(s0);

float2 DisplacementScroll;
float2 displacement;

texture2D distortion;
sampler2D distortionSampler = sampler_state
{
    Texture = <distortion>;
    MagFilter = Point;
};

float4 PixelShaderFunction(float4 pos : SV_POSITION, float4 color1 : COLOR0, float2 coords: TEXCOORD0) : COLOR0
{
    // Look up the displacement amount.
    displacement = tex2D(distortionSampler, DisplacementScroll + coords / 3);

    // Offset the main texture coordinates.
    coords += displacement * 0.2 - 0.15;

    // Look up into the main texture.
    return tex2D(inputTexture, coords);
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile ps_4_0_level_9_1 PixelShaderFunction();
    }
}

And my C# code:

public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        private Texture2D battlecruiserTexture2D, fighterTexture2D, normalTexture2D;
        private Effect effect;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            graphics.GraphicsProfile = GraphicsProfile.HiDef;
            graphics.PreferredBackBufferWidth = 1920;
            graphics.PreferredBackBufferHeight = 1080;

            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            battlecruiserTexture2D = Content.Load<Texture2D>("Battlecruiser_1");
            fighterTexture2D = Content.Load<Texture2D>("Fighter2-shootSm");
            normalTexture2D = Content.Load<Texture2D>("Normal1");
            effect = Content.Load<Effect>("ShipShader");

            effect.Parameters["distortion"].SetValue(normalTexture2D);
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// game-specific content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();

            float timeInSeconds = (float) gameTime.ElapsedGameTime.TotalSeconds;

            // TODO: Add your update logic here
            effect.Parameters["DisplacementScroll"].SetValue(MoveInCircle(gameTime, 0.1f));

            base.Update(gameTime);
        }

        private Vector2 MoveInCircle(GameTime gameTime, float speed)
        {
            double time = gameTime.TotalGameTime.TotalSeconds * speed;

            float x = (float)Math.Cos(time);
            float y = (float)Math.Sin(time);

            return new Vector2(x, y);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here
            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, effect:effect);
            spriteBatch.Draw(battlecruiserTexture2D, new Vector2(500, 500), Color.White);
            //spriteBatch.Draw(fighterTexture2D, new Vector2(650, 650), Color.Black * 0.5f);
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }

For those that have played Terraria, I am essentially looking for a distortion effect and shield effect like the Celestial Pillars.

https://www.youtube.com/watch?v=hL3x33CIf5Y

Go to 30 seconds in to see the shield around the pillar for an example. Terraria is in XNA so I know this would be possible.

Does anyone know why this is not working properly? Also, why I am getting a null reference exception on the following line even though I use the variable in the shader file?

effect.Parameters["distortion"].SetValue(normalTexture2D);
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

Just a quick update: With the help of a few people in the MonoGame Discord and MonoGame forums, my issue has been resolved. It appears that you must create a sampler of the texture passed to the shader before creating a sampler for any other textures, and all textures must have a sampler. There is a line used at the top of the main function to use the TextureSampler. If that line is removed, it will also break the shader. You can check out the post here: http://community.monogame.net/t/shader-that-works-in-xna-4-0-is-broken-in-monogame/11896

To prevent issues with the possibility of the link dying, the Shader file changed to:

float2 DisplacementScroll;

Texture2D Texture;
sampler TextureSampler 
{
    Texture = <Texture>;
};

Texture2D Displacement;
sampler DisplacementSampler 
{
    Texture = <Displacement>;
};


struct vsOutput
{
    float4 position : SV_Position;
    float4 color : COLOR0;
    float2 texCoord : TEXCOORD0;
};

float4 main(vsOutput input) : COLOR0
{
    // Comment this line out to break the shader!!!
    float4 v =  tex2D(TextureSampler, input.texCoord);


    // Look up the displacement amount.
    float2 displacement = tex2D(DisplacementSampler, DisplacementScroll + input.texCoord / 3).xy;

    // Offset the main texture coordinates.
    input.texCoord += displacement * 0.2 - 0.15;

    // Look up into the main texture.
    return tex2D(TextureSampler, input.texCoord) * input.color;
}


technique Refraction
{
    pass Pass1
    {
        PixelShader = compile ps_4_0 main();
    }
}
\$\endgroup\$
1
\$\begingroup\$

Lord need 50 rep to comment. I will answer here even though it is answered. For posterity so others who may come across this question in search of answers may find a decent set of examples.

With a link to a post on the monogame site with multiple refraction shaders i made.

http://community.monogame.net/t/2d-refraction-shader-example-for-spritebatch/11902

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .