Result of rendering into texture is empty only with shader - c#

I think I am very stupid because I can't figure out what causes the issue in this simplest case.
Project type is Windows OpenGL (on Android the issue also persists).
Here is the shader:
//----------------------------------------------------------------------------
float4 PSTest (float2 TexCoords : TEXCOORD0) : COLOR0
{
float4 color = float4 (1, 0, 0, 1);
return color;
}
//----------------------------------------------------------------------------
Technique Test
{
pass Test
{
PixelShader = compile ps_2_0 PSTest();
}
}
It works fine if I draw it to the screen with the Texture (128x128):
Shader.CurrentTechnique = Shader.Techniques["Test"];
GraphicsDevice.SetRenderTarget (null);
GraphicsDevice.Clear (Color.White);
Batch.Begin (SpriteSortMode.Immediate, BlendState.Opaque,
SamplerState.PointClamp, DepthStencilState.None, null, Shader);
Batch.Draw (Texture, Vector2.Zero, Color.White);
Batch.End();
Now I decide to draw it into render target Output created by code:
new RenderTarget2D (GraphicsDevice, 256, 256, false,
SurfaceFormat.Color, DepthFormat.None);
Draw code:
// Render into Output
Shader.CurrentTechnique = Shader.Techniques["Test"];
GraphicsDevice.SetRenderTarget (Output);
GraphicsDevice.Clear (Color.DimGray);
Batch.Begin (SpriteSortMode.Immediate, BlendState.Opaque,
SamplerState.PointClamp, DepthStencilState.None, null, Shader);
Batch.Draw (Texture, Vector2.Zero, Color.White);
Batch.End();
// Draw Output
GraphicsDevice.SetRenderTarget (null);
GraphicsDevice.Clear (Color.White);
Batch.Begin();
Batch.Draw (Output, Vector2.Zero, Color.White);
Batch.End();
But the result is totally absurd:
I have tried different simplest shaders, SurfaceFormat.HdrBlendable, texture sizes - but nothing helps.
Also I have tried to draw Texture (filled with violet) into render target without shader (then to the screen) and it works fine.
It seems like I have missed some basics thing about shaders in XNA but I can't figure out what it is.

Here is the solution: https://monogame.codeplex.com/discussions/530086. The reason is in the shader's input parameters.

Related

Whirl effect with HLSL, starting from Microsoft SpriteEffects sample

The sample
If you watch the code, I'm interested in refraction.fx, and in void DrawRefractGlacier(GameTime gameTime) function. Here you can notice that the function uses a texture to render water distortion on an image (waterfall.jpg as "distorter image", and glacier.jpg as distorted image).
If you read inside refraction.fx, at the beginning it says:
// Effect uses a scrolling displacement texture to offset the position of the main
// texture. Depending on the contents of the displacement texture, this can give a
// wide range of refraction, rippling, warping, and swirling type effects.
It seems that would be easy to achieve another effect by changing the image. I tried that with an image like this:
I want to achieve the effect of distorting everything around as a rotating whirl, or a spiral. How can I do that?
Some simple sequential screen of how it looks with my texture:
Refraction shader:
// Effect uses a scrolling displacement texture to offset the position of the main
// texture. Depending on the contents of the displacement texture, this can give a
// wide range of refraction, rippling, warping, and swirling type effects.
float2 DisplacementScroll;
float2 angle;
sampler TextureSampler : register(s0);
sampler DisplacementSampler : register(s1);
float2x2 RotationMatrix(float rotation)
{
float c = cos(rotation);
float s = sin(rotation);
return float2x2(c, -s, s ,c);
}
float4 main(float4 color : COLOR0, float2 texCoord : TEXCOORD0) : COLOR0
{
float2 rotated_texcoord = texCoord;
rotated_texcoord -= float2(0.25, 0.25);
rotated_texcoord = mul(rotated_texcoord, RotationMatrix(angle));
rotated_texcoord += float2(0.25, 0.25);
float2 DispScroll = DisplacementScroll;
// Look up the displacement amount.
float2 displacement = tex2D(DisplacementSampler, DispScroll+ texCoord / 3);
// Offset the main texture coordinates.
texCoord += displacement * 0.2 - 0.15;
// Look up into the main texture.
return tex2D(TextureSampler, texCoord) * color;
}
technique Refraction
{
pass Pass1
{
PixelShader = compile ps_2_0 main();
}
}
Its draw call:
void DrawRefractGlacier(GameTime gameTime)
{
// Set an effect parameter to make the
// displacement texture scroll in a giant circle.
refractionEffect.Parameters["DisplacementScroll"].SetValue(
MoveInCircle(gameTime, 0.2f));
// Set the displacement texture.
graphics.GraphicsDevice.Textures[1] = waterfallTexture;
// Begin the sprite batch.
spriteBatch.Begin(0, null, null, null, null, refractionEffect);
// Because the effect will displace the texture coordinates before
// sampling the main texture, the coordinates could sometimes go right
// off the edges of the texture, which looks ugly. To prevent this, we
// adjust our sprite source region to leave a little border around the
// edge of the texture. The displacement effect will then just move the
// texture coordinates into this border region, without ever hitting
// the edge of the texture.
Rectangle croppedGlacier = new Rectangle(32, 32,
glacierTexture.Width - 64,
glacierTexture.Height - 64);
spriteBatch.Draw(glacierTexture,
GraphicsDevice.Viewport.Bounds,
croppedGlacier,
Color.White);
// End the sprite batch.
spriteBatch.End();
}

Drawn quads, lines, points in opentk don't show up right

I've got drawing sprites to work with OpenTK in my 2d game engine now. Only problem I'm having is that custom drawn objects with opengl (anything but sprites really) show up as the background color. Example:
I'm Drawing a 2.4f width black line here. There's also a quad and a point in the example, but they do not overlap anything that's actually visible. The line overlaps the magenta sprite, but the color is just wrong. My question is: Am I missing an OpenGL feature, or doing something horrible wrong?
These are the samples of my project concerning drawing: (you can also find the project on https://github.com/Villermen/HatlessEngine if there's questions about the code)
Initialization:
Window = new GameWindow(windowSize.Width, windowSize.Height);
//OpenGL initialization
GL.Enable(EnableCap.PointSmooth);
GL.Hint(HintTarget.PointSmoothHint, HintMode.Nicest);
GL.Enable(EnableCap.LineSmooth);
GL.Hint(HintTarget.LineSmoothHint, HintMode.Nicest);
GL.Enable(EnableCap.Blend);
GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
GL.ClearColor(Color.Gray);
GL.Enable(EnableCap.Texture2D);
GL.Enable(EnableCap.DepthTest);
GL.DepthFunc(DepthFunction.Lequal);
GL.ClearDepth(1d);
GL.DepthRange(1d, 0d); //does not seem right, but it works (see it as duct-tape)
Every draw cycle:
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
//reset depth and color to be consistent over multiple frames
DrawX.Depth = 0;
DrawX.DefaultColor = Color.Black;
foreach(View view in Resources.Views)
{
CurrentDrawArea = view.Area;
GL.Viewport((int)view.Viewport.Left * Window.Width, (int)view.Viewport.Top * Window.Height, (int)view.Viewport.Right * Window.Width, (int)view.Viewport.Bottom * Window.Height);
GL.MatrixMode(MatrixMode.Projection);
GL.LoadIdentity();
GL.Ortho(view.Area.Left, view.Area.Right, view.Area.Bottom, view.Area.Top, -1f, 1f);
GL.MatrixMode(MatrixMode.Modelview);
//drawing
foreach (LogicalObject obj in Resources.Objects)
{
//set view's coords for clipping?
obj.Draw();
}
}
GL.Flush();
Window.Context.SwapBuffers();
DrawX.Line:
public static void Line(PointF pos1, PointF pos2, Color color, float width = 1)
{
RectangleF lineRectangle = new RectangleF(pos1.X, pos1.Y, pos2.X - pos1.X, pos2.Y - pos1.Y);
if (lineRectangle.IntersectsWith(Game.CurrentDrawArea))
{
GL.LineWidth(width);
GL.Color3(color);
GL.Begin(PrimitiveType.Lines);
GL.Vertex3(pos1.X, pos1.Y, GLDepth);
GL.Vertex3(pos2.X, pos2.Y, GLDepth);
GL.End();
}
}
Edit: If I disable the blendcap before and enable it after drawing the line it does show up with the right color, but I must have it blended.
I forgot to unbind the texture in the texture-drawing method...
GL.BindTexture(TextureTarget.Texture2D, 0);

Compiling shader for MonoGame

I'm using VS 2013 to and trying to get a pixelshader to work properly. I've had this shader working in XNA 4 so I'm pretty certain it's ok.
I'm trying to compile the shader using the 2MGFX tool
Just running
2MGFX.exe AlphaMap.fx AlphaMap.fxg
Works and I get my compiled AlphaMap.fxg file.
However when trying to use/load this file in MonoGame I get:
The MGFX effect is the wrong profile for this platform!
The fix for this seems to be to add /DX11 to the 2MGFX command, but then I get this error instead:
Pixel shader 'PixelShaderFunction' must be SM 4.0 level 9.1 or higher!
Failed to compile the input file 'AlphaMap.fx'!
What am I doing wrong?
Code for shader.
uniform extern texture ScreenTexture;
sampler screen = sampler_state
{
// get the texture we are trying to render.
Texture = <ScreenTexture>;
};
uniform extern texture MaskTexture;
sampler mask = sampler_state
{
Texture = <MaskTexture>;
};
// here we do the real work.
float4 PixelShaderFunction(float2 inCoord: TEXCOORD0) : COLOR
{
float4 color = tex2D(screen, inCoord);
color.rgba = color.rgba - tex2D(mask, inCoord).r;
return color;
}
technique
{
pass P0
{
// changed this to reflect fex answer
PixelShader = compile ps_4_0_level_9_1 PixelShaderFunction();
}
}
EDIT
The answer by fex makes me able to load the effect but it dosent seem to work now.
Im using it like this:
Texture2D Planet = _Common.ContentManager.Load<Texture2D>("Materials/RedPlanet512");
Texture2D AlphaMapp = _Common.ContentManager.Load<Texture2D>("Materials/Dots2");
Effect AlphaShader = _Common.ContentManager.Load<Effect>("Effects/AlphaMap");
AlphaShader.Parameters["MaskTexture"].SetValue(AlphaMapp);
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, AlphaShader, _Common.Camera.View);
spriteBatch.Draw(Planet,
new Vector2(0, 0),
null, Color.White, 0f,
new Vector2(Planet.Width / 2, Planet.Height / 2),
1f, SpriteEffects.None, 1f);
spriteBatch.End();
These are the textures im using:
http://www.syntaxwarriors.com/wp-content/gallery/alphamapping-gallery/redplanet512.png
http://www.syntaxwarriors.com/wp-content/gallery/alphamapping-gallery/whitedots_0.png
Try to change this line:
PixelShader = compile ps_2_0 PixelShaderFunction();
into:
PixelShader = compile ps_4_0_level_9_1 PixelShaderFunction();
By the way - why don't you use MonoGame Content template?

Why does a valid Texture not reach the Shader? (Direct3D9)

Hello everyone I'm currently trying to create a deferred renderer for my graphics engine using c# and SlimDX. As a resource I use this tutorial which is very helpful eventhough it's intended for XNA.
But right now I'm stuck...
I have my renderer set up to draw all geometry's color, normals and depth to seperate render target textures. This works. I can draw the resulting textures to the restored backbuffer as sprites and I can see that they contain just what they are supposed to. But when I try to pass those Textures to another shader, in this case to create a light map, weirds things happen. Here's how I draw one frame:
public bool RenderFrame(FrameInfo fInfo){
if(!BeginRender()) //checks Device, resizes buffers, calls BeginScene(), etc.
return false;
foreach(RenderQueue queue in fInfo.GetRenderQueues()){
RenderQueue(queue);
}
EndRender(); //currently only calls EndScene, used to do more
ResolveGBuffer();
DrawDirectionalLight(
new Vector3(1f, -1f, 0),
new Color4(1f,1f,1f,1f),
fi.CameraPosition,
SlimMath.Matrix.Invert(fi.ViewProjectionMatrix));
}
private void ResolveGBuffer() {
if(DeviceContext9 == null || DeviceContext9.Device == null)
return;
DeviceContext9.Device.SetRenderTarget(0, _backbuffer);
DeviceContext9.Device.SetRenderTarget(1, null);
DeviceContext9.Device.SetRenderTarget(2, null);
}
private void DrawDirectionalLight(Vector3 lightDirection, Color4 color, SlimMath.Vector3 cameraPosition, SlimMath.Matrix invertedViewProjection) {
if(DeviceContext9 == null || DeviceContext9.Device == null)
return;
DeviceContext9.Device.BeginScene();
_directionalLightShader.Shader.SetTexture(
_directionalLightShader.Parameters["ColorMap"],
_colorTexture);
_directionalLightShader.Shader.SetTexture(
_directionalLightShader.Parameters["NormalMap"],
_normalTexture);
_directionalLightShader.Shader.SetTexture(
_directionalLightShader.Parameters["DepthMap"],
_depthTexture);
_directionalLightShader.Shader.SetValue<Vector3>(
_directionalLightShader.Parameters["lightDirection"],
lightDirection);
_directionalLightShader.Shader.SetValue<Color4>(
_directionalLightShader.Parameters["Color"],
color);
_directionalLightShader.Shader.SetValue<SlimMath.Vector3>(
_directionalLightShader.Parameters["cameraPosition"],
cameraPosition);
_directionalLightShader.Shader.SetValue<SlimMath.Matrix>(
_directionalLightShader.Parameters["InvertViewProjection"],
invertedViewProjection);
_directionalLightShader.Shader.SetValue<Vector2>(
_directionalLightShader.Parameters["halfPixel"],
_halfPixel);
_directionalLightShader.Shader.Technique =
_directionalLightShader.Technique("Technique0");
_directionalLightShader.Shader.Begin();
_directionalLightShader.Shader.BeginPass(0);
RenderQuad(SlimMath.Vector2.One * -1, SlimMath.Vector2.One);
_directionalLightShader.Shader.EndPass();
_directionalLightShader.Shader.End();
DeviceContext9.Device.EndScene();
}
Now when I replace the call to DrawDirectionalLight with some code to draw _colorTexture, _normalTexture and _depthTexture to the screen everything looks ok, but when I use the DrawDirectionalLight function instead I see wild flickering. From the output of PIX it looks like my textures do not get passed to the shader correctly:
Following the tutorial the texture parameters and samplers are defined as follows:
float3 lightDirection;
float3 Color;
float3 cameraPosition;
float4x4 InvertViewProjection;
texture ColorMap;
texture NormalMap;
texture DepthMap;
sampler colorSampler = sampler_state{
Texture = ColorMap;
AddressU = CLAMP;
AddressV = CLAMP;
MagFilter= LINEAR;
MinFilter= LINEAR;
MipFilter= LINEAR;
};
sampler depthSampler = sampler_state{
Texture = DepthMap;
AddressU = CLAMP;
AddressV = CLAMP;
MagFilter= POINT;
MinFilter= POINT;
MipFilter= POINT;
};
sampler normalSampler = sampler_state{
Texture = NormalMap;
AddressU = CLAMP;
AddressV = CLAMP;
MagFilter= POINT;
MinFilter= POINT;
MipFilter= POINT;
};
Now my big question is WHY? There are no error messages printed to debug output.
EDIT:
the rendertargets/textures are created like this:
_colorTexture = new Texture(DeviceContext9.Device,
DeviceContext9.PresentParameters.BackBufferWidth,
DeviceContext9.PresentParameters.BackBufferHeight,
1,
Usage.RenderTarget,
Format.A8R8G8B8,
Pool.Default);
_colorSurface = _colorTexture.GetSurfaceLevel(0);
_normalTexture = new Texture(DeviceContext9.Device,
DeviceContext9.PresentParameters.BackBufferWidth,
DeviceContext9.PresentParameters.BackBufferHeight,
1,
Usage.RenderTarget,
Format.A8R8G8B8,
Pool.Default);
_normalSurface = _normalTexture.GetSurfaceLevel(0);
_depthTexture = new Texture(DeviceContext9.Device,
DeviceContext9.PresentParameters.BackBufferWidth,
DeviceContext9.PresentParameters.BackBufferHeight,
1,
Usage.RenderTarget,
Format.A8R8G8B8,
Pool.Default);
_depthSurface = _depthTexture.GetSurfaceLevel(0);
EDIT 2:
The problems seems to lie in the directionalLightShader itselft since passing other regular textures doesn't work either.
The answer to my problem is as simple as the problem was stupid. The strange behaviour was caused by 2 different errors:
I was just looking at the wrong events in PIX. The textures we passed correctly to the shader but I didn't see it because it was 'hidden' in the BeginPass-event (behind the '+').
The pixel shader which I was trying to execute never got called because vertices of the fullscreen quad I used to render were drawn in clockwise order... my CullMode was also set to clockwise...
Thanks to everyone who read this question!

Problem with xna shader

Trying to make a glow effect in xna but it doesn't show the glow or any change at all. Also my back color is purple instead of black and I can't change that either :
GraphicsDevice.Clear(Color.Black);
GraphicsDevice.SetRenderTarget(bulletRenderTarget);
spriteBatch.Begin();
foreach (Bullet bullet in bulletList)
{
Texture2D bulletTexture = textures[bullet.bulletType];
spriteBatch.Draw(
bulletTexture,
new Rectangle(
(int)bullet.position.X,
(int)bullet.position.Y,
bulletTexture.Width,
bulletTexture.Height
),
null,
Color.White,
MathHelper.ToRadians(bullet.angle),
new Vector2(
bulletTexture.Width / 2,
bulletTexture.Height / 2
),
SpriteEffects.None,
0
);
}
spriteBatch.End();
GraphicsDevice.SetRenderTarget(null);
GraphicsDevice.Clear(Color.Black);
postProcessEffect.CurrentTechnique = postProcessEffect.Techniques["Blur"];
spriteBatch.Begin();
spriteBatch.Draw(
bulletRenderTarget,
new Vector2(0, 0),
Color.White
);
GraphicsDevice.BlendState = BlendState.Additive;
foreach (EffectPass pass in postProcessEffect.CurrentTechnique.Passes)
{
pass.Apply();
spriteBatch.Draw(
bulletRenderTarget,
new Vector2(0,0),
Color.White
);
}
DrawHud();
foreach (BaseEntity entity in entityList)
{
entity.Draw(gameTime);
}
spriteBatch.End();
I'm only trying to get the bullets to glow.
shader :
float BlurDistance = 0.002f;
sampler ColorMapSampler : register(s1);
float4 PixelShaderFunction(float2 Tex: TEXCOORD0) : COLOR
{
float4 Color;
// Get the texel from ColorMapSampler using a modified texture coordinate. This
// gets the texels at the neighbour texels and adds it to Color.
Color = tex2D( ColorMapSampler, float2(Tex.x+BlurDistance, Tex.y+BlurDistance));
Color += tex2D( ColorMapSampler, float2(Tex.x-BlurDistance, Tex.y-BlurDistance));
Color += tex2D( ColorMapSampler, float2(Tex.x+BlurDistance, Tex.y-BlurDistance));
Color += tex2D( ColorMapSampler, float2(Tex.x-BlurDistance, Tex.y+BlurDistance));
// We need to devide the color with the amount of times we added
// a color to it, in this case 4, to get the avg. color
Color = Color / 4;
// returned the blurred color
return Color;
}
technique Blur
{
pass Pass1
{
PixelShader = compile ps_2_0 PixelShaderFunction();
}
}
The reason it's purple is because you have
GraphicsDevice.Clear(Color.Black);
GraphicsDevice.SetRenderTarget(bulletRenderTarget);
which should be the other way around, so changing that into
GraphicsDevice.SetRenderTarget(bulletRenderTarget);
GraphicsDevice.Clear(Color.Black);
fixes the purple problem, to fix the shader change the following in the fx file
sampler ColorMapSampler : register(s0);
And change your spriteBatch.Begin() into
spriteBatch.Begin(SpriteSortMode.Immediate, null);
Some extra info:
the s0 points to the first texture on the graphics device, which is the one that supplied by spriteBatch.Draw, if you want to use s1 you'd have to set it on the GraphicsDevice first by using:
GraphicsDevice.Textures[1] = bulletRenderTarget;
the SpriteSortMode.Immediate just forces the spriteBatch.Draw to draw the sprite immediately, if you don't set it it'll create a batch and draw them all at once, but this will be to late because it needs to be drawn when the EffectPass is being applied.
As for the blur you could lower the value of BlurDistance, but you'd have to try, you can also look up how to do a bloom shader, usually gives a nice effect too.

Categories