MonoGame
Draw the shaders you made in the tutorial in a MonoGame window.
In the Get Started you made your shaders in a library that knows nothing about MonoGame. They compiled, and you saw the result as text in the console. Here you take the step that was missing: seeing them in a MonoGame window.

That is what will show up in your window in a few minutes, and the Gradient you wrote yourself is what will draw it.
What you are going to do#
You are going to add one more project to your folder: the game.
Tutorial/
├── MyShaders/ your shaders
├── TryIt/ the console program from the tutorial
└── MyGame/ new: a MonoGame window that uses your shadersThe path has three parts:
- Prepare your shaders for MonoGame. One command, in step 0.
- Create the game. A new project with MonoGame installed (steps 1 to 3).
- See them. You run the game and your shader shows up (steps 4 to 6).
You will see one word a lot: plugin. A plugin is an extension of the yotsuba tool. Without it, yotsuba knows how to prepare shaders for OpenGL, DirectX, Metal and Vulkan, but not for MonoGame. With the MonoGame plugin, it learns. You do not write it, and your game does not use it: only yotsuba uses it, while it compiles.
0. Prepare your shaders for MonoGame#
This step is short, but do not skip it: without it, your game will have no way to ask for the shader.
The command#
From the Tutorial folder:
dotnet yotsuba add MyShaders/MyShaders.csproj --target spirv --target monogameIt is the same command as always, with one more part:
--target spirvis what you already used.--target monogamemeans "and prepare them also for MonoGame".
The first time, yotsuba downloads the MonoGame plugin from the internet by itself. You do not install anything. The next times it uses the copy it saved.
Check that it worked#
Open MyShaders/YotsubaShader.g.cs. It is a file that the command wrote. Look for ToMGFX: there must be one for each of your shader classes. That method is the one your game will use in step 3.
If you cannot find it, the command did not have --target monogame. Run it again with it.
What the plugin makes#
The plugin makes a MonoGame effect (MGFX format), the same one MonoGame's own Content Pipeline would make. An effect changes depending on the system where it runs, so the plugin prepares one version for each platform, and your game picks one (in step 3):
MonoGamePlatform | Use it with |
|---|---|
DesktopGL | MonoGame.Framework.DesktopGL (Windows, macOS, Linux) |
WindowsDX11 | MonoGame.Framework.WindowsDX (Windows with DirectX 11) |
WindowsDirectX12, DesktopVulkan, GL4 | The new MonoGame with DirectX 12, Vulkan or OpenGL 4 |
Android, iOS | MonoGame.Framework.Android and .iOS |
You choose the platform in the game, not in the .csproj.
Optional: make it run by itself#
Every time you change a shader you would have to repeat the command. To make it happen on its own when you build, open MyShaders/MyShaders.csproj and add this just before the closing </Project>. The rest of the file stays as it is:
<Target Name="CompileShaders" BeforeTargets="CoreCompile" Condition="'$(DesignTimeBuild)' != 'true'">
<Exec Command="dotnet yotsuba add "$(MSBuildProjectFullPath)" --target spirv --target monogame" />
<ItemGroup>
<Compile Remove="YotsubaShader.g.cs" />
<Compile Include="YotsubaShader.g.cs" />
</ItemGroup>
</Target>What each part says:
BeforeTargets="CoreCompile": "do this right before compiling the C#".Exec: it is the same command you typed by hand.Condition: your editor builds the project in the background while you type. This keeps the command from running on every keystroke.Compile RemoveandCompile Include: they addYotsubaShader.g.csto the build even if it does not exist yet.
From now on, dotnet build MyShaders runs the command for you.
Other plugin commands#
If you want to download the plugin before (for example, to work without internet), use dotnet yotsuba plugin install monogame. And dotnet yotsuba plugin list shows which ones you have. There is more in The CLI.
1. Create the game and install the engine#
From the Tutorial folder:
dotnet new console -n MyGame -f net8.0Install MonoGame:
dotnet add MyGame package MonoGame.Framework.DesktopGLAnd tell it that it is going to use your shaders:
dotnet add MyGame reference MyShaders/MyShaders.csprojMonoGame.Framework.DesktopGL is the MonoGame that works on Windows, macOS and Linux, and it opens the window with OpenGL. If your game uses another one (for example the DirectX one), what changes is further down.
Notice what you did not install: you did not install any Yotsuba Shader package for MonoGame, and you did not create the game with dotnet new mgdesktopgl. A plain console project plus this package is enough, because the shader does not go through MonoGame's Content Pipeline. That means you will not need dotnet-mgcb, the MGCB Editor or a Content.mgcb file: your shader reaches the game as bytes inside your own library (you will see how in step 3).
2. The rectangle that covers the screen#
In the tutorial you saw that a shader does not draw "the screen": it draws a shape, and to paint the whole screen we use a rectangle that covers it. That rectangle has four corners, and each corner carries the two pieces of data you declared in Corner:
public struct Corner
{
[location(0)] public vec2 Position;
[location(1)] public vec2 Uv;
}Now it is the game's turn to send those corners. For that, MonoGame asks for a struct that says how each one is made. Create MyGame/ScreenCorner.cs:
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
public readonly struct ScreenCorner(Vector2 position, Vector2 uv) : IVertexType
{
private static readonly VertexDeclaration Declaration = new(
new VertexElement(0, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0),
new VertexElement(8, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 1));
public readonly Vector2 Position = position;
public readonly Vector2 Uv = uv;
VertexDeclaration IVertexType.VertexDeclaration => Declaration;
}(MonoGame keeps the XNA names, so the using lines say Microsoft.Xna.Framework even though you are not using Microsoft's XNA.)
The two fields are the same ones as in Corner: the position and the Uv. What is new is the VertexDeclaration, which is MonoGame's way of explaining to the GPU what is in each corner. Each line describes one field:
new VertexElement(0, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0),- The first
0is the byte where the field starts.Positioncomes first, so it starts at 0. Vector2is its type: twofloat.TextureCoordinateand the last0are the slot. This is the important part.
And the second line, the one for Uv, starts at byte 8 because the two float of Position come first, and they take 4 bytes each.
IVertexType is the interface that lets MonoGame ask your struct for that declaration. And readonly struct with a primary constructor is just a short way to write a struct whose fields are set once.
From [location] to TextureCoordinate#
In your shader the slots have only a number: [location(0)], [location(1)]. In MonoGame they have a name and a number. Yotsuba Shader makes the translation like this:
| In your shader | In MonoGame |
|---|---|
[location(0)] | TextureCoordinate, number 0 |
[location(1)] | TextureCoordinate, number 1 |
[location(2)] | TextureCoordinate, number 2 |
That is: the name is always TextureCoordinate, and the number is the one from your location.
3. The game#
Delete what MyGame/Program.cs has and leave only this, which creates the game and starts it:
using var game = new MyGame();
game.Run();Now create MyGame/MyGame.cs:
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using MyShaders;
using YotsubaShader;
public class MyGame : Game
{
private readonly GraphicsDeviceManager _graphics;
private Effect _shader = null!;
private readonly ScreenCorner[] _screen =
[
new(new Vector2(-1f, 1f), new Vector2(0f, 0f)),
new(new Vector2( 1f, 1f), new Vector2(1f, 0f)),
new(new Vector2(-1f, -1f), new Vector2(0f, 1f)),
new(new Vector2( 1f, -1f), new Vector2(1f, 1f)),
];
public MyGame()
{
_graphics = new GraphicsDeviceManager(this)
{
PreferredBackBufferWidth = 800,
PreferredBackBufferHeight = 800,
};
}
protected override void LoadContent()
{
byte[] compiled = new Gradient().ToMGFX(MonoGamePlatform.DesktopGL);
_shader = new Effect(GraphicsDevice, compiled);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.RasterizerState = RasterizerState.CullNone;
_shader.CurrentTechnique.Passes[0].Apply();
GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleStrip, _screen, 0, 2);
base.Draw(gameTime);
}
}The first lines say where each thing comes from: Microsoft.Xna.Framework has Game, Vector2 and GameTime; ...Graphics has Effect, GraphicsDevice and the drawing types; MyShaders is your library; and YotsubaShader is the namespace of the generated file (where ToMGFX and MonoGamePlatform lives).
There are three parts that matter for Yotsuba Shader. After them, a section explains what each MonoGame piece does.
The four corners#
_screen is the rectangle. Each line is a corner, with its position and its Uv:
new(new Vector2(-1f, 1f), new Vector2(0f, 0f)), // top left
new(new Vector2( 1f, 1f), new Vector2(1f, 0f)), // top right
new(new Vector2(-1f, -1f), new Vector2(0f, 1f)), // bottom left
new(new Vector2( 1f, -1f), new Vector2(1f, 1f)), // bottom rightFor the GPU the screen goes from -1 to 1, with (0, 0) in the center and the 1 of Y at the top. That is why the positions are -1 and 1: they are the edges of the screen. The Uv are the ones you saw in the tutorial: (0, 0) at the top left and (1, 1) at the bottom right.
Loading the shader#
This is the part that joins the two worlds:
byte[] compiled = new Gradient().ToMGFX(MonoGamePlatform.DesktopGL);
_shader = new Effect(GraphicsDevice, compiled);new Gradient() is your shader, the class you wrote. ToMGFX is the method that add put on your class for MonoGame (you tell it which MonoGame you want, DesktopGL). It returns the shader already compiled, in the format MonoGame reads. That is why Effect accepts it directly.
There is no .fx file, no Content folder and no separate step to compile. The shader already comes inside your library.
Drawing#
GraphicsDevice.RasterizerState = RasterizerState.CullNone;
_shader.CurrentTechnique.Passes[0].Apply();
GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleStrip, _screen, 0, 2);Apply()tells the GPU: "from now on, draw with this shader".DrawUserPrimitivessends the four corners. The GPU does not know how to draw rectangles, only triangles, so the rectangle goes as two triangles glued together. That isTriangleStrip, and the2at the end is how many triangles there are.CullNoneasks the GPU not to discard any triangle. Normally it discards the ones that "face backwards", which in a 3D game are the faces you cannot see. Here there is nothing to hide.
What each MonoGame piece does#
This part is about MonoGame, not about Yotsuba Shader, but without it the game above is a block you copy without understanding. Read it once.
Game and its cycle. Your class inherits from Game. When Program.cs calls Run(), MonoGame opens the window and repeats a cycle until the window closes. You do not call the steps: you override the ones you need.
protected override void Initialize() { /* once, before the window shows */ base.Initialize(); }
protected override void LoadContent() { /* once, when the graphics are ready */ }
protected override void Update(GameTime gameTime) { /* every frame: logic */ base.Update(gameTime); }
protected override void Draw(GameTime gameTime) { /* every frame: drawing */ base.Draw(gameTime); }| Method | When it runs | In this guide |
|---|---|---|
Initialize | Once, at the start. | Not used. |
LoadContent | Once, right after the graphics device exists. | We create the Effect here, because it needs the GraphicsDevice. |
Update | Every frame, before drawing. Usually 60 times per second. | Not used yet. |
Draw | Every frame, after Update. | We draw the rectangle. |
base.Draw(gameTime) calls the original version of Draw that Game has. Here it does nothing visible, but it is good to keep it: it is what draws any component you add to the game later.
GraphicsDeviceManager. It is the object that creates and configures the window and the graphics card connection. You build it in the constructor, passing the game (this). The two PreferredBackBuffer... lines set the size of the drawing area: 800 by 800 pixels. If you do not set them, MonoGame uses 800 by 480.
GraphicsDevice. It is a property that Game has once the manager has created it. It represents the graphics card: everything you draw goes through it. That is why new Effect(GraphicsDevice, ...) asks for it, and why you cannot create the Effect in the constructor (the device does not exist yet): that is the reason for LoadContent.
Effect. It is a compiled shader that MonoGame can use. It holds the vertex and fragment code, together, and its parameters. The three things you use:
_shader.CurrentTechnique // the set of steps that draws with this effect
_shader.CurrentTechnique.Passes[0] // the first (and, here, only) step
_shader.Parameters["Name"] // a value you can change from C#An effect can have several techniques with several passes. The ones Yotsuba Shader generates have one technique with one pass, so Passes[0] is always the one.
GameTime. It is what MonoGame passes to Update and Draw to tell you about time. gameTime.TotalGameTime is how long the game has been open, and gameTime.ElapsedGameTime is how long the last frame took. In step 6 you use the first one.
DrawUserPrimitives. It sends vertices from an array in memory straight to the GPU, and draws them. It is the simplest way to draw, and it is perfect for four corners. For thousands of vertices, MonoGame has VertexBuffer and IndexBuffer, which keep the data in the GPU memory so it is not sent every frame. For a rectangle you do not need them.
Closing the window. Your game has no way to close except the window's own button. If you want Esc to close it, add an Update:
protected override void Update(GameTime gameTime)
{
if (Keyboard.GetState().IsKeyDown(Keys.Escape))
{
Exit();
}
base.Update(gameTime);
}Keyboard and Keys are in Microsoft.Xna.Framework.Input, so you also add that using.
What you will not need. MonoGame also has SpriteBatch (for drawing 2D images, with its own shader), Content.Load (to read files from the Content Pipeline) and Texture2D. This guide uses none of them: you draw the rectangle yourself, and the shader is already in memory. When textures work in the compiler, Texture2D will come in.
4. Run it#
dotnet run --project MyGameA window opens with the sunset. That color was calculated by your Fragment method, pixel by pixel, on the GPU.
5. Change the shader#
Changing shader means changing one word. In LoadContent, where it says Gradient, put Mandelbrot:
byte[] compiled = new Mandelbrot().ToMGFX(MonoGamePlatform.DesktopGL);Run again:
dotnet run --project MyGame
The same rectangle, the same four corners, and a completely different drawing. Everything that changed is inside the shader.
6. A shader that moves#
Until here the window shows a still image. For something to move, the game has to send the shader a value that changes: the time. In the tutorial you saw it in Shader 4: that data is called a uniform.
You are going to make a strip of light that crosses the screen from left to right:
| Second 0.3 | Second 1 | Second 1.7 |
|---|---|---|
![]() | ![]() | ![]() |
The shader#
Create MyShaders/Sweep.cs:
using YotsubaShader.GlslSyntax;
using YotsubaShader.GlslSyntax.Resources;
using YotsubaShader.GlslSyntax.Types;
using YotsubaShader.Language;
namespace MyShaders;
public struct Stopwatch
{
public float Seconds;
}
public class Sweep
{
[uniform, layout(0, 0)]
public Stopwatch Time;
[ShaderStage(Stage.Vertex)]
public Pixel Vertex(Corner corner)
{
Pixel pixel;
pixel.Position = Make.Vec4(corner.Position.X, corner.Position.Y, 0f, 1f);
pixel.Uv = corner.Uv;
return pixel;
}
[ShaderStage(Stage.Fragment)]
[return: location(0)]
public vec4 Fragment(PixelIn pixel)
{
float center = Time.Seconds * 0.5f;
float distance = pixel.Uv.X - center;
if (distance < 0f)
{
distance = -distance;
}
float brightness = 1f - distance * 5f;
if (brightness < 0f)
{
brightness = 0f;
}
return Make.Vec4(brightness, brightness * 0.5f, 0.15f + 0.35f * pixel.Uv.Y, 1f);
}
}The Vertex method is the usual one. What is new:
Stopwatchis a normalstructwith the piece of data the game is going to send.[uniform, layout(0, 0)] public Stopwatch Time;declares that data inside the shader.- In
Fragment,centeris where the strip is right now, from0(left edge) to1(right edge).distanceis how far this pixel is from the strip, and theifremoves the sign. The farther away, the lessbrightness.
Build it with add, like in the tutorial, asking for the plugin as in step 0:
dotnet yotsuba add MyShaders/MyShaders.csproj --target spirv --target monogameIf you added the Target from step 0, you do not need to: it runs when you build the game.
The game sends it the time#
In MyGame/MyGame.cs two things change: which shader is loaded, and two new lines in Draw. The complete file looks like this:
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using MyShaders;
using YotsubaShader;
public class MyGame : Game
{
private readonly GraphicsDeviceManager _graphics;
private Effect _shader = null!;
private readonly ScreenCorner[] _screen =
[
new(new Vector2(-1f, 1f), new Vector2(0f, 0f)),
new(new Vector2( 1f, 1f), new Vector2(1f, 0f)),
new(new Vector2(-1f, -1f), new Vector2(0f, 1f)),
new(new Vector2( 1f, -1f), new Vector2(1f, 1f)),
];
public MyGame()
{
_graphics = new GraphicsDeviceManager(this)
{
PreferredBackBufferWidth = 800,
PreferredBackBufferHeight = 800,
};
}
protected override void LoadContent()
{
byte[] compiled = new Sweep().ToMGFX(MonoGamePlatform.DesktopGL);
_shader = new Effect(GraphicsDevice, compiled);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.RasterizerState = RasterizerState.CullNone;
float seconds = (float)(gameTime.TotalGameTime.TotalSeconds % 2.0);
_shader.Parameters["Time_Seconds"].SetValue(seconds);
_shader.CurrentTechnique.Passes[0].Apply();
GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleStrip, _screen, 0, 2);
base.Draw(gameTime);
}
}The two new lines:
float seconds = (float)(gameTime.TotalGameTime.TotalSeconds % 2.0);
_shader.Parameters["Time_Seconds"].SetValue(seconds);The first one gets how many seconds the game has been open. The % 2.0 makes it go back to 0 every two seconds, so the strip starts again from the left.
The second one hands that number to the shader. The name "Time_Seconds" is not made up, it comes from your code: it is the name of the field, an underscore and the name of the data.
| In your shader | In MonoGame |
|---|---|
public Stopwatch Time; with a Seconds piece of data | Parameters["Time_Seconds"] |
It has to be done before Apply(), because Apply() is the moment when the data travels to the GPU.
SetValue has a version for each type you can have in a struct:
| In your shader | What you pass to SetValue |
|---|---|
float | A float |
int | An int |
vec2 | A Vector2 |
vec3 | A Vector3 |
vec4 | A Vector4 |
mat4 | A Matrix |
If the name does not match any parameter, Parameters["..."] gives you null, and the line fails with a NullReferenceException. When you are not sure the shader uses that value (for example, a shader that does not read the time), write ?.SetValue(...) and the line is skipped instead.
Run:
dotnet run --project MyGameThe strip crosses the screen again and again.
Other MonoGame platforms#
MonoGame is not just one: there is one for each system, and each one wants the shader compiled its own way. That is what the value you pass to ToMGFX is for (the table in step 0 says which MonoGame each one is for).
Changing platform takes two things. First, the package of your game:
dotnet add MyGame package MonoGame.Framework.WindowsDXWindowsDX only runs on Windows, so the game project has to target Windows. In MyGame/MyGame.csproj:
<TargetFramework>net8.0-windows</TargetFramework>And second, the word in your game:
byte[] compiled = new Gradient().ToMGFX(MonoGamePlatform.WindowsDX11);add already left every version inside YotsubaShader.g.cs, so you do not need to compile again to change platform.
If something fails#
| What you see | What it means | What to do |
|---|---|---|
ToMGFX does not exist | The generated file does not have it: add ran without the plugin. | Run add with --target monogame (step 0), or add it to the Target of the .csproj. |
add fails with a message about a shader | One of your shaders cannot be compiled for the GPU yet (for example Neon, Plasma or Underwater from the tutorial). | Move that file out of the MyShaders folder for now. |
add finishes, but running the game throws NotSupportedException | The plugin could not compile that shader. add does not fail, it leaves the method ready to report the reason. | Run add again and read what it prints: it says which shader and why. |
| The rectangle is deformed or does not show up | The corners use VertexElementUsage.Position. | Use TextureCoordinate with the number of your location (step 2). |
NullReferenceException in Parameters[...].SetValue | The name does not exist in the shader. | The name is Field_Data: check both against your struct (step 6). |
| The window opens and stays black | Apply() or DrawUserPrimitives are missing, or the shader returns black. | Check step 3 and make sure the Fragment returns a color with 1 in the last value. |
The first add with the plugin fails with a network error | The CLI is downloading the plugin and cannot reach NuGet. | Check your connection, or use dotnet yotsuba plugin install monogame when you are online. |
What is not possible yet#
Summary#
Of everything you did, what belongs to MonoGame is this:
| The plugin (for the CLI) | monogame |
The add command | dotnet yotsuba add MyShaders/MyShaders.csproj --target spirv --target monogame |
| The package (for the game) | MonoGame.Framework.DesktopGL |
| The method | ToMGFX(MonoGamePlatform.DesktopGL) |
The rest is the same in MonoGame, KNI and FNA, because the three share the same way of programming:
- The corners are declared with
TextureCoordinateand the number of your[location]. - The shader is loaded with
new Effect(GraphicsDevice, bytes). - The data of a uniform is sent with
Parameters["Field_Data"].SetValue(...), beforeApply().
And your MyShaders library did not change at all to work here, except for asking for the plugin when you build it.


