Hello everyone,
This is my first attempt to derive a Texture2D
programmatically. The idea is simple, I try to generate by code a texture that should look like this :
.
I am working on the inside of the texture.
This is what I achieved so far :
As you can see, on the “diagonals”, I have distortions. If we look closer :
If I run the same code but without a saturation on the alpha channel, I obtained the figure below where we can easily see the artefacts/distortions.
To be complete, I have written a small demo with a 1/4th of the square. The code is below.
Do you know what I need to change to ensure I have no distortion ? I am sure it should be somewhere in the shaders and how they are drawn on the screen…
Thank you !
public class App : Game
{
private SpriteBatch spriteBatch;
private RenderTarget2D target;
private readonly GraphicsDeviceManager graphics;
public App()
{
graphics = new GraphicsDeviceManager(this);
}
protected override void Initialize()
{
base.Initialize();
graphics.PreferredBackBufferWidth = Constants.WINDOW_WIDTH;
graphics.PreferredBackBufferHeight = Constants.WINDOW_HEIGHT;
textureTest = Create(GraphicsDevice, 300, 300);
spriteBatch = new SpriteBatch(GraphicsDevice);
target = new RenderTarget2D(
GraphicsDevice,
Constants.VIRTUAL_WIDTH,
Constants.VIRTUAL_HEIGHT,
false,
SurfaceFormat.Color,
DepthFormat.None, GraphicsDevice.PresentationParameters.MultiSampleCount,
RenderTargetUsage.DiscardContents
);
}
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.SetRenderTarget(target);
GraphicsDevice.Clear(Color.Black);
spriteBatch.Begin(blendState: BlendState.Additive);
spriteBatch.Draw(textureTest, new Vector2(50, 50), Color.Yellow);
spriteBatch.End();
graphics.GraphicsDevice.SetRenderTarget(null);
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive);
var dst = new Rectangle(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height);
spriteBatch.Draw(target, dst, Color.White);
spriteBatch.End();
}
private Texture2D Create(GraphicsDevice device, int width, int height)
{
Debug.Assert(width == height);
// initialize a texture
Texture2D texture = new Texture2D(device, width, height);
var data = new float[width * height];
var granularity = 1f / (float)height;
for (int i = 0; i < height; i++)
{
for (int j = i; j < width; j++)
{
data[i * width + j] = 1f - granularity * i;
}
for (int k = i; k < height; k++)
{
data[k * width + i] = 1f - granularity * i;
}
}
texture.SetData(data.Select(d => new Color(Color.White, d)).ToArray());
return texture;
}
}
public class Constants
{
public const int WINDOW_WIDTH = 1024;
public const int WINDOW_HEIGHT = 768;
public const int VIRTUAL_WIDTH = 640;
public const int VIRTUAL_HEIGHT = 480;
}