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

xna3.1与4.0的区别不小,但也不是很大,在转换一些项目时候下面的tip能给些帮助。原文地址是:http://blogs.msdn.com/b/shawnhar/archive/2011/01/04/xna-3-1-to-4-0-cheat-sheet.aspx?utm_source=twitterfeed&utm_medium=twitter

遇到如下问题,该备忘录将解决的问题:

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

PS:其他问题,如xna模型画出边界,看起来透明或者丢失顶点以及看起来不对劲。

----------------------------------------------------------------------------------------

XNA 3.1 转为 XNA4.0 的例子:

SpriteBlendMode, SaveStateMode

view sourceprint?
1 // XNA 3.1
2 sprite.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Deferred, SaveStateMode.SaveState);
3 // XNA 4.0
4 sprite.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
5
6 // XNA 3.1
7 // 通过深度排列场景对象

view sourceprint?
1 spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.BackToFront, SaveStateMode.None);
2 // XNA 4.0
3 // 通过深度排列场景对象

view sourceprint?
1 spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
2
3 // XNA 3.1
4 sprite.Begin(SpriteBlendMode.None, SpriteSortMode.Immediate, SaveStateMode.SaveState);
5 // XNA 4.0
6 sprite.Begin(SpriteSortMode.Immediate, BlendState.Opaque);
7
8 // XNA 3.1
9 // 画背景图

view sourceprint?
1 spriteBatch.Begin(SpriteBlendMode.None);
2 Viewport viewport = GraphicsDevice.Viewport;
3 spriteBatch.Draw(background, new Rectangle(0, 0, viewport.Width, viewport.Height), Color.White);
4 spriteBatch.End();
5 // XNA 4.0
6 // 画背景图

view sourceprint?
1 spriteBatch.Begin(0, BlendState.Opaque);
2 spriteBatch.Draw(background, GraphicsDevice.Viewport.Bounds, Color.White);
3 spriteBatch.End();

RenderState

view sourceprint?
1 // XNA 3.1
2 // 启用alpha混合和深度写

view sourceprint?
01 GraphicsDevice.RenderState.AlphaBlendEnable = true;
02 GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha;
03 GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;
04 GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = true;
05 GraphicsDevice.RenderState.AlphaBlendOperation = BlendFunction.Add;
06 GraphicsDevice.RenderState.AlphaSourceBlend = Blend.One;
07 GraphicsDevice.RenderState.AlphaDestinationBlend = Blend.One;
08 GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
09 // XNA 4.0
10 // 启用alpha混合和深度写

view sourceprint?
1 GraphicsDevice.BlendState = BlendState.AlphaBlend;
2 GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead;
3
4 // XNA 3.1
5 // 重置混合和深度写

view sourceprint?
1 GraphicsDevice.RenderState.AlphaBlendEnable = false;
2 GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = false;
3 GraphicsDevice.RenderState.DepthBufferWriteEnable = true;
4 // XNA 4.0
5 // 重置混合和深度写

view sourceprint?
1 GraphicsDevice.BlendState = BlendState.Additive;
2 GraphicsDevice.DepthStencilState = DepthStencilState.Default;
3
4 // XNA 3.1
5 // 启用深度缓冲

view sourceprint?
1 GraphicsDevice.RenderState.DepthBufferEnable = true;
2 // XNA 4.0
3 // 启用深度缓冲

view sourceprint?
1 GraphicsDevice.DepthStencilState = DepthStencilState.Default;
2
3 // XNA 3.1
4 // 禁用深度缓冲

view sourceprint?
1 GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
2 GraphicsDevice.RenderState.DepthBufferEnable = false;
3 // XNA 4.0
4 // 禁用深度缓冲

view sourceprint?
01 GraphicsDevice.DepthStencilState = DepthStencilState.None;
02
03 // XNA 3.1
04 // 累加混合(zero on alpha)
05 GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
06 GraphicsDevice.RenderState.AlphaBlendEnable = true;
07 GraphicsDevice.RenderState.SourceBlend = Blend.One;
08 GraphicsDevice.RenderState.DestinationBlend = Blend.One;
09 // XNA 4.0
10 // 累加混合(zero on alpha)
11 GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead;
12 GraphicsDevice.BlendState = BlendState.AlphaBlend;
13
14 // XNA 3.1
15 // 恢复混合模式

view sourceprint?
1 GraphicsDevice.RenderState.DepthBufferWriteEnable = true;
2 GraphicsDevice.RenderState.AlphaBlendEnable = false;
3 GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = false;
4 // XNA 4.0
5 // 恢复混合模式

view sourceprint?
1 GraphicsDevice.BlendState = BlendState.Opaque;
2 GraphicsDevice.DepthStencilState = DepthStencilState.Default;
3
4 // XNA 3.1
5 // 设置alpha混合,无深度测试和深度写

view sourceprint?
1 GraphicsDevice.RenderState.DepthBufferEnable = false;
2 GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
3 GraphicsDevice.RenderState.AlphaBlendEnable = true;
4 GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha;
5 GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;
6 // XNA 4.0
7 // 设置alpha混合,无深度测试和深度写

view sourceprint?
1 GraphicsDevice.DepthStencilState = DepthStencilState.None;
2 GraphicsDevice.BlendState = BlendState.AlphaBlend;
3
4 // XNA 3.1
5 // 绘制3D模型时设置合适渲染模式

view sourceprint?
1 GraphicsDevice.RenderState.AlphaBlendEnable = false;
2 GraphicsDevice.RenderState.AlphaTestEnable = false;
3 GraphicsDevice.RenderState.DepthBufferEnable = true;
4 // XNA 4.0
5 // 绘制3D模型时设置合适渲染模式

view sourceprint?
1 GraphicsDevice.BlendState = BlendState.Opaque;
2 GraphicsDevice.DepthStencilState = DepthStencilState.Default;
3
4 // XNA 3.1
5 // 加性混合

view sourceprint?
1 GraphicsDevice.RenderState.AlphaBlendEnable = true;
2 GraphicsDevice.RenderState.SourceBlend = Blend.One;
3 GraphicsDevice.RenderState.DestinationBlend = Blend.One;
4 // XNA 4.0
5 // 加性混合

view sourceprint?
1 GraphicsDevice.BlendState = BlendState.Additive;
2
3 // XNA 3.1
4 // 设置加性混合

view sourceprint?
1 GraphicsDevice.RenderState.DestinationBlend = Blend.One;
2 // XNA 4.0
3 // 设置加性混合

view sourceprint?
1 GraphicsDevice.BlendState = BlendState.Additive;
2
3 // XNA 3.1
4 // 设置alpha混合

view sourceprint?
1 GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;
2 // XNA 4.0
3 // 设置alpha混合

view sourceprint?
1 GraphicsDevice.BlendState = BlendState.AlphaBlend;
2
3 // XNA 3.1
4 GraphicsDevice.RenderState.CullMode = CullMode.CullCounterClockwiseFace;
5 // XNA 4.0
6 GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
7
8 // XNA 3.1
9 // 设置渲染状态

view sourceprint?
01 GraphicsDevice.RenderState.DepthBufferEnable = false;
02 GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
03 GraphicsDevice.RenderState.AlphaBlendEnable = true;
04 GraphicsDevice.RenderState.SourceBlend = Blend.One;
05 GraphicsDevice.RenderState.DestinationBlend = Blend.One;
06 GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = true;
07 GraphicsDevice.RenderState.AlphaBlendOperation = BlendFunction.Add;
08 GraphicsDevice.RenderState.AlphaDestinationBlend = Blend.Zero;
09 GraphicsDevice.RenderState.AlphaSourceBlend = Blend.Zero;
10
11       // drawing code here..
12
13 // 恢复状态

view sourceprint?
1 GraphicsDevice.RenderState.DepthBufferEnable = true;
2 GraphicsDevice.RenderState.DepthBufferWriteEnable = true;
3 GraphicsDevice.RenderState.AlphaBlendEnable = false;
4 GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = false;
5 // XNA 4.0
6 //存储状态

view sourceprint?
1 DepthStencilState ds = GraphicsDevice.DepthStencilState;
2 BlendState bs = GraphicsDevice.BlendState;
3
4 //设置渲染状态

view sourceprint?
1 GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead;
2 GraphicsDevice.BlendState = BlendState.AlphaBlend;
3
4        // drawing code here..
5
6 // 恢复状态

view sourceprint?
1 GraphicsDevice.DepthStencilState = ds;
2 GraphicsDevice.BlendState = bs;

Effect, EffectPass, Begin(), End(), CommitChanges(), Clone()

view sourceprint?
01 // 应用效果 XNA 3.1
02 blurEffect.CommitChanges();
03 blurEffect.Begin(SaveStateMode.SaveState);
04 blurEffect.CurrentTechnique.Passes[0].Begin();
05 GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 2);
06 blurEffect.CurrentTechnique.Passes[0].End();
07 blurEffect.End();
08 // 应用效果 XNA 4.0
09 blurEffect.CurrentTechnique.Passes[0].Apply();
10 GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 2);
11
12 // XNA 3.1
13 // 提交效果改变

view sourceprint?
1 effect.CommitChanges();
2 // XNA 4.0
3 //  当任何效果属性改变需要调用EffectPass.Apply()

view sourceprint?
1 // 否则就删除它

view sourceprint?
1 // XNA 3.1
2 // 开始一个效果

view sourceprint?
1 effect.Begin(SaveStateMode.SaveState);
2 effect.CurrentTechnique.Passes[0].Begin();
3 // XNA 4.0
4 // 开始一个效果

view sourceprint?
1 effect.CurrentTechnique.Passes[0].Apply();
2
3 // XNA 3.1
4 // 结束一个效果

view sourceprint?
1 effect.CurrentTechnique.Passes[0].End();
2 effect.End();
3 // XNA 4.0
4 // 如果不需要可直接删除

view sourceprint?
1 // XNA 3.1
2 // 产生一个效果的克隆体

view sourceprint?
1 Effect newEffect = replacementEffect.Clone(replacementEffect.GraphicsDevice);
2 // XNA 4.0
3 // 产生一个效果的克隆体

view sourceprint?
1 Effect newEffect = replacementEffect.Clone();
2
3 // XNA 3.1
4 // 启用效果中的tech

view sourceprint?
01 postprocessEffect.CurrentTechnique = postprocessEffect.Techniques[effectTechniqueName];    
02
03 // 用预处理效果画一个全屏的精灵.
04 spriteBatch.Begin(SpriteBlendMode.None,SpriteSortMode.Immediate, SaveStateMode.None);
05
06 postprocessEffect.Begin();
07 postprocessEffect.CurrentTechnique.Passes[0].Begin();
08
09 spriteBatch.Draw(sceneRenderTarget.GetTexture(), Vector2.Zero, Color.White);
10 spriteBatch.End();
11
12 postprocessEffect.CurrentTechnique.Passes[0].End();
13 postprocessEffect.End();
14 // XNA 4.0
15 // 启用效果中的tech

view sourceprint?
1 postprocessEffect.CurrentTechnique = postprocessEffect.Techniques[effectTechniqueName];
2
3 // 用预处理效果画一个全屏的精灵.

view sourceprint?
1 spriteBatch.Begin(0, BlendState.Opaque, null, null, null, postprocessEffect);
2 spriteBatch.Draw(sceneRenderTarget, Vector2.Zero, Color.White);
3 spriteBatch.End();

ShaderProfile, TotalRealTime, TransparentBlack

view sourceprint?
1 // XNA 3.1
2 graphics.MinimumPixelShaderProfile = ShaderProfile.PS_3_0; //any PS number...
3 graphics.MinimumVertexShaderProfile = ShaderProfile.VS_3_0;//any VS number...
4 // XNA 4.0
5 // 不再需要该语句

view sourceprint?
1 // XNA 3.1
2 float myTime = (float)gameTime.TotalRealTime.TotalSeconds * 0.2f;
3 // XNA 4.0
4 float myTime = (float)gameTime.TotalGameTime.TotalSeconds * 0.2f;
5
6 // XNA 3.1
7 GraphicsDevice.Clear(Color.TransparentBlack);
8 // XNA 4.0
9 GraphicsDevice.Clear(Color.Transparent);

ResolveTexture2D, ResolveBackBuffer, RenderTarget2D, GetTexture, DepthStencilBuffer, PresentationParameters, MultiSampleType, MultiSampleQuality, SetRenderTarget

view sourceprint?
01 // XNA 3.1
02 ResolveTexture2D sceneMap;
03 // XNA 4.0
04 RenderTarget2D sceneMap;
05
06 // XNA 3.1
07 // 查询主缓冲的分辨率和格式.
08 PresentationParameters pp = GraphicsDevice.PresentationParameters;
09
10 // 从缓冲读取一个材质数据.
11 sceneMap = new ResolveTexture2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, 1, pp.BackBufferFormat);
12 // XNA 4.0
13 // 查询主缓冲的分辨率和格式.
14 PresentationParameters pp = GraphicsDevice.PresentationParameters;
15
16 // 从缓冲读取一个材质数据.
17 sceneMap = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false, pp.BackBufferFormat,
18                                 pp.DepthStencilFormat);
19 //or
20
21 sceneMap = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false, pp.BackBufferFormat,
22                                 pp.DepthStencilFormat, pp.MultiSampleCount, RenderTargetUsage.DiscardContents);
23
24 // XNA 3.1
25 GraphicsDevice.ResolveBackBuffer(sceneMap);
26 // XNA 4.0
27 GraphicsDevice.SetRenderTarget(sceneMap);
28
29 // XNA 3.1
30 int width = GraphicsDevice.Viewport.Width;
31 int height = GraphicsDevice.Viewport.Height;
32
33 // 创建渲染对象

view sourceprint?
1 myRenderTarget = new RenderTarget2D(GraphicsDevice, width, height, 1, SurfaceFormat.Color);
2 // XNA 4.0
3 int width = GraphicsDevice.Viewport.Width;
4 int height = GraphicsDevice.Viewport.Height;
5
6 // 创建渲染对象

view sourceprint?
1 myRenderTarget = new RenderTarget2D(GraphicsDevice, width, height, true, SurfaceFormat.Color, DepthFormat.Depth24);
2
3 // XNA 3.1
4 PresentationParameters pp = GraphicsDevice.PresentationParameters;
5
6 // 创建自动以渲染对象

view sourceprint?
1 sceneRenderTarget = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, 1,
2                                    pp.BackBufferFormat, pp.MultiSampleType, pp.MultiSampleQuality);
3 // XNA 4.0
4 PresentationParameters pp = GraphicsDevice.PresentationParameters;
5
6 // 创建自动以渲染对象

view sourceprint?
1 sceneRenderTarget = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false,
2                                    pp.BackBufferFormat, pp.DepthStencilFormat, pp.MultiSampleCount,
3                                    RenderTargetUsage.DiscardContents);
4
5 // XNA 3.1
6 PresentationParameters pp = GraphicsDevice.PresentationParameters;
7
8 // 配置一个深度缓冲

view sourceprint?
1 drawBuffer = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, 1,
2                                 SurfaceFormat.Color, pp.MultiSampleType, pp.MultiSampleQuality);
3
4 drawDepthBuffer = new DepthStencilBuffer(GraphicsDevice, pp.AutoDepthStencilFormat,
5                                             pp.MultiSampleType, pp.MultiSampleQuality);
6 // XNA 4.0
7 PresentationParameters pp = GraphicsDevice.PresentationParameters;
8
9 // 配置一个深度缓冲

view sourceprint?
1 drawBuffer = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, true,
2                                 SurfaceFormat.Color,DepthFormat.Depth24Stencil8,
3                                 pp.MultiSampleCount, RenderTargetUsage.DiscardContents);
4 //NOTE:  DepthStencilBuffer 类不再存在

view sourceprint?
1 // XNA 3.1
2 spriteBatch.Draw(myRenderTarget.GetTexture(), Vector2.Zero, Color.White);
3 // XNA 4.0
4 spriteBatch.Draw(myRenderTarget, Vector2.Zero, Color.White); // NOTE: ".GetTexure()"  不再需要

view sourceprint?
01 // XNA 3.1
02 Texture2D myTexture = myRenderTarget.GetTexture();
03 // XNA 4.0
04 Texture2D myTexture = myRenderTarget; // NOTE: ".GetTexure()"  No longer needed
05
06 // XNA 3.1
07 GraphicsDevice.SetRenderTarget(0, myRenderTarget);
08 // XNA 4.0
09 GraphicsDevice.SetRenderTarget(myRenderTarget);
10
11 // XNA 3.1
12 // 设置两个渲染目标

view sourceprint?
1 GraphicsDevice.SetRenderTarget(0, colorRT);
2 GraphicsDevice.SetRenderTarget(1, depthRT);
3 // XNA 4.0
4 // 设置两个渲染目标

view sourceprint?
1 GraphicsDevice.SetRenderTargets(colorRT, depthRT);
2
3 // XNA 3.1
4 GraphicsDevice.SetRenderTarget(0, null);
5 // XNA 4.0
6 GraphicsDevice.SetRenderTarget(null);
7
8 // XNA 3.1
9 // 将深度缓冲解析为深度图

view sourceprint?
1 GraphicsDevice.ResolveBackBuffer(depthMap);
2
3 // 绘制场景图, 用深度图模糊它

view sourceprint?
1 GraphicsDevice.Textures[1] = depthMap;
2 Viewport viewport = GraphicsDevice.Viewport;
3 dofEffect.CurrentTechnique = depthBlurTechnique;
4 DrawFullscreenQuad(sceneMap, viewport.Width, viewport.Height, dofEffect);
5 // XNA 4.0
6 // 将深度缓冲解析为深度图

view sourceprint?
1 GraphicsDevice.SetRenderTarget(null);
2
3 // 绘制场景图, 用深度图模糊它

view sourceprint?
01 GraphicsDevice.Textures[1] = depthMap;
02 GraphicsDevice.SamplerStates[1] = SamplerState.PointClamp;
03 Viewport viewport = GraphicsDevice.Viewport;
04 dofEffect.CurrentTechnique = depthBlurTechnique;
05 DrawFullscreenQuad(sceneMap, viewport.Width, viewport.Height, dofEffect);
06
07 // XNA 3.1
08 ResolveTexture2D resolveTarget;
09 RenderTarget2D renderTarget1;
10 RenderTarget2D renderTarget2;
11
12 // 查找主缓冲的分辨率和格式.
13 PresentationParameters pp = GraphicsDevice.PresentationParameters;
14
15 int width = pp.BackBufferWidth;
16 int height = pp.BackBufferHeight;
17 SurfaceFormat format = pp.BackBufferFormat;
18
19 // 创建一个材质读取缓冲中的内容.
20 resolveTarget = new ResolveTexture2D(GraphicsDevice, width, height, 1, format);
21
22 // Create two rendertargets half size for the bloom processing.
23 width /= 2;
24 height /= 2;
25
26 renderTarget1 = new RenderTarget2D(GraphicsDevice, width, height, 1,format);
27 renderTarget2 = new RenderTarget2D(GraphicsDevice, width, height, 1,format);
28
29 // ... In the Draw Method...
30 GraphicsDevice.ResolveBackBuffer(resolveTarget);
31 // ...apply effect and draw pass 1...
32 // XNA 4.0
33 RenderTarget2D sceneRenderTarget;
34 RenderTarget2D renderTarget1;
35 RenderTarget2D renderTarget2;
36
37 // 查找主缓冲的分辨率和格式. .
38 PresentationParameters pp = GraphicsDevice.PresentationParameters;
39
40 int width = pp.BackBufferWidth;
41 int height = pp.BackBufferHeight;
42 SurfaceFormat format = pp.BackBufferFormat;
43
44 // Create a texture for rendering the main scene, prior to applying bloom.
45 sceneRenderTarget = new RenderTarget2D(GraphicsDevice, width, height, false,
46                                        format, pp.DepthStencilFormat, pp.MultiSampleCount,
47                                        RenderTargetUsage.DiscardContents);
48
49 // Create two rendertargets half size for the bloom processing.
50 width /= 2;
51 height /= 2;
52
53 renderTarget1 = new RenderTarget2D(GraphicsDevice, width, height, false, format, DepthFormat.None);
54 renderTarget2 = new RenderTarget2D(GraphicsDevice, width, height, false, format, DepthFormat.None);
55
56 // ...In the Draw Method...
57 GraphicsDevice.SetRenderTarget(sceneRenderTarget);
58 GraphicsDevice.SamplerStates[1] = SamplerState.LinearClamp;
59 // ...apply effect and draw pass 1....

VertexDeclaration, Vertices, VertexElements, SizeInBytes

view sourceprint?
01 // XNA 3.1
02 // Vertex declaration for rendering our 3D model.
03 GraphicsDevice.VertexDeclaration = new VertexDeclaration(VertexPositionTexture.VertexElements);
04 // XNA 4.0
05 // Delete it. No longer needed.
06
07 // XNA 3.1
08 // set vertex buffer and declaration
09 GraphicsDevice.VertexDeclaration = vertexDeclaration;
10 GraphicsDevice.Vertices[0].SetSource(vertexBuffer, 0, VertexPositionTexture.SizeInBytes);
11 // XNA 4.0
12 // set vertex buffer and declaration
13 GraphicsDevice.SetVertexBuffer(vertexBuffer);
14
15 // XNA 3.1
16 // create vertex declaration
17 vertexDeclaration = new VertexDeclaration(GraphicsDevice, VertexPositionTexture.VertexElements);
18 // XNA 4.0
19 // create vertex declaration
20 vertexDeclaration = new VertexDeclaration(VertexPositionTexture.VertexDeclaration.GetVertexElements());
21
22 // XNA 3.1
23 // reset vertex buffer declaration
24 GraphicsDevice.VertexDeclaration = null;
25 GraphicsDevice.Vertices[0].SetSource(null, 0, 0);
26 // XNA 4.0
27 // reset vertex buffer declaration
28 GraphicsDevice.SetVertexBuffer(null);
29
30 // XNA 3.1
31 // the vertices array
32 VertexPositionNormalTexture[] vertices = new VertexPositionNormalTexture[100];
33
34 // set new particles to vertex buffer
35 vertexBuffer.SetData<VertexPositionNormalTexture>(VertexPositionNormalTexture.SizeInBytes * vertexCount,
36                     vertices,vertexCount,count,VertexPositionNormalTexture.SizeInBytes);
37 // XNA 4.0
38 // the vertices array
39 VertexPositionNormalTexture[] vertices = new VertexPositionNormalTexture[100];
40
41 // set new particles to vertex buffer
42 vertexBuffer.SetData<VertexPositionNormalTexture>(vertices);

view sourceprint?
1

view sourceprint?
1 VertexBuffer, StreamOffset, VertexStride, IndexBuffer, BaseVertex

view sourceprint?
01 // XNA 3.1
02 // for each mesh part
03 foreach (ModelMeshPart meshPart in mesh.MeshParts)
04 {
05     // if primitives to render
06     if (meshPart.PrimitiveCount > 0)
07     {
08         // setup vertices and indices
09         GraphicsDevice.VertexDeclaration = meshPart.VertexDeclaration;
10         GraphicsDevice.Vertices[0].SetSource(mesh.VertexBuffer, meshPart.StreamOffset, meshPart.VertexStride);
11         GraphicsDevice.Indices = mesh.IndexBuffer;
12         ...
13 // XNA 4.0
14 GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap; // may be needed in some cases...
15
16 // for each mesh part
17 foreach (ModelMeshPart meshPart in mesh.MeshParts)
18 {
19     // if primitives to render
20     if (meshPart.PrimitiveCount > 0)
21     {
22         // setup vertices and indices
23         GraphicsDevice.SetVertexBuffer(meshPart.VertexBuffer);
24         GraphicsDevice.Indices = meshPart.IndexBuffer;
25         ...
26
27 // XNA 3.1
28 // draw primitives
29 GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList,
30     meshPart.BaseVertex, 0, meshPart.NumVertices,
31     meshPart.StartIndex, meshPart.PrimitiveCount);
32 // XNA 4.0
33 // draw primitives
34 GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList,
35     meshPart.VertexOffset, 0, meshPart.NumVertices,
36     meshPart.StartIndex, meshPart.PrimitiveCount);

Points, PointSpriteEnable, PointSizeMax, PointList

view sourceprint?
01 // XNA 3.1
02 // create the vertex buffer
03 vertexBuffer = new VertexBuffer(GraphicsDevice, typeof(VertexPositionNormalTexture),
04                                 250, BufferUsage.WriteOnly | BufferUsage.Points);
05 // XNA 4.0
06 // create the vertex buffer
07 vertexBuffer = new VertexBuffer(GraphicsDevice, typeof(VertexPositionNormalTexture),
08                                 250, BufferUsage.WriteOnly | BufferUsage.None);
09
10 // XNA 3.1
11 // enable point sprite 3.1
12 GraphicsDevice.RenderState.PointSpriteEnable = true;
13 GraphicsDevice.RenderState.PointSizeMax = 128;
14 // XNA 4.0
15 // Delete it. No longer available.
16
17 // XNA 3.1
18 // draw the point sprites
19 GraphicsDevice.DrawPrimitives(PrimitiveType.PointList, vertexPosition, numberVertices);
20 // XNA 4.0
21 // draw the point sprites
22 GraphicsDevice.DrawPrimitives(PrimitiveType.LineList, vertexPosition, numberVertices);

OpenContainer, BeginShowStorageDeviceSelector, EndShowStorageDeviceSelector, Path, TitleLocation, FileStream

view sourceprint?
001 // XNA 3.1
002 // open the container
003 StorageContainer storageContainer = storageDevice.OpenContainer("YourGameName");
004 // XNA 4.0
005 //To make life easier simply create a method to replace the storageDevice.OpenContainer...
006
007 /// <summary>
008 /// Synchronously opens storage container
009 /// </summary>
010 private static StorageContainer OpenContainer(StorageDevice storageDevice, string saveGameName)
011 {
012     IAsyncResult result = storageDevice.BeginOpenContainer(saveGameName, null, null);
013
014     // Wait for the WaitHandle to become signaled.
015     result.AsyncWaitHandle.WaitOne();
016
017     StorageContainer container = storageDevice.EndOpenContainer(result);
018
019     // Close the wait handle.
020     result.AsyncWaitHandle.Close();
021
022     return container;
023 }
024
025 // open the container
026 StorageContainer storageContainer = OpenContainer(storageDevice, "YourGameName");
027
028 // XNA 3.1
029 // retrieve the storage device
030 Guide.BeginShowStorageDeviceSelector(GetStorageDeviceResult, retrievalDelegate);
031 // XNA 4.0
032 // retrieve the storage device
033 if (!Guide.IsVisible)
034 {
035     StorageDevice.BeginShowSelector(GetStorageDeviceResult, retrievalDelegate);
036 }
037
038 // XNA 3.1
039 // retrieve and store the storage device
040 storageDevice = Guide.EndShowStorageDeviceSelector(result);
041 // XNA 4.0
042 // retrieve and store the storage device
043 storageDevice = StorageDevice.EndShowSelector(result);
044
045 // XNA 3.1
046 // get the level setup files
047 string[] filenames = Directory.GetFiles(storageContainer.Path, "LevelSetup*.xml");
048 // XNA 4.0
049 // get the level setup files
050 string[] filenames = storageContainer.GetFileNames("LevelSetup*.xml"");
051
052 // XNA 3.1
053 // save game level data
054 using (FileStream stream = new FileStream(Path.Combine(storageContainer.Path, levelFilename), FileMode.Create))
055 {
056     new XmlSerializer(typeof(SaveGameLevel)).Serialize(stream, levelData);
057 }
058 // XNA 4.0
059 // save game level data
060 using (Stream stream = storageContainer.OpenFile(levelFilename, FileMode.Create))
061 {
062     new XmlSerializer(typeof(SaveGameLevel)).Serialize(stream, levelData);
063 }
064
065 // XNA 3.1
066 // Delete the saved game level data.
067 using (StorageContainer storageContainer = storageDevice.OpenContainer("saveGameName"))
068 {
069     File.Delete(Path.Combine(storageContainer.Path, saveGameLevel.FileName));
070
071     File.Delete(Path.Combine(storageContainer.Path, "SaveGameLevel" +
072         Path.GetFileNameWithoutExtension(saveGameLevel.FileName).Substring(8) +".xml"));
073 }
074 // XNA 4.0
075 // Delete the saved game level data. NOTE: using OpenContainer method created in previous example
076 using (StorageContainer storageContainer = OpenContainer(storageDevice, "saveGameName"))
077 {
078     storageContainer.DeleteFile(saveGameLevel.FileName);
079
080     storageContainer.DeleteFile("SaveGameLevel" +
081         Path.GetFileNameWithoutExtension(saveGameLevel.FileName).Substring(8) + ".xml");
082 }
083
084 // XNA 3.1
085 //Load the Next Level...
086
087 // Find the path of the next level.
088 string levelPath;
089
090 // Loop here so we can try again when we can't find a level.
091 while (true)
092 {
093     // Try to find the next level. They are sequentially numbered txt files.
094     levelPath = String.Format("Levels/{0}.txt", ++levelIndex);
095     levelPath = Path.Combine(StorageContainer.TitleLocation, "Content/" + levelPath);
096     if (File.Exists(levelPath))
097         break;
098
099     // If there isn't even a level 0, something has gone wrong.
100     if (levelIndex == 0)
101         throw new Exception("No levels found.");
102
103     // Whenever we can't find a level, start over again at 0.
104     levelIndex = -1;
105 }
106
107 // Unloads the content for the current level before loading the next one.
108 if (level != null)
109     level.Dispose();
110
111 // Load the level.
112 level = new Level(Services, levelPath);
113 // XNA 4.0
114 // Load the Next Level...
115
116 // move to the next level
117 levelIndex = (levelIndex + 1) % numberOfLevels;
118
119 // Unloads the content for the current level before loading the next one.
120 if (level != null)
121     level.Dispose();
122
123 // Load the level.
124 string levelPath = string.Format("Content/Levels/{0}.txt", levelIndex);
125 using (Stream fileStream = TitleContainer.OpenStream(levelPath))
126     level = new Level(Services, fileStream, levelIndex);
127
128
129 // XNA 3.1
130 //Save the current state of the session, with the given storage device.
131
132 // check the parameter
133 if ((storageDevice == null) || !storageDevice.IsConnected)
134 {
135     return;
136 }
137
138 // open the container
139 using (StorageContainer storageContainer = storageDevice.OpenContainer(Session.SaveGameContainerName))
140 {
141     string filename;
142     string descriptionFilename;
143
144     // get the filenames
145     if (overwriteDescription == null)
146     {
147         int saveGameIndex = 0;
148         string testFilename;
149         do
150         {
151             saveGameIndex++;
152             testFilename = Path.Combine(storageContainer.Path, "SaveGame" + saveGameIndex.ToString() + ".xml");
153         }
154         while (File.Exists(testFilename));
155         filename = testFilename;
156         descriptionFilename = "SaveGameDescription" + saveGameIndex.ToString() + ".xml";
157     }
158     else
159     {
160         filename = Path.Combine(storageContainer.Path, overwriteDescription.FileName);
161         descriptionFilename = "SaveGameDescription" +
162             Path.GetFileNameWithoutExtension(overwriteDescription.FileName).Substring(8) + ".xml";
163     }
164
165     using (FileStream stream = new FileStream(filename, FileMode.Create))
166     {
167         using (XmlWriter xmlWriter = XmlWriter.Create(stream))
168         {
169             //create and write xml data...
170         }
171     }
172
173    // create the save game description
174     SaveGameDescription description = new SaveGameDescription();
175     description.FileName = Path.GetFileName(filename);
176     description.ChapterName = IsQuestLineComplete ? "Quest Line Complete" : Quest.Name;
177     description.Description = DateTime.Now.ToString();
178
179     using (FileStream stream = new FileStream(Path.Combine(storageContainer.Path, descriptionFilename), FileMode.Create))
180     {
181         new XmlSerializer(typeof(SaveGameDescription)).Serialize(stream, description);
182     }
183 }
184 // XNA 4.0
185 //Save the current state of the session, with the given storage device.
186
187 // check the parameter
188 if ((storageDevice == null) || !storageDevice.IsConnected)
189 {
190     return;
191 }
192
193 // open the container Note: using OpenContainer method from previous examples
194 using (StorageContainer storageContainer = OpenContainer(storageDevice, Session.SaveGameContainerName))
195 {
196     string filename;
197     string descriptionFilename;
198     // get the filenames
199     if (overwriteDescription == null)
200     {
201         int saveGameIndex = 0;
202         string testFilename;
203         do
204         {
205             saveGameIndex++;
206             testFilename = "SaveGame" + saveGameIndex.ToString() + ".xml";
207         }
208         while (storageContainer.FileExists(testFilename));
209         filename = testFilename;
210         descriptionFilename = "SaveGameDescription" + saveGameIndex.ToString() + ".xml";
211     }
212     else
213     {
214         filename = overwriteDescription.FileName;
215         descriptionFilename = "SaveGameDescription" +
216             Path.GetFileNameWithoutExtension(overwriteDescription.FileName).Substring(8) + ".xml";
217     }
218
219     // Note: using Stream instead of FileStream...
220     using (Stream stream = storageContainer.OpenFile(filename, FileMode.Create))
221     {
222         using (XmlWriter xmlWriter = XmlWriter.Create(stream))
223         {
224             //create and write xml data...
225         }
226     }
227
228     // create the save game description
229     SaveGameDescription description = new SaveGameDescription();
230     description.FileName = Path.GetFileName(filename);
231     description.ChapterName = IsQuestLineComplete ? "Quest Line Complete" : Quest.Name;
232     description.Description = DateTime.Now.ToString();
233
234     // Note: using Stream instead of FileStream...
235     using (Stream stream = storageContainer.OpenFile(descriptionFilename, FileMode.Create))
236     {
237         new XmlSerializer(typeof(SaveGameDescription)).Serialize(stream, description);
238     }
239 }

view sourceprint?
1

view sourceprint?
1 VertexShader, PixelShader, ps_1_x

view sourceprint?
01 // XNA 3.1
02 VertexShaderOutput VertexShader(...)
03 {
04     //some code
05 }
06 float4 PixelShader(...)
07 {
08    // some code
09 }
10 // XNA 4.0
11 // VertexShader can not be used
12 VertexShaderOutput  VertexShaderFunction(...)
13 {
14    // some code
15 }
16 // PixelShader can not be used
17 float4 PixelShaderFunction(...)
18 {
19    // some code
20 }
21
22 // XNA 3.1
23 technique
24 {
25     pass
26     {
27         VertexShader = compile vs_1_1 VertexShader();
28         PixelShader  = compile ps_1_1 PixelShader();
29     }
30 }
31 // XNA 4.0
32 technique
33 {
34     pass
35     {
36         VertexShader = compile vs_2_0 VertexShaderFunction(); //VertexShader can not be used & set vs higher than 1_1
37         PixelShader  = compile ps_2_0 PixelShaderFunction(); //PixelShader can not be used & set ps higher than 1_1
38     }
39 }

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

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

[转]XNA 3.1 转换到 XNA4.0 的备忘录相关推荐

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

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

  2. QQ超市模拟排配2D版 1.08 (XNA4.0)

    XNA4.0开发的.学XNA后的练手作品. 功能: 1.模拟配置货架    添加.删除.移动.旋转功能齐全    可设置双面宝石和4面宝石.    自动寻路 2.地图齐全.可保存. 3.实时自动计算当 ...

  3. QQ超市模拟排配3D版 1.1 (XNA4.0)

    XNA4.0学习过程中,练手方便,就把2D的改为3D的了.功能基本没变化. 加了一些学习过程中学到的东西而已.山水.草地~ 超市货架地板等都是自己用3ds max2011建模,材质球改了下颜色,随便加 ...

  4. 如何转换高度:0; 达到高度:自动; 使用CSS?

    我正在尝试使用CSS过渡使<ul>滑落. <ul>从height: 0; . 悬停时,将高度设置为height:auto; . 但是,这导致它只是显示而不是过渡, 如果我从he ...

  5. [代码发布]中文文字转换组件 1.0,支持VB/ASP编程

    中文文字转换组件 1.0 *************************************************************** 版本历史: ***************** ...

  6. qt QString数值转换格式化不足补0 QString十进制转换不足补0

    int num = 1; QString("%1").arg(num,2, 10, QChar('0')); 这样输出的就是01. 其中2代表要输出几位,10代表10进制转换,QC ...

  7. 智能实验室-专用链转换 1.5.0.150

    专用链转换(SpecialLinkio)是用以双向转换专用链的工具. 特点: 1.支持格式:支持市面上的各种格式,包括网际快车(FlashGet).迅雷(Thunder).QQ旋风..FS2You等: ...

  8. QQ超市模拟排配2D版1.13 (XNA4.0) (修正双格货架移动的一个bug和3-5地图)

    抱歉,更新了一个地图-- 下载地址:(版本过期了,请下新版) 1.13:更新日期:2012-3-22 更新3店5口地图错误问题.启动程序前请手动删除旧版地图数据. 地址:C:\(我的文档路径)\Sav ...

  9. 【XNA4.0】动画

    2D XNA游戏中的动画的制作过程很像卡通手翻书.动画制作包含着大量的独立图像,通过在一个周期内图像间的快速切换来使它们显示为动画.通常精灵动画存放在图片文件中,您需要用某种顺序把图片上独立的图像提取 ...

最新文章

  1. Gradle入门系列(4):创建二进制发布版本
  2. 河北工业机器人夹爪生产厂家_电动夹爪会成为“标配”吗?
  3. 【转】更简单的非递归遍历二叉树的方法
  4. rs232串口驱动_电脑主板RS232串口硬件设计
  5. css字体样式代码大全_这都2020年了,还没了解CSS?
  6. api postmain 鉴权_认证鉴权与API权限控制在微服务架构中的设计与实现(一)
  7. 会mysql不会sql_不是吧,不会有人还不知道MySQL中具实用的SQL语句
  8. 只需一行代码,就能导入所有的Python库?
  9. Oralce weblogic 11g 安装部署使用手册
  10. MVC3.0 如何点击点击一张图片连接到另一地址
  11. [Python] 字典 get(key, default=None):获取字典中相应键的对应值
  12. MATLAB2016b安装教程
  13. SpringBoot中Session超时原理说明
  14. flash player 10 beta已经放出
  15. Excel2013每次打开都弹出配置进度窗口的分步解决办法
  16. Proximal Policy Optimization(PPO)算法原理及实现!
  17. 如何不开会员,把易企秀图片下载保存本地
  18. Java RestTemplate中几种常见的请求方式
  19. Win11新电脑开机跳过联网解决方法
  20. python 复制某文件到另一个文件夹

热门文章

  1. OpenCV方形检测Square Detection的实例(附完整代码)
  2. OpenGL 位图字体渲染的实例
  3. C++ Opengl 线,网格游戏源码
  4. 怎么用matlab处理数据,如何用Matlab处理.wfm格式的数据
  5. 远程拷贝、查看端口、vim常见快捷键、查找替换命令、grep命令、查看存储空间的命令、chkconfig命令、系统自动启动级别、主机名配置、IP地址配置、域名映射、防火墙设置
  6. 3.关于QT中的MainWindow窗口,MenuBar,ToolBar,QuickTip等方面的知识点
  7. SQLite 数据类型(http://www.w3cschool.cc/sqlite/sqlite-data-types.html)
  8. SQLite 命令(http://www.w3cschool.cc/sqlite/sqlite-commands.html)
  9. 一个系统的base.css,兼容IE7,IE8,IE9,IE10,IE11,firefox,safari,谷歌,360,世界之窗等浏览器起的公共css
  10. 一个ApplicationContext.xml的配置