XNA 3.1 to XNA 4.0 Conversion Cheat Sheet

转自:http://nelxon.com/resources/xna-3-1-to-xna-4-0-cheatsheet.php

Nelxon here again providing yet another resource for XNA Game developers. There are a few sites available to help us convert those XNA 3.1 projects to XNA 4.0, but it seems many of us are still have problems migrating successfully and easily. Its a pain to visit multiple sites and pages only to find corrections for 1 to 3 errors and still have hundreds more left.

After losing many hours of production time, I decided it would be more convenient to have a simple cheat sheet  - (collection of code snippets XNA 3.1 to XNA 4.0)  to help me convert projects faster with less difficulty. So far, this cheat sheet has helped me convert over a dozen XNA 3.1 projects, which removed at least 90% of the errors due to the code breaking changes from XNA 4.0. The remaining errors I could resolve myself or simply ask for help on the forums. 5 errors are better than 50…

I decided to share this cheat sheet because I am constantly reading forums where developers discuss having the same problems converting their projects. I figured maybe other developers would find this useful as well. These code snippets were created from comparing the XNA 3.1 creator’s club educational samples to the newer XNA 4.0 samples. However do not consider this page as a tutorial, it is a list of examples to help you see the difference between XNA 3.1 and XNA 4.0 syntax and provided to help you learn by example.

DON’T FORGET TO BACKUP YOUR WORK FIRST, BEFORE YOU TRY TO CONVERT IT.

Bookmark this page, because it may come in handy if you find a good library written in XNA 3.1.
If a developer is having problems converting their projects, please send them to this page, it may help.
List of errors resolved using this cheat sheet:

The name ‘SpriteBlendMode‘ does not exist in the current context
The name ‘SaveStateMode‘ does not exist in the current context

‘Microsoft.Xna.Framework.Graphics.GraphicsDevice‘ does not contain a definition for ‘RenderState‘…

‘Microsoft.Xna.Framework.Graphics.Effect‘ does not contain a definition for ‘Begin‘ …
‘Microsoft.Xna.Framework.Graphics.Effect‘ does not contain a definition for ‘End‘..
‘Microsoft.Xna.Framework.Graphics.Effect‘ does not contain a definition for ‘CommitChanges‘ …
‘Microsoft.Xna.Framework.Graphics.EffectPass‘ does not contain a definition for ‘Begin‘ …
‘Microsoft.Xna.Framework.Graphics.EffectPass‘ does not contain a definition for ‘End‘ ….
No overload for method ‘Clone‘ takes 1 arguments

The name ‘ShaderProfile‘ does not exist in the current context
‘Microsoft.Xna.Framework.GameTime‘ does not contain a definition for ‘TotalRealTime‘ …
‘Microsoft.Xna.Framework.Color‘ does not contain a definition for ‘TransparentBlack‘ …

The type or namespace name ‘ResolveTexture2D‘ could not be found …
‘Microsoft.Xna.Framework.Graphics.GraphicsDevice‘ does not contain a definition for ‘ResolveBackBuffer‘…
The type or namespace name ‘DepthStencilBuffer‘ could not be found …

‘Microsoft.Xna.Framework.Graphics.RenderTarget2D‘ does not contain a constructor that takes 5 arguments
‘Microsoft.Xna.Framework.Graphics.RenderTarget2D‘ does not contain a definition for ‘GetTexture‘ …

‘Microsoft.Xna.Framework.Graphics.PresentationParameters‘ does not contain a definition for ‘MultiSampleType‘ …
‘Microsoft.Xna.Framework.Graphics.PresentationParameters‘ does not contain a definition for ‘MultiSampleQuality‘ …

The best overloaded method match for ‘Microsoft.Xna.Framework.Graphics.GraphicsDevice.SetRenderTarget

‘Microsoft.Xna.Framework.Graphics.GraphicsDevice‘ does not contain a definition for ‘VertexDeclaration
‘Microsoft.Xna.Framework.Graphics.GraphicsDevice‘ does not contain a definition for ‘Vertices

‘Microsoft.Xna.Framework.Graphics.VertexPositionTexture‘ does not contain a definition for ‘SizeInBytes
‘Microsoft.Xna.Framework.Graphics.VertexPositionTexture‘ does not contain a definition for ‘VertexElements

‘Microsoft.Xna.Framework.Graphics.ModelMesh‘ does not contain a definition for ‘IndexBuffer
‘Microsoft.Xna.Framework.Graphics.ModelMesh‘ does not contain a definition for ‘VertexBuffer

‘Microsoft.Xna.Framework.Graphics.ModelMeshPart‘ does not contain a definition for ‘BaseVertex
‘Microsoft.Xna.Framework.Graphics.ModelMeshPart‘ does not contain a definition for ‘StreamOffset
‘Microsoft.Xna.Framework.Graphics.ModelMeshPart‘ does not contain a definition for ‘VertexStride

‘Microsoft.Xna.Framework.Storage.StorageContainer‘ does not contain a definition for ‘TitleLocation
‘Microsoft.Xna.Framework.Storage.StorageContainer‘ does not contain a definition for ‘Path
‘Microsoft.Xna.Framework.Storage.StorageDevice‘ does not contain a definition for ‘OpenContainer
‘Microsoft.Xna.Framework.GamerServices.Guide‘ does not contain a definition for ‘BeginShowStorageDeviceSelector
‘Microsoft.Xna.Framework.GamerServices.Guide‘ does not contain a definition for ‘EndShowStorageDeviceSelector

syntax error: unexpected token ‘VertexShader
syntax error: unexpected token ‘PixelShader
error X3539: ps_1_x is no longer supported

Other Issues:
XNA model is drawn inside out, looks transparent, missing vertices or just doesn’t look right…

List of Examples Converting XNA 3.1 to XNA 4.0

SpriteBlendMode, SaveStateMode
1
2
// XNA 3.1
sprite.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Deferred, SaveStateMode.SaveState);

1
2
// XNA 4.0
sprite.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);

1
2
3
// XNA 3.1
// Sort the object layer and player sprite according to depth
spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.BackToFront, SaveStateMode.None);

1
2
3
// XNA 4.0
// Sort the object layer and player sprite according to depth
spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);

1
2
// XNA 3.1
sprite.Begin(SpriteBlendMode.None, SpriteSortMode.Immediate, SaveStateMode.SaveState);

1
2
// XNA 4.0
sprite.Begin(SpriteSortMode.Immediate, BlendState.Opaque);

1
2
3
4
5
6
// XNA 3.1
// Draw the background image.
spriteBatch.Begin(SpriteBlendMode.None);
Viewport viewport = GraphicsDevice.Viewport;
spriteBatch.Draw(background, new Rectangle(0, 0, viewport.Width, viewport.Height), Color.White);
spriteBatch.End();

1
2
3
4
5
// XNA 4.0
// Draw the background image.
spriteBatch.Begin(0, BlendState.Opaque);
spriteBatch.Draw(background, GraphicsDevice.Viewport.Bounds, Color.White);
spriteBatch.End();

RenderState
1
2
3
4
5
6
7
8
9
10
// XNA 3.1
// enable alpha blending and disable depth write
GraphicsDevice.RenderState.AlphaBlendEnable = true;
GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha;
GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;
GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = true;
GraphicsDevice.RenderState.AlphaBlendOperation = BlendFunction.Add;
GraphicsDevice.RenderState.AlphaSourceBlend = Blend.One;
GraphicsDevice.RenderState.AlphaDestinationBlend = Blend.One;
GraphicsDevice.RenderState.DepthBufferWriteEnable = false;

1
2
3
4
// XNA 4.0
// enable alpha blending and disable depth write
GraphicsDevice.BlendState = BlendState.AlphaBlend;
GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead;

1
2
3
4
5
// XNA 3.1
// reset blend and depth write
GraphicsDevice.RenderState.AlphaBlendEnable = false;
GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = false;
GraphicsDevice.RenderState.DepthBufferWriteEnable = true;

1
2
3
4
// XNA 4.0
// reset blend and depth write
GraphicsDevice.BlendState = BlendState.Additive;
GraphicsDevice.DepthStencilState = DepthStencilState.Default;

1
2
3
// XNA 3.1
// enable depth buffering
GraphicsDevice.RenderState.DepthBufferEnable = true;

1
2
3
// XNA 4.0
// enable depth buffering
GraphicsDevice.DepthStencilState = DepthStencilState.Default;

1
2
3
4
// XNA 3.1
//disable depth buffering
GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
GraphicsDevice.RenderState.DepthBufferEnable = false;

1
2
3
// XNA 4.0
//disable depth buffering
GraphicsDevice.DepthStencilState = DepthStencilState.None;

1
2
3
4
5
6
// XNA 3.1
// set additive blend (zero on alpha)
GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
GraphicsDevice.RenderState.AlphaBlendEnable = true;
GraphicsDevice.RenderState.SourceBlend = Blend.One;
GraphicsDevice.RenderState.DestinationBlend = Blend.One;

1
2
3
4
// XNA 4.0
// set additive blend (zero on alpha)
GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead;
GraphicsDevice.BlendState = BlendState.AlphaBlend;

1
2
3
4
5
// XNA 3.1
// restore blend modes
GraphicsDevice.RenderState.DepthBufferWriteEnable = true;
GraphicsDevice.RenderState.AlphaBlendEnable = false;
GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = false;

1
2
3
4
// XNA 4.0
// restore blend modes
GraphicsDevice.BlendState = BlendState.Opaque;
GraphicsDevice.DepthStencilState = DepthStencilState.Default;

1
2
3
4
5
6
7
// XNA 3.1
// set alpha blend and no depth test or write
GraphicsDevice.RenderState.DepthBufferEnable = false;
GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
GraphicsDevice.RenderState.AlphaBlendEnable = true;
GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha;
GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;

1
2
3
4
// XNA 4.0
// set alpha blend and no depth test or write
GraphicsDevice.DepthStencilState = DepthStencilState.None;
GraphicsDevice.BlendState = BlendState.AlphaBlend;

1
2
3
4
5
// XNA 3.1
// Set suitable renderstates for drawing a 3D model
GraphicsDevice.RenderState.AlphaBlendEnable = false;
GraphicsDevice.RenderState.AlphaTestEnable = false;
GraphicsDevice.RenderState.DepthBufferEnable = true;

1
2
3
4
// XNA 4.0
// Set suitable renderstates for drawing a 3D model
GraphicsDevice.BlendState = BlendState.Opaque;
GraphicsDevice.DepthStencilState = DepthStencilState.Default;

1
2
3
4
5
// XNA 3.1
// additive blend
GraphicsDevice.RenderState.AlphaBlendEnable = true;
GraphicsDevice.RenderState.SourceBlend = Blend.One;
GraphicsDevice.RenderState.DestinationBlend = Blend.One;

1
2
3
// XNA 4.0
// additive blend
GraphicsDevice.BlendState = BlendState.Additive;

1
2
3
// XNA 3.1
// set additive blend
GraphicsDevice.RenderState.DestinationBlend = Blend.One;

1
2
3
// XNA 4.0
// set additive blend
GraphicsDevice.BlendState = BlendState.Additive;

1
2
3
// XNA 3.1
// set alpha blend
GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;

1
2
3
// XNA 4.0
// set alpha blend
GraphicsDevice.BlendState = BlendState.AlphaBlend;

1
2
// XNA 3.1
GraphicsDevice.RenderState.CullMode = CullMode.CullCounterClockwiseFace;

1
2
// XNA 4.0
GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// XNA 3.1
// set render states
GraphicsDevice.RenderState.DepthBufferEnable = false;
GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
GraphicsDevice.RenderState.AlphaBlendEnable = true;
GraphicsDevice.RenderState.SourceBlend = Blend.One;
GraphicsDevice.RenderState.DestinationBlend = Blend.One;
GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = true;
GraphicsDevice.RenderState.AlphaBlendOperation = BlendFunction.Add;
GraphicsDevice.RenderState.AlphaDestinationBlend = Blend.Zero;
GraphicsDevice.RenderState.AlphaSourceBlend = Blend.Zero;
      // drawing code here..
// restore render states
GraphicsDevice.RenderState.DepthBufferEnable = true;
GraphicsDevice.RenderState.DepthBufferWriteEnable = true;
GraphicsDevice.RenderState.AlphaBlendEnable = false;
GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = false;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// XNA 4.0
//save the states
DepthStencilState ds = GraphicsDevice.DepthStencilState;
BlendState bs = GraphicsDevice.BlendState;
//set render states
GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead;
GraphicsDevice.BlendState = BlendState.AlphaBlend;
       // drawing code here..
// restore render states
GraphicsDevice.DepthStencilState = ds;
GraphicsDevice.BlendState = bs;

Effect and EffectPass, Begin(), End(), CommitChanges(), Clone()
1
2
3
4
5
6
7
// apply effect XNA 3.1
blurEffect.CommitChanges();
blurEffect.Begin(SaveStateMode.SaveState);
blurEffect.CurrentTechnique.Passes[0].Begin();
GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 2);
blurEffect.CurrentTechnique.Passes[0].End();
blurEffect.End();

1
2
3
// apply effect XNA 4.0
blurEffect.CurrentTechnique.Passes[0].Apply();
GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 2);

1
2
3
// XNA 3.1
// commit effect changes
effect.CommitChanges();

1
2
3
// XNA 4.0
//  you will need to call EffectPass.Apply() if any of the effect properties change
// Otherwise Delete it.

1
2
3
4
// XNA 3.1
// begin effect
effect.Begin(SaveStateMode.SaveState);
effect.CurrentTechnique.Passes[0].Begin();

1
2
3
// XNA 4.0
// begin effect
effect.CurrentTechnique.Passes[0].Apply();

1
2
3
4
// XNA 3.1
// end effect
effect.CurrentTechnique.Passes[0].End();
effect.End();

1
2
// XNA 4.0
// Delete it. No longer needed.

1
2
3
// XNA 3.1
// Make a clone of our replacement effect
Effect newEffect = replacementEffect.Clone(replacementEffect.GraphicsDevice);

1
2
3
// XNA 4.0
// Make a clone of our replacement effect. 3.1
Effect newEffect = replacementEffect.Clone();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// XNA 3.1
// Activate the appropriate effect technique
postprocessEffect.CurrentTechnique = postprocessEffect.Techniques[effectTechniqueName];    
// Draw a fullscreen sprite to apply the postprocessing effect.
spriteBatch.Begin(SpriteBlendMode.None,SpriteSortMode.Immediate, SaveStateMode.None);
postprocessEffect.Begin();
postprocessEffect.CurrentTechnique.Passes[0].Begin();
spriteBatch.Draw(sceneRenderTarget.GetTexture(), Vector2.Zero, Color.White);
spriteBatch.End();
postprocessEffect.CurrentTechnique.Passes[0].End();
postprocessEffect.End();

1
2
3
4
5
6
7
8
// XNA 4.0
// Activate the appropriate effect technique
postprocessEffect.CurrentTechnique = postprocessEffect.Techniques[effectTechniqueName];
// Draw a fullscreen sprite to apply the postprocessing effect.
spriteBatch.Begin(0, BlendState.Opaque, null, null, null, postprocessEffect);
spriteBatch.Draw(sceneRenderTarget, Vector2.Zero, Color.White);
spriteBatch.End();

ShaderProfile, TotalRealTime, TransparentBlack
1
2
3
// XNA 3.1
graphics.MinimumPixelShaderProfile = ShaderProfile.PS_3_0; //any PS number...
graphics.MinimumVertexShaderProfile = ShaderProfile.VS_3_0;//any VS number...

1
2
// XNA 4.0
// Delete it. No longer needed.

1
2
// XNA 3.1
float myTime = (float)gameTime.TotalRealTime.TotalSeconds * 0.2f;

1
2
// XNA 4.0
float myTime = (float)gameTime.TotalGameTime.TotalSeconds * 0.2f;

1
2
// XNA 3.1
GraphicsDevice.Clear(Color.TransparentBlack);

1
2
// XNA 4.0
GraphicsDevice.Clear(Color.Transparent);

ResolveTexture2D, ResolveBackBuffer, RenderTarget2D, GetTexture, DepthStencilBuffer, PresentationParameters, MultiSampleType, MultiSampleQuality, SetRenderTarget
1
2
// XNA 3.1
ResolveTexture2D sceneMap;

1
2
// XNA 4.0
RenderTarget2D sceneMap;

1
2
3
4
5
6
// XNA 3.1
// Look up the resolution and format of our main backbuffer.
PresentationParameters pp = GraphicsDevice.PresentationParameters;
// Create a texture for reading back the backbuffer contents.
sceneMap = new ResolveTexture2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, 1, pp.BackBufferFormat);

1
2
3
4
5
6
7
8
9
10
11
// XNA 4.0
// Look up the resolution and format of our main backbuffer.
PresentationParameters pp = GraphicsDevice.PresentationParameters;
// Create a texture for reading back the backbuffer contents.
sceneMap = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false, pp.BackBufferFormat,
                                pp.DepthStencilFormat);
//or
sceneMap = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false, pp.BackBufferFormat,
                                pp.DepthStencilFormat, pp.MultiSampleCount, RenderTargetUsage.DiscardContents);

1
2
// XNA 3.1
GraphicsDevice.ResolveBackBuffer(sceneMap);

1
2
// XNA 4.0
GraphicsDevice.SetRenderTarget(sceneMap);

1
2
3
4
5
6
// XNA 3.1
int width = GraphicsDevice.Viewport.Width;
int height = GraphicsDevice.Viewport.Height;
// create render target
myRenderTarget = new RenderTarget2D(GraphicsDevice, width, height, 1, SurfaceFormat.Color);

1
2
3
4
5
6
// XNA 4.0
int width = GraphicsDevice.Viewport.Width;
int height = GraphicsDevice.Viewport.Height;
// create render target
myRenderTarget = new RenderTarget2D(GraphicsDevice, width, height, true, SurfaceFormat.Color, DepthFormat.Depth24);

1
2
3
4
5
6
// XNA 3.1
PresentationParameters pp = GraphicsDevice.PresentationParameters;
// Create custom rendertarget
sceneRenderTarget = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, 1,
                                   pp.BackBufferFormat, pp.MultiSampleType, pp.MultiSampleQuality);

1
2
3
4
5
6
7
// XNA 4.0
PresentationParameters pp = GraphicsDevice.PresentationParameters;
// Create custom rendertarget
sceneRenderTarget = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false,
                                   pp.BackBufferFormat, pp.DepthStencilFormat, pp.MultiSampleCount,
                                   RenderTargetUsage.DiscardContents);

1
2
3
4
5
6
7
8
9
// XNA 3.1/div>

PresentationParameters pp = GraphicsDevice.PresentationParameters;
// Setup a DepthBuffer
drawBuffer = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, 1,
                                SurfaceFormat.Color, pp.MultiSampleType, pp.MultiSampleQuality);
drawDepthBuffer = new DepthStencilBuffer(GraphicsDevice, pp.AutoDepthStencilFormat,
                                            pp.MultiSampleType, pp.MultiSampleQuality);

1
2
3
4
5
6
7
8
// XNA 4.0
PresentationParameters pp = GraphicsDevice.PresentationParameters;
// Setup a DepthBuffer
drawBuffer = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, true,
                                SurfaceFormat.Color,DepthFormat.Depth24Stencil8,
                                pp.MultiSampleCount, RenderTargetUsage.DiscardContents);
//NOTE:  DepthStencilBuffer class no longer exists

1
2
// XNA 3.1
spriteBatch.Draw(myRenderTarget.GetTexture(), Vector2.Zero, Color.White);

1
2
// XNA 4.0
spriteBatch.Draw(myRenderTarget, Vector2.Zero, Color.White); // NOTE: ".GetTexure()"  No longer needed

1
2
// XNA 3.1
Texture2D myTexture = myRenderTarget.GetTexture();

1
2
// XNA 4.0
Texture2D myTexture = myRenderTarget; // NOTE: ".GetTexure()"  No longer needed

1
2
// XNA 3.1
GraphicsDevice.SetRenderTarget(0, myRenderTarget);

1
2
// XNA 4.0
GraphicsDevice.SetRenderTarget(myRenderTarget);

1
2
3
4
// XNA 3.1
// Set the two render targets
GraphicsDevice.SetRenderTarget(0, colorRT);
GraphicsDevice.SetRenderTarget(1, depthRT);

1
2
3
// XNA 4.0
// Set the two render targets
GraphicsDevice.SetRenderTargets(colorRT, depthRT);

1
2
// XNA 3.1
GraphicsDevice.SetRenderTarget(0, null);

1
2
// XNA 4.0
GraphicsDevice.SetRenderTarget(null);

1
2
3
4
5
6
7
8
9
// XNA 3.1
// resolve the backbuffer as the depth map
GraphicsDevice.ResolveBackBuffer(depthMap);
// draw the scene image again, blur it with the depth map
GraphicsDevice.Textures[1] = depthMap;
Viewport viewport = GraphicsDevice.Viewport;
dofEffect.CurrentTechnique = depthBlurTechnique;
DrawFullscreenQuad(sceneMap, viewport.Width, viewport.Height, dofEffect);

1
2
3
4
5
6
7
8
9
10
// XNA 4.0
// resolve the backbuffer as the depth map
GraphicsDevice.SetRenderTarget(null);
// draw the scene image again, blur it with the depth map
GraphicsDevice.Textures[1] = depthMap;
GraphicsDevice.SamplerStates[1] = SamplerState.PointClamp;
Viewport viewport = GraphicsDevice.Viewport;
dofEffect.CurrentTechnique = depthBlurTechnique;
DrawFullscreenQuad(sceneMap, viewport.Width, viewport.Height, dofEffect);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// XNA 3.1
ResolveTexture2D resolveTarget;
RenderTarget2D renderTarget1;
RenderTarget2D renderTarget2;
// Look up the resolution and format of our main backbuffer.
PresentationParameters pp = GraphicsDevice.PresentationParameters;
int width = pp.BackBufferWidth;
int height = pp.BackBufferHeight;
SurfaceFormat format = pp.BackBufferFormat;
// Create a texture for reading back the backbuffer contents.
resolveTarget = new ResolveTexture2D(GraphicsDevice, width, height, 1, format);
// Create two rendertargets half size for the bloom processing.
width /= 2;
height /= 2;
renderTarget1 = new RenderTarget2D(GraphicsDevice, width, height, 1,format);
renderTarget2 = new RenderTarget2D(GraphicsDevice, width, height, 1,format);
// ... In the Draw Method...
GraphicsDevice.ResolveBackBuffer(resolveTarget);
// ...apply effect and draw pass 1...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// XNA 4.0
RenderTarget2D sceneRenderTarget;
RenderTarget2D renderTarget1;
RenderTarget2D renderTarget2;
// Look up the resolution and format of our main backbuffer.
PresentationParameters pp = GraphicsDevice.PresentationParameters;
int width = pp.BackBufferWidth;
int height = pp.BackBufferHeight;
SurfaceFormat format = pp.BackBufferFormat;
// Create a texture for rendering the main scene, prior to applying bloom.
sceneRenderTarget = new RenderTarget2D(GraphicsDevice, width, height, false,
                                       format, pp.DepthStencilFormat, pp.MultiSampleCount,
                                       RenderTargetUsage.DiscardContents);
// Create two rendertargets half size for the bloom processing.
width /= 2;
height /= 2;
renderTarget1 = new RenderTarget2D(GraphicsDevice, width, height, false, format, DepthFormat.None);
renderTarget2 = new RenderTarget2D(GraphicsDevice, width, height, false, format, DepthFormat.None);
// ...In the Draw Method...
GraphicsDevice.SetRenderTarget(sceneRenderTarget);
GraphicsDevice.SamplerStates[1] = SamplerState.LinearClamp;
// ...apply effect and draw pass 1....

VertexDeclaration, Vertices, VertexElements, SizeInBytes
1
2
3
// XNA 3.1
// Vertex declaration for rendering our 3D model.
GraphicsDevice.VertexDeclaration = new VertexDeclaration(VertexPositionTexture.VertexElements);

1
2
// XNA 4.0
// Delete it. No longer needed.

1
2
3
4
// XNA 3.1
// set vertex buffer and declaration
GraphicsDevice.VertexDeclaration = vertexDeclaration;
GraphicsDevice.Vertices[0].SetSource(vertexBuffer, 0, VertexPositionTexture.SizeInBytes);

1
2
3
// XNA 4.0
// set vertex buffer and declaration
GraphicsDevice.SetVertexBuffer(vertexBuffer);

1
2
3
// XNA 3.1
// create vertex declaration
vertexDeclaration = new VertexDeclaration(GraphicsDevice, VertexPositionTexture.VertexElements);

1
2
3
// XNA 4.0
// create vertex declaration
vertexDeclaration = new VertexDeclaration(VertexPositionTexture.VertexDeclaration.GetVertexElements());

1
2
3
4
// XNA 3.1
// reset vertex buffer declaration
GraphicsDevice.VertexDeclaration = null;
GraphicsDevice.Vertices[0].SetSource(null, 0, 0);

1
2
3
// XNA 4.0
// reset vertex buffer declaration
GraphicsDevice.SetVertexBuffer(null);

1
2
3
4
5
6
7
// XNA 3.1
// the vertices array
VertexPositionNormalTexture[] vertices = new VertexPositionNormalTexture[100];
// set new particles to vertex buffer
vertexBuffer.SetData<VertexPositionNormalTexture>(VertexPositionNormalTexture.SizeInBytes * vertexCount,
                    vertices,vertexCount,count,VertexPositionNormalTexture.SizeInBytes);

1
2
3
4
5
6
// XNA 4.0
// the vertices array
VertexPositionNormalTexture[] vertices = new VertexPositionNormalTexture[100];
// set new particles to vertex buffer
vertexBuffer.SetData<VertexPositionNormalTexture>(vertices);

VertexBuffer, StreamOffset, VertexStride, IndexBuffer, BaseVertex
1
2
3
4
5
6
7
8
9
10
11
12
// XNA 3.1
// for each mesh part
foreach (ModelMeshPart meshPart in mesh.MeshParts)
{
    // if primitives to render
    if (meshPart.PrimitiveCount > 0)
    {
        // setup vertices and indices
        GraphicsDevice.VertexDeclaration = meshPart.VertexDeclaration;
        GraphicsDevice.Vertices[0].SetSource(mesh.VertexBuffer, meshPart.StreamOffset, meshPart.VertexStride);
        GraphicsDevice.Indices = mesh.IndexBuffer;
        ...

1
2
3
4
5
6
7
8
9
10
11
12
13
// XNA 4.0
GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap; // may be needed in some cases...
// for each mesh part
foreach (ModelMeshPart meshPart in mesh.MeshParts)
{
    // if primitives to render
    if (meshPart.PrimitiveCount > 0)
    {
        // setup vertices and indices
        GraphicsDevice.SetVertexBuffer(meshPart.VertexBuffer);
        GraphicsDevice.Indices = meshPart.IndexBuffer;
        ...

1
2
3
4
5
// XNA 3.1
// draw primitives
GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList,
    meshPart.BaseVertex, 0, meshPart.NumVertices,
    meshPart.StartIndex, meshPart.PrimitiveCount);

1
2
3
4
// XNA 4.0
// draw primitives
GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0,
    meshPart.NumVertices, meshPart.StartIndex, meshPart.PrimitiveCount);

Points, PointSpriteEnable, PointSizeMax, PointList
1
2
3
4
// XNA 3.1
// create the vertex buffer
vertexBuffer = new VertexBuffer(GraphicsDevice, typeof(VertexPositionNormalTexture),
                                250, BufferUsage.WriteOnly | BufferUsage.Points);

1
2
3
4
// XNA 4.0
// create the vertex buffer
vertexBuffer = new VertexBuffer(GraphicsDevice, typeof(VertexPositionNormalTexture),
                                250, BufferUsage.WriteOnly | BufferUsage.None);

1
2
3
4
// XNA 3.1
// enable point sprite 3.1
GraphicsDevice.RenderState.PointSpriteEnable = true;
GraphicsDevice.RenderState.PointSizeMax = 128;

1
2
// XNA 4.0
// Delete it. No longer available.

1
2
3
// XNA 3.1
// draw the point sprites
GraphicsDevice.DrawPrimitives(PrimitiveType.PointList, vertexPosition, numberVertices);

1
2
3
// XNA 4.0
// draw the point sprites
GraphicsDevice.DrawPrimitives(PrimitiveType.LineList, vertexPosition, numberVertices);

OpenContainer, BeginShowStorageDeviceSelector, EndShowStorageDeviceSelector, Path, TitleLocation, FileStream
1
2
3
// XNA 3.1
// open the container
StorageContainer storageContainer = storageDevice.OpenContainer("YourGameName");

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// XNA 4.0
//To make life easier simply create a method to replace the storageDevice.OpenContainer...
/// <summary>
/// Synchronously opens storage container
/// </summary>
private static StorageContainer OpenContainer(StorageDevice storageDevice, string saveGameName)
{
    IAsyncResult result = storageDevice.BeginOpenContainer(saveGameName, null, null);
    // Wait for the WaitHandle to become signaled.
    result.AsyncWaitHandle.WaitOne();
    StorageContainer container = storageDevice.EndOpenContainer(result);
    // Close the wait handle.
    result.AsyncWaitHandle.Close();
    return container;
}
// open the container
StorageContainer storageContainer = OpenContainer(storageDevice, "YourGameName");

1
2
3
// XNA 3.1
// retrieve the storage device
Guide.BeginShowStorageDeviceSelector(GetStorageDeviceResult, retrievalDelegate);

1
2
3
4
5
6
// XNA 4.0
// retrieve the storage device
if (!Guide.IsVisible)
{
    StorageDevice.BeginShowSelector(GetStorageDeviceResult, retrievalDelegate);
}

1
2
3
// XNA 3.1
// retrieve and store the storage device
storageDevice = Guide.EndShowStorageDeviceSelector(result);

1
2
3
// XNA 4.0
// retrieve and store the storage device
storageDevice = StorageDevice.EndShowSelector(result);

1
2
3
// XNA 3.1
// get the level setup files
string[] filenames = Directory.GetFiles(storageContainer.Path, "LevelSetup*.xml");

1
2
3
// XNA 4.0
// get the level setup files
string[] filenames = storageContainer.GetFileNames("LevelSetup*.xml"");

1
2
3
4
5
6
// XNA 3.1
// save game level data
using (FileStream stream = new FileStream(Path.Combine(storageContainer.Path, levelFilename), FileMode.Create))
{
    new XmlSerializer(typeof(SaveGameLevel)).Serialize(stream, levelData);
}

1
2
3
4
5
6
// XNA 4.0
// save game level data
using (Stream stream = storageContainer.OpenFile(levelFilename, FileMode.Create))
{
    new XmlSerializer(typeof(SaveGameLevel)).Serialize(stream, levelData);
}

1
2
3
4
5
6
7
8
9
// XNA 3.1
// Delete the saved game level data.
using (StorageContainer storageContainer = storageDevice.OpenContainer("saveGameName"))
{
    File.Delete(Path.Combine(storageContainer.Path, saveGameLevel.FileName));
    File.Delete(Path.Combine(storageContainer.Path, "SaveGameLevel" +
        Path.GetFileNameWithoutExtension(saveGameLevel.FileName).Substring(8) +".xml"));
}

1
2
3
4
5
6
7
8
9
// XNA 4.0
// Delete the saved game level data. NOTE: using OpenContainer method created in previous example
using (StorageContainer storageContainer = OpenContainer(storageDevice, "saveGameName"))
{
    storageContainer.DeleteFile(saveGameLevel.FileName);
    storageContainer.DeleteFile("SaveGameLevel" +
        Path.GetFileNameWithoutExtension(saveGameLevel.FileName).Substring(8) + ".xml");
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// XNA 3.1
//Load the Next Level...
// Find the path of the next level.
string levelPath;
// Loop here so we can try again when we can't find a level.
while (true)
{
    // Try to find the next level. They are sequentially numbered txt files.
    levelPath = String.Format("Levels/{0}.txt", ++levelIndex);
    levelPath = Path.Combine(StorageContainer.TitleLocation, "Content/" + levelPath);
    if (File.Exists(levelPath))
        break;
    // If there isn't even a level 0, something has gone wrong.
    if (levelIndex == 0)
        throw new Exception("No levels found.");
    // Whenever we can't find a level, start over again at 0.
    levelIndex = -1;
}
// Unloads the content for the current level before loading the next one.
if (level != null)
    level.Dispose();
// Load the level.
level = new Level(Services, levelPath);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// XNA 4.0
// Load the Next Level...
// move to the next level
levelIndex = (levelIndex + 1) % numberOfLevels;
// Unloads the content for the current level before loading the next one.
if (level != null)
    level.Dispose();
// Load the level.
string levelPath = string.Format("Content/Levels/{0}.txt", levelIndex);
using (Stream fileStream = TitleContainer.OpenStream(levelPath))
    level = new Level(Services, fileStream, levelIndex);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// XNA 3.1
//Save the current state of the session, with the given storage device.
// check the parameter
if ((storageDevice == null) || !storageDevice.IsConnected)
{
    return;
}
// open the container
using (StorageContainer storageContainer = storageDevice.OpenContainer(Session.SaveGameContainerName))
{
    string filename;
    string descriptionFilename;
    // get the filenames
    if (overwriteDescription == null)
    {
        int saveGameIndex = 0;
        string testFilename;
        do
        {
            saveGameIndex++;
            testFilename = Path.Combine(storageContainer.Path, "SaveGame" + saveGameIndex.ToString() + ".xml");
        }
        while (File.Exists(testFilename));
        filename = testFilename;
        descriptionFilename = "SaveGameDescription" + saveGameIndex.ToString() + ".xml";
    }
    else
    {
        filename = Path.Combine(storageContainer.Path, overwriteDescription.FileName);
        descriptionFilename = "SaveGameDescription" +
            Path.GetFileNameWithoutExtension(overwriteDescription.FileName).Substring(8) + ".xml";
    }
    using (FileStream stream = new FileStream(filename, FileMode.Create))
    {
        using (XmlWriter xmlWriter = XmlWriter.Create(stream))
        {
            //create and write xml data...
        }
    }
   // create the save game description
    SaveGameDescription description = new SaveGameDescription();
    description.FileName = Path.GetFileName(filename);
    description.ChapterName = IsQuestLineComplete ? "Quest Line Complete" : Quest.Name;
    description.Description = DateTime.Now.ToString();
    using (FileStream stream = new FileStream(Path.Combine(storageContainer.Path, descriptionFilename), FileMode.Create))
    {
        new XmlSerializer(typeof(SaveGameDescription)).Serialize(stream, description);
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// XNA 4.0
//Save the current state of the session, with the given storage device.
// check the parameter
if ((storageDevice == null) || !storageDevice.IsConnected)
{
    return;
}
// open the container Note: using OpenContainer method from previous examples
using (StorageContainer storageContainer = OpenContainer(storageDevice, Session.SaveGameContainerName))
{
    string filename;
    string descriptionFilename;
    // get the filenames
    if (overwriteDescription == null)
    {
        int saveGameIndex = 0;
        string testFilename;
        do
        {
            saveGameIndex++;
            testFilename = "SaveGame" + saveGameIndex.ToString() + ".xml";
        }
        while (storageContainer.FileExists(testFilename));
        filename = testFilename;
        descriptionFilename = "SaveGameDescription" + saveGameIndex.ToString() + ".xml";
    }
    else
    {
        filename = overwriteDescription.FileName;
        descriptionFilename = "SaveGameDescription" +
            Path.GetFileNameWithoutExtension(overwriteDescription.FileName).Substring(8) + ".xml";
    }
    // Note: using Stream instead of FileStream...
    using (Stream stream = storageContainer.OpenFile(filename, FileMode.Create))
    {
        using (XmlWriter xmlWriter = XmlWriter.Create(stream))
        {
            //create and write xml data...
        }
    }
    // create the save game description
    SaveGameDescription description = new SaveGameDescription();
    description.FileName = Path.GetFileName(filename);
    description.ChapterName = IsQuestLineComplete ? "Quest Line Complete" : Quest.Name;
    description.Description = DateTime.Now.ToString();
    // Note: using Stream instead of FileStream...
    using (Stream stream = storageContainer.OpenFile(descriptionFilename, FileMode.Create))
    {
        new XmlSerializer(typeof(SaveGameDescription)).Serialize(stream, description);
    }
}

VertexShader, PixelShader, ps_1_x
Inside your shader (*.fx) files…
1
2
3
4
5
6
7
8
9
// XNA 3.1
VertexShaderOutput VertexShader(...)
{
    //some code
}
float4 PixelShader(...)
{
   // some code
}

1
2
3
4
5
6
7
8
9
10
11
// XNA 4.0
// VertexShader can not be used
VertexShaderOutput  VertexShaderFunction(...)
{
   // some code
}
// PixelShader can not be used
float4 PixelShaderFunction(...)
{
   // some code
}

1
2
3
4
5
6
7
8
9
// XNA 3.1
technique
{
    pass
    {
        VertexShader = compile vs_1_1 VertexShader();
        PixelShader  = compile ps_1_1 PixelShader();
    }
}

1
2
3
4
5
6
7
8
9
// XNA 4.0
technique
{
    pass
    {
        VertexShader = compile vs_2_0 VertexShaderFunction(); //VertexShader can not be used & set vs higher than 1_1
        PixelShader  = compile ps_2_0 PixelShaderFunction(); //PixelShader can not be used & set ps higher than 1_1
    }
}

XNA Model drawn inside out, slightly transparent, missing parts or just looks wrong

Add the following code before the XNA Model Draw code

1
2
3
4
5
// Set suitable renderstates for drawing a 3D model
GraphicsDevice.BlendState = BlendState.Opaque;
GraphicsDevice.DepthStencilState = DepthStencilState.Default;
// your model draw code starts here...

Well That’s all for now, I will continue to add more examples as needed.
Good luck with your games and Remember Indie Games are the future.

-Nelxon Studio

[转]xna 3.1 to xna 4.0相关推荐

  1. [转]XNA 3.1 转换到 XNA4.0 的备忘录

    XNA 3.1 转换到 XNA4.0 的备忘录 xna3.1与4.0的区别不小,但也不是很大,在转换一些项目时候下面的tip能给些帮助.原文地址是:http://blogs.msdn.com/b/sh ...

  2. XNA游戏:Hello XNA

    下面创建一个简单的Windows Phone 7的XNA 程序,只是一个Hello XNA的文本,从屏幕的左上角一直往右下角移动,通过该例子来开始Windows Phone 7 XNA的游戏编程. 新 ...

  3. XNA 3.1 转换到 XNA4.0 的备忘录

    本文原创版权归 博客园 Meta.Grfx 所有,转载请详细标明原创作者及出处,以示尊重! 作者:Meta.Grfx 原文:http://www.cnblogs.com/Baesky/archive/ ...

  4. XNA之RPG游戏开发教程之三

    本节在上一节基础上继续完善该游戏引擎,主要完成以下任务: (1)完善StartMenuScreen,同时添加一个GamePlayScreen页面 (2)创建一个新的控件,picture box (3) ...

  5. 《XNA高级编程:Xbox 360和Windows》1-2

    1.2免费获取XNA Game Studio Express 要开始编写代码,您必须确保已经安装了一些工具,其中IDE是您快速开始的一个非常重要的工具.如果您已经安装并配置了XNA Game Stud ...

  6. 本文将引导你使用XNA Game Studio Express一步一步地创建一个简单的游戏

    本文将引导你使用XNA Game Studio Express一步一步地创建一个简单的游戏 第1步: 安装软件 第2步: 创建新项目 第3步: 查看代码 第4步: 加入一个精灵 第5步: 使精灵可以移 ...

  7. 手把手教用XNA开发winphone7游戏(三)

    XNA Game Studio 游戏循环 在这部分中您将重点两剩余部分的游戏 - - 重写Update 和 Draw 功能.有些大大可能看过相关微软的训练包,我这里主要是帮一些初学者.希望各位大大包含 ...

  8. Windows Phone XNAでアニメーション - ぐるぐる

    Windows Phone XNAでアニメーション - ぐるぐる この投稿では.Windows PhoneでGameなどの高機能なグラフィックスを必要とするアプリケーション開発に最適な.XNA Fra ...

  9. 《XNA游戏开发》简介

    一.XNA简介 XNA是基于DirectX的游戏开发环境. 以C# 为开发语言 以 .NET Framework 为基础.并加入游戏应用所需之函式库所构成的 XNA Framework 可开发XNA ...

最新文章

  1. python3.8安装教程-二、Python2.7的安装并与Python3.8共存
  2. python装饰器作用-python装饰器有什么用
  3. linux sftp命令连接数,linux记录sftp命令
  4. Servlet中的HttpServlet
  5. 程序集强命名与GAC
  6. 1622C. Set or Decrease
  7. httpd-2.2.21 + php-5.3.8 自动安装脚本
  8. java 打包运行环境_Jar 打包 EXE文件,可以脱离java环境运行 Jsmooth的使用
  9. EXTJS4:如何改变grid某一个单元格的背景颜色
  10. 智能对话机器人之多轮对话工作机制 | Chatopera
  11. linux网卡驱动如何安装,linux下网卡驱动安装全过程
  12. 高数 | 【不定积分】基础知识点梳理 及 经典例题、李林880求不定积分例题
  13. 启用php client,RabbitMQ(二):安装 和 PHP Client
  14. 【Java基础】从Java语言层面理解BIO,NIO,AIO(二)
  15. 健康程序员:五分钟与鼠标手说再见
  16. 基于学术研究下载NOAA探空数据资料的详细步骤
  17. 加拿大存储厂商将在二战掩体中建设云数据中心
  18. SparkCore案例练习:统计广告ID
  19. 【Android】GPS定位基本原理浅析
  20. npm与包之包管理配置文件

热门文章

  1. 如何画西装外套?西装怎么画?
  2. Cloud Driver 将云盘变为本地磁盘
  3. BFS团战可以输、提莫必须死(转载)
  4. A006 - 基础 - VRF/VPN-instance
  5. deepin 任务栏 不见 或者闪烁
  6. SpriteKit塔防游戏动态改变防御塔价格标签的颜色
  7. windows下 conda创建虚拟环境
  8. 不好意思,科研生涯也许从此结束了,准备考公了
  9. 主动扫描-Nmap-端口、系统、服务扫描
  10. 把insert和update写成一个复合语句