Skip to content

Commit 1d068f5

Browse files
Added missing graphics HowTo articles
1 parent ee4ae37 commit 1d068f5

File tree

7 files changed

+407
-0
lines changed

7 files changed

+407
-0
lines changed
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
---
2+
title: How to create a Basic Effect
3+
description: Demonstrates how to create and initialize an instance of the BasicEffect class and use it to draw simple geometry.
4+
requireMSLicense: true
5+
---
6+
7+
## Overview
8+
9+
The steps described here apply to effects created with the [BasicEffect](xref:Microsoft.Xna.Framework.Graphics.BasicEffect) class using the [Effect](xref:Microsoft.Xna.Framework.Graphics.Effect) class to write a custom effect.
10+
11+
> [!NOTE]
12+
> The example draws aliased geometry, to see an example that draws smoother edges because it also applies anti-aliasing, see [Enabling Anti-aliasing (Multi-sampling)](HowTo_Enable_Anti_Aliasing.md).
13+
14+
### End result
15+
16+
![The output of this tutorial](images/HowTo_BasicEffect_Sample.png)
17+
18+
## To use BasicEffect
19+
20+
Using the basic effect class requires a set of `world`, `view`, and `projection` matrices, a `vertex buffer`, a `vertex declaration`, and an instance of the [BasicEffect](xref:Microsoft.Xna.Framework.Graphics.BasicEffect) class.
21+
22+
1. Declare these properties at the beginning of the game class.
23+
24+
```csharp
25+
//Matrices for 3D perspective
26+
private Matrix worldMatrix, viewMatrix, projectionMatrix;
27+
28+
// Vertex data for rendering
29+
private VertexPositionColor[] triangleVertices;
30+
31+
// A Vertex format structure that contains position, normal data, and one set of texture coordinates
32+
private BasicEffect basicEffect;
33+
```
34+
35+
1. Initialize the world, view, and projection matrices in the `Initialize`.
36+
37+
Next, create a world matrix using the default `Matrix.Identity` for simplicity. Set the `view matrix` as a `look-at` matrix with a camera position of `(0, 0, 50)`, pointing at the origin. The `projection matrix` is a `perspective` projection matrix based on a a `45-degree` field of view, an aspect ratio equal to the client window, and a set of `near` and `far` planes to render the geometry within in view of the camera.
38+
39+
```csharp
40+
protected override void Initialize()
41+
{
42+
// Setup the matrices to look forward
43+
worldMatrix = Matrix.Identity;
44+
viewMatrix = Matrix.CreateLookAt(new Vector3(0, 0, 50), Vector3.Zero, Vector3.Up);
45+
46+
projectionMatrix = Matrix.CreatePerspectiveFieldOfView(
47+
MathHelper.PiOver4,
48+
GraphicsDevice.Viewport.AspectRatio,
49+
1.0f, 300.0f);
50+
51+
base.Initialize();
52+
}
53+
```
54+
55+
1. Initialize a [BasicEffect](xref:Microsoft.Xna.Framework.Graphics.BasicEffect) with the transformation and light values in the `LoadContent` method.
56+
57+
```csharp
58+
protected override void LoadContent()
59+
{
60+
basicEffect = new BasicEffect(_graphics.GraphicsDevice);
61+
62+
basicEffect.World = worldMatrix;
63+
basicEffect.View = viewMatrix;
64+
basicEffect.Projection = projectionMatrix;
65+
66+
// primitive color
67+
basicEffect.AmbientLightColor = new Vector3(0.1f, 0.1f, 0.1f);
68+
basicEffect.DiffuseColor = new Vector3(1.0f, 1.0f, 1.0f);
69+
basicEffect.SpecularColor = new Vector3(0.25f, 0.25f, 0.25f);
70+
basicEffect.SpecularPower = 5.0f;
71+
basicEffect.Alpha = 1.0f;
72+
// The following MUST be enabled if you want to color your vertices
73+
basicEffect.VertexColorEnabled = true;
74+
75+
// Use the built in 3 lighting mode provided with BasicEffect
76+
basicEffect.EnableDefaultLighting();
77+
```
78+
79+
> [!NOTE]
80+
> If you wish, you can set up the lighting manually through code, as follows:
81+
> [!code-csharp[](./files/basiceffectlighting.cs)]
82+
83+
84+
1. Still in `LoadContent`, create the per vertex data using the `VertexPositionColor` format. This example shows the data for the face of a triangle.
85+
86+
```csharp
87+
triangleVertices = new VertexPositionColor[3];
88+
89+
triangleVertices[0].Position = new Vector3(0f, 0f, 0f);
90+
triangleVertices[0].Color = Color.Red;
91+
triangleVertices[1].Position = new Vector3(10f, 10f, 0f);
92+
triangleVertices[1].Color = Color.Yellow;
93+
triangleVertices[2].Position = new Vector3(10f, 0f, -5f);
94+
triangleVertices[2].Color = Color.Green;
95+
```
96+
97+
1. Finally, in the `Draw` Method, call [GraphicsDevice.Clear](xref:Microsoft.Xna.Framework.Graphics.GraphicsDevice#Microsoft_Xna_Framework_Graphics_GraphicsDevice_Clear_Microsoft_Xna_Framework_Color_) to clear the render target.
98+
99+
1. Set the rasterizer state to turn off culling using the [RasterizerState](xref:Microsoft.Xna.Framework.Graphics.GraphicsDevice.RasterizerState) property.
100+
101+
1. Call [EffectPass.Apply](/api/Microsoft.Xna.Framework.Graphics.EffectPass.html#Microsoft_Xna_Framework_Graphics_EffectPass_Apply) to set the effect state in preparation for rendering.
102+
103+
1. Draw the geometry by calling [GraphicsDevice.DrawUserPrimitives](/api/Microsoft.Xna.Framework.Graphics.GraphicsDevice.html#Microsoft_Xna_Framework_Graphics_GraphicsDevice_DrawUserPrimitives__1_Microsoft_Xna_Framework_Graphics_PrimitiveType___0___System_Int32_System_Int32_Microsoft_Xna_Framework_Graphics_VertexDeclaration_).
104+
105+
```csharp
106+
protected override void Draw(GameTime gameTime)
107+
{
108+
GraphicsDevice.Clear(Color.SteelBlue);
109+
110+
RasterizerState rasterizerState1 = new RasterizerState();
111+
rasterizerState1.CullMode = CullMode.None;
112+
GraphicsDevice.RasterizerState = rasterizerState1;
113+
foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
114+
{
115+
pass.Apply();
116+
117+
GraphicsDevice.DrawUserPrimitives(
118+
PrimitiveType.TriangleList,
119+
triangleVertices,
120+
0,
121+
1,
122+
VertexPositionColor.VertexDeclaration
123+
);
124+
}
125+
126+
base.Draw(gameTime);
127+
}
128+
```
129+
130+
When the sample is run, the basic geometry is rendered using the custom [BasicEffect](xref:Microsoft.Xna.Framework.Graphics.BasicEffect), feel free to play with the position, content or rendering order to enhance the effect.
131+
132+
## See Also
133+
134+
- [How to create a State Object](HowTo_Create_a_StateObject.md)
135+
136+
### Concepts
137+
138+
- [What Is a Configurable Effect?](../../whatis/graphics/WhatIs_ConfigurableEffect.md)
139+
140+
### Reference
141+
142+
- [GraphicsDevice](xref:Microsoft.Xna.Framework.Graphics.GraphicsDevice)
143+
- [BasicEffect](xref:Microsoft.Xna.Framework.Graphics.BasicEffect)
144+
- [RasterizerState](xref:Microsoft.Xna.Framework.Graphics.GraphicsDevice.RasterizerState)
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
---
2+
title: How to create a Render Target
3+
description: Demonstrates how to create a render target using a RenderTarget2D.
4+
requireMSLicense: true
5+
---
6+
7+
## Overview
8+
9+
The example is very basic but the principles are the same, when drawing to a Render Texture we apply the following process.
10+
11+
1. Set the Graphics Device to output to a texture.
12+
2. Clear the buffer (or not depending on the use case).
13+
3. Draw the full screen contents required in the Render Texture, e.g. a map or camera view.
14+
4. Reset the Graphics device to the back buffer (screen).
15+
5. Draw your game as normal.
16+
6. Draw the Render Texture to the screen in the position we desire (e.g. in the lower corner for a mini-map), most likely on top of your game graphics.
17+
18+
> [!TIP]
19+
> The technique is very useful, especially if you are doing split-screen gaming and need to draw multiple camera views.
20+
21+
## Requirements
22+
23+
This sample uses a `grid` texture (available below) to draw to the [RenderTarget2D](xref:Microsoft.Xna.Framework.Graphics.RenderTarget2D) before then rendering the contents of the `Render Target` to the screen as a texture.
24+
25+
![Grid Texture](images/grid.png)
26+
27+
Download the `Grid` texture and add it to your `Content Project` for this example. (see [How to Add Content](../content_pipeline/HowTo_GameContent_Add.md) for more information on this.)
28+
29+
## Creating a Render Target
30+
31+
1. Declare variables for a render target using the [RenderTarget2D](xref:Microsoft.Xna.Framework.Graphics.RenderTarget2D) class, for this example we will also be using a [Texture2D](xref:Microsoft.Xna.Framework.Graphics.Texture2D) for the "grid" texture we will output to the `Render Target`.
32+
33+
```csharp
34+
private GraphicsDeviceManager _graphics;
35+
private SpriteBatch _spriteBatch;
36+
private Texture2D grid;
37+
private RenderTarget2D renderTarget;
38+
```
39+
40+
2. Load the "grid" texture, which contains vertical and horizontal lines.
41+
42+
```csharp
43+
protected override void LoadContent()
44+
{
45+
// Create a new SpriteBatch, which can be used to draw textures.
46+
_spriteBatch = new SpriteBatch(GraphicsDevice);
47+
48+
// using "grid" which matches the NAME of the grid texture in the content project.
49+
grid = Content.Load<Texture2D>("grid");
50+
}
51+
```
52+
53+
3. While still in the `LoadContent` method, create the render target, giving it the same size as either the Texture (shown below) or the display back buffer (if you are rendering full screen), ideally in the [Game.LoadContent](xref:Microsoft.Xna.Framework.Game#Microsoft_Xna_Framework_Game_LoadContent) method or later.
54+
55+
```csharp
56+
renderTarget = new RenderTarget2D(
57+
GraphicsDevice,
58+
grid.Width,
59+
grid.Height);
60+
```
61+
62+
4. Render the "grid" texture to the render target.
63+
64+
Rendering to a [RenderTarget2D](xref:Microsoft.Xna.Framework.Graphics.RenderTarget2D) changes the Graphics Device output to write to a `texture` instead of the screen. Once you have finished rendering to the [RenderTarget2D](xref:Microsoft.Xna.Framework.Graphics.RenderTarget2D) you **MUST** reset the [GraphicsDevice](xref:Microsoft.Xna.Framework.Graphics.GraphicsDevice) Render Target to `null` to return to drawing to the screen / back buffer.
65+
66+
The example function below, sets the render target on the device, draws the texture (to the render target) using a [SpriteBatch](xref:Microsoft.Xna.Framework.Graphics.SpriteBatch). When rendering is complete, it then resets the device render target to `null` (which resets the device to the back buffer).
67+
68+
```csharp
69+
private void DrawRenderTarget()
70+
{
71+
// Set the device to the render target
72+
GraphicsDevice.SetRenderTarget(renderTarget);
73+
74+
// Clear the graphics buffer to a solid color
75+
GraphicsDevice.Clear(Color.Black);
76+
77+
// Draw the "grid" texture to the graphics buffer, currently outputting to the Render Texture.
78+
_spriteBatch.Begin();
79+
_spriteBatch.Draw(grid, Vector2.Zero, Color.White);
80+
_spriteBatch.End();
81+
82+
// Reset the device to the back buffer
83+
GraphicsDevice.SetRenderTarget(null);
84+
}
85+
```
86+
87+
5. Draw the render target texture to the back buffer.
88+
89+
With the render target populated using the `DrawRenderTarget` function, we can then draw the output to the screen.
90+
91+
```csharp
92+
protected override void Draw(GameTime gameTime)
93+
{
94+
// Populate the RenderTarget
95+
DrawRenderTarget();
96+
97+
// Clear the screen
98+
GraphicsDevice.Clear(Color.CornflowerBlue);
99+
100+
// Draw the contents of the Render Target texture
101+
_spriteBatch.Begin();
102+
_spriteBatch.Draw(renderTarget,
103+
new Vector2(200, 50), // x,y position
104+
new Rectangle(0, 0, 32, 32), // just one grid
105+
Color.White // no color scaling
106+
);
107+
_spriteBatch.End();
108+
109+
base.Draw(gameTime);
110+
}
111+
```
112+
113+
The final output should look like the following:
114+
115+
![Output](images/HowTo_Create_a_RenderTarget_Final.png)
116+
117+
Rendering a 32 by 32 square from the RenderTarget texture to a position 200 x 50 on the screen.
118+
119+
120+
## See Also
121+
122+
- [How to create a Basic Effect](HowTo_Create_a_BasicEffect.md)
123+
124+
### Concepts
125+
126+
- [What Is a Render Target?](../../whatis/graphics/WhatIs_Render_Target.md)
127+
- [What Is a Back Buffer?](../../whatis/graphics/WhatIs_BackBuffer.md)
128+
129+
### Reference
130+
131+
- [GraphicsDevice](xref:Microsoft.Xna.Framework.Graphics.GraphicsDevice)
132+
- [RenderTarget2D](xref:Microsoft.Xna.Framework.Graphics.RenderTarget2D)
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
---
2+
title: How to create a State Object
3+
description: Demonstrates how to create a state object using any of the state object classes.
4+
requireMSLicense: true
5+
---
6+
7+
## Overview
8+
9+
In this example, we will demonstrate how to create a state object using any of the state object classes: [BlendState](xref:Microsoft.Xna.Framework.Graphics.BlendState), [DepthStencilState](xref:Microsoft.Xna.Framework.Graphics.DepthStencilState), [RasterizerState](xref:Microsoft.Xna.Framework.Graphics.RasterizerState), or [SamplerState](xref:Microsoft.Xna.Framework.Graphics.SamplerState).
10+
11+
## To create a state object
12+
13+
1. Declare three state object variables as fields in your game.
14+
15+
This example declares three rasterizer state objects and uses them to change the culling state.
16+
17+
```csharp
18+
RasterizerState rsCullNone;
19+
```
20+
21+
2. Create a customizable state object.
22+
23+
Create a state object from the [RasterizerState](xref:Microsoft.Xna.Framework.Graphics.RasterizerState) class and initialize it by explicitly setting the cull mode.
24+
25+
```csharp
26+
rsCullNone = new RasterizerState();
27+
rsCullNone.CullMode = CullMode.None;
28+
rsCullNone.FillMode = FillMode.WireFrame;
29+
rsCullNone.MultiSampleAntiAlias = false;
30+
```
31+
32+
3. Respond to the user pressing the A key on a gamepad to change the culling mode.
33+
34+
The application starts with culling turned off; toggle between culling modes by pushing the A key on a gamepad. Unlike a customizable state object, use a built-in state object to create an object with a set of predefined state.
35+
36+
```csharp
37+
if (GamePad.GetState(PlayerIndex.One).Buttons.A == ButtonState.Pressed)
38+
{
39+
changeState = true;
40+
}
41+
42+
if ((changeState) && (GamePad.GetState(PlayerIndex.One).Buttons.A == ButtonState.Released))
43+
{
44+
if (GraphicsDevice.RasterizerState.CullMode == CullMode.None)
45+
{
46+
GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
47+
}
48+
else if (GraphicsDevice.RasterizerState.CullMode == CullMode.CullCounterClockwiseFace)
49+
{
50+
GraphicsDevice.RasterizerState = RasterizerState.CullClockwise;
51+
}
52+
else if (GraphicsDevice.RasterizerState.CullMode == CullMode.CullClockwiseFace)
53+
{
54+
GraphicsDevice.RasterizerState = rsCullNone;
55+
}
56+
57+
changeState = false;
58+
}
59+
```
60+
61+
Try this technique with the [HowTo Create a BasicEffect](./HowTo_Create_a_BasicEffect.md) sample and see what kinds of effects the above functionality applies.

0 commit comments

Comments
 (0)