DotNet编程-星光伴我行

滴滴真谛 水滴石穿

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
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

1// XNA 3.1
2sprite.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Deferred, SaveStateMode.SaveState);
3// XNA 4.0
4sprite.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
5
6// XNA 3.1
7// 通过深度排列场景对象
1spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.BackToFront, SaveStateMode.None);
2// XNA 4.0
3// 通过深度排列场景对象
1spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
2
3// XNA 3.1
4sprite.Begin(SpriteBlendMode.None, SpriteSortMode.Immediate, SaveStateMode.SaveState);
5// XNA 4.0
6sprite.Begin(SpriteSortMode.Immediate, BlendState.Opaque);
7
8// XNA 3.1
9// 画背景图
1spriteBatch.Begin(SpriteBlendMode.None);
2Viewport viewport = GraphicsDevice.Viewport;
3spriteBatch.Draw(background, new Rectangle(0, 0, viewport.Width, viewport.Height), Color.White);
4spriteBatch.End();
5// XNA 4.0
6// 画背景图
1spriteBatch.Begin(0, BlendState.Opaque);
2spriteBatch.Draw(background, GraphicsDevice.Viewport.Bounds, Color.White);
3spriteBatch.End();

RenderState

1// XNA 3.1
2// 启用alpha混合和深度写
01GraphicsDevice.RenderState.AlphaBlendEnable = true;
02GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha;
03GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;
04GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = true;
05GraphicsDevice.RenderState.AlphaBlendOperation = BlendFunction.Add;
06GraphicsDevice.RenderState.AlphaSourceBlend = Blend.One;
07GraphicsDevice.RenderState.AlphaDestinationBlend = Blend.One;
08GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
09// XNA 4.0
10// 启用alpha混合和深度写
1GraphicsDevice.BlendState = BlendState.AlphaBlend;
2GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead;
3
4// XNA 3.1
5// 重置混合和深度写
1GraphicsDevice.RenderState.AlphaBlendEnable = false;
2GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = false;
3GraphicsDevice.RenderState.DepthBufferWriteEnable = true;
4// XNA 4.0
5// 重置混合和深度写
1GraphicsDevice.BlendState = BlendState.Additive;
2GraphicsDevice.DepthStencilState = DepthStencilState.Default;
3
4// XNA 3.1
5// 启用深度缓冲
1GraphicsDevice.RenderState.DepthBufferEnable = true;
2// XNA 4.0
3// 启用深度缓冲
1GraphicsDevice.DepthStencilState = DepthStencilState.Default;
2
3// XNA 3.1
4// 禁用深度缓冲
1GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
2GraphicsDevice.RenderState.DepthBufferEnable = false;
3// XNA 4.0
4// 禁用深度缓冲
01GraphicsDevice.DepthStencilState = DepthStencilState.None;
02
03// XNA 3.1
04// 累加混合(zero on alpha)
05GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
06GraphicsDevice.RenderState.AlphaBlendEnable = true;
07GraphicsDevice.RenderState.SourceBlend = Blend.One;
08GraphicsDevice.RenderState.DestinationBlend = Blend.One;
09// XNA 4.0
10// 累加混合(zero on alpha)
11GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead;
12GraphicsDevice.BlendState = BlendState.AlphaBlend;
13
14// XNA 3.1
15// 恢复混合模式
1GraphicsDevice.RenderState.DepthBufferWriteEnable = true;
2GraphicsDevice.RenderState.AlphaBlendEnable = false;
3GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = false;
4// XNA 4.0
5// 恢复混合模式
1GraphicsDevice.BlendState = BlendState.Opaque;
2GraphicsDevice.DepthStencilState = DepthStencilState.Default;
3
4// XNA 3.1
5// 设置alpha混合,无深度测试和深度写
1GraphicsDevice.RenderState.DepthBufferEnable = false;
2GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
3GraphicsDevice.RenderState.AlphaBlendEnable = true;
4GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha;
5GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;
6// XNA 4.0
7// 设置alpha混合,无深度测试和深度写
1GraphicsDevice.DepthStencilState = DepthStencilState.None;
2GraphicsDevice.BlendState = BlendState.AlphaBlend;
3
4// XNA 3.1
5// 绘制3D模型时设置合适渲染模式
1GraphicsDevice.RenderState.AlphaBlendEnable = false;
2GraphicsDevice.RenderState.AlphaTestEnable = false;
3GraphicsDevice.RenderState.DepthBufferEnable = true;
4// XNA 4.0
5// 绘制3D模型时设置合适渲染模式
1GraphicsDevice.BlendState = BlendState.Opaque;
2GraphicsDevice.DepthStencilState = DepthStencilState.Default;
3
4// XNA 3.1
5// 加性混合
1GraphicsDevice.RenderState.AlphaBlendEnable = true;
2GraphicsDevice.RenderState.SourceBlend = Blend.One;
3GraphicsDevice.RenderState.DestinationBlend = Blend.One;
4// XNA 4.0
5// 加性混合
1GraphicsDevice.BlendState = BlendState.Additive;
2
3// XNA 3.1
4// 设置加性混合
1GraphicsDevice.RenderState.DestinationBlend = Blend.One;
2// XNA 4.0
3// 设置加性混合
1GraphicsDevice.BlendState = BlendState.Additive;
2
3// XNA 3.1
4// 设置alpha混合
1GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;
2// XNA 4.0
3// 设置alpha混合
1GraphicsDevice.BlendState = BlendState.AlphaBlend;
2
3// XNA 3.1
4GraphicsDevice.RenderState.CullMode = CullMode.CullCounterClockwiseFace;
5// XNA 4.0
6 GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
7
8// XNA 3.1
9// 设置渲染状态
01GraphicsDevice.RenderState.DepthBufferEnable = false;
02GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
03GraphicsDevice.RenderState.AlphaBlendEnable = true;
04GraphicsDevice.RenderState.SourceBlend = Blend.One;
05GraphicsDevice.RenderState.DestinationBlend = Blend.One;
06GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = true;
07GraphicsDevice.RenderState.AlphaBlendOperation = BlendFunction.Add;
08GraphicsDevice.RenderState.AlphaDestinationBlend = Blend.Zero;
09GraphicsDevice.RenderState.AlphaSourceBlend = Blend.Zero;
10
11      // drawing code here..
12
13// 恢复状态
1GraphicsDevice.RenderState.DepthBufferEnable = true;
2GraphicsDevice.RenderState.DepthBufferWriteEnable = true;
3GraphicsDevice.RenderState.AlphaBlendEnable = false;
4GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = false;
5// XNA 4.0
6//存储状态
1DepthStencilState ds = GraphicsDevice.DepthStencilState;
2BlendState bs = GraphicsDevice.BlendState;
3
4//设置渲染状态
1GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead;
2GraphicsDevice.BlendState = BlendState.AlphaBlend;
3
4       // drawing code here..
5
6// 恢复状态
1GraphicsDevice.DepthStencilState = ds;
2GraphicsDevice.BlendState = bs;

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

01// 应用效果 XNA 3.1
02blurEffect.CommitChanges();
03blurEffect.Begin(SaveStateMode.SaveState);
04blurEffect.CurrentTechnique.Passes[0].Begin();
05GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 2);
06blurEffect.CurrentTechnique.Passes[0].End();
07blurEffect.End();
08// 应用效果 XNA 4.0
09blurEffect.CurrentTechnique.Passes[0].Apply();
10GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 2);
11
12// XNA 3.1
13// 提交效果改变
1effect.CommitChanges();
2// XNA 4.0
3//  当任何效果属性改变需要调用EffectPass.Apply()
1// 否则就删除它
1// XNA 3.1
2// 开始一个效果
1effect.Begin(SaveStateMode.SaveState);
2effect.CurrentTechnique.Passes[0].Begin();
3// XNA 4.0
4// 开始一个效果
1effect.CurrentTechnique.Passes[0].Apply();
2
3// XNA 3.1
4// 结束一个效果
1effect.CurrentTechnique.Passes[0].End();
2effect.End();
3// XNA 4.0
4// 如果不需要可直接删除
1// XNA 3.1
2// 产生一个效果的克隆体
1Effect newEffect = replacementEffect.Clone(replacementEffect.GraphicsDevice);
2// XNA 4.0
3// 产生一个效果的克隆体
1Effect newEffect = replacementEffect.Clone();
2
3// XNA 3.1
4// 启用效果中的tech
01postprocessEffect.CurrentTechnique = postprocessEffect.Techniques[effectTechniqueName];    
02
03// 用预处理效果画一个全屏的精灵.
04spriteBatch.Begin(SpriteBlendMode.None,SpriteSortMode.Immediate, SaveStateMode.None);
05
06postprocessEffect.Begin();
07postprocessEffect.CurrentTechnique.Passes[0].Begin();
08
09spriteBatch.Draw(sceneRenderTarget.GetTexture(), Vector2.Zero, Color.White);
10spriteBatch.End();
11
12postprocessEffect.CurrentTechnique.Passes[0].End();
13postprocessEffect.End();
14// XNA 4.0
15// 启用效果中的tech
1postprocessEffect.CurrentTechnique = postprocessEffect.Techniques[effectTechniqueName];
2
3// 用预处理效果画一个全屏的精灵.
1spriteBatch.Begin(0, BlendState.Opaque, null, null, null, postprocessEffect);
2spriteBatch.Draw(sceneRenderTarget, Vector2.Zero, Color.White);
3spriteBatch.End();

ShaderProfile, TotalRealTime, TransparentBlack

1// XNA 3.1
2graphics.MinimumPixelShaderProfile = ShaderProfile.PS_3_0; //any PS number...
3graphics.MinimumVertexShaderProfile = ShaderProfile.VS_3_0;//any VS number...
4// XNA 4.0
5// 不再需要该语句
1// XNA 3.1
2float myTime = (float)gameTime.TotalRealTime.TotalSeconds * 0.2f;
3// XNA 4.0
4float myTime = (float)gameTime.TotalGameTime.TotalSeconds * 0.2f;
5
6// XNA 3.1
7GraphicsDevice.Clear(Color.TransparentBlack);
8// XNA 4.0
9GraphicsDevice.Clear(Color.Transparent);

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

01// XNA 3.1
02ResolveTexture2D sceneMap;
03// XNA 4.0
04RenderTarget2D sceneMap;
05
06// XNA 3.1
07// 查询主缓冲的分辨率和格式.
08PresentationParameters pp = GraphicsDevice.PresentationParameters;
09
10// 从缓冲读取一个材质数据.
11sceneMap = new ResolveTexture2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, 1, pp.BackBufferFormat);
12// XNA 4.0
13// 查询主缓冲的分辨率和格式.
14PresentationParameters pp = GraphicsDevice.PresentationParameters;
15
16// 从缓冲读取一个材质数据.
17sceneMap = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false, pp.BackBufferFormat,
18                                pp.DepthStencilFormat);
19//or
20
21sceneMap = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false, pp.BackBufferFormat,
22                                pp.DepthStencilFormat, pp.MultiSampleCount, RenderTargetUsage.DiscardContents);
23
24// XNA 3.1
25GraphicsDevice.ResolveBackBuffer(sceneMap);
26// XNA 4.0
27GraphicsDevice.SetRenderTarget(sceneMap);
28
29// XNA 3.1
30int width = GraphicsDevice.Viewport.Width;
31int height = GraphicsDevice.Viewport.Height;
32
33// 创建渲染对象
1myRenderTarget = new RenderTarget2D(GraphicsDevice, width, height, 1, SurfaceFormat.Color);
2// XNA 4.0
3int width = GraphicsDevice.Viewport.Width;
4int height = GraphicsDevice.Viewport.Height;
5
6// 创建渲染对象
1myRenderTarget = new RenderTarget2D(GraphicsDevice, width, height, true, SurfaceFormat.Color, DepthFormat.Depth24);
2
3// XNA 3.1
4PresentationParameters pp = GraphicsDevice.PresentationParameters;
5
6// 创建自动以渲染对象
1sceneRenderTarget = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, 1,
2                                   pp.BackBufferFormat, pp.MultiSampleType, pp.MultiSampleQuality);
3// XNA 4.0
4PresentationParameters pp = GraphicsDevice.PresentationParameters;
5
6// 创建自动以渲染对象
1sceneRenderTarget = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false,
2                                   pp.BackBufferFormat, pp.DepthStencilFormat, pp.MultiSampleCount,
3                                   RenderTargetUsage.DiscardContents);
4
5// XNA 3.1
6PresentationParameters pp = GraphicsDevice.PresentationParameters;
7
8// 配置一个深度缓冲
1drawBuffer = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, 1,
2                                SurfaceFormat.Color, pp.MultiSampleType, pp.MultiSampleQuality);
3
4drawDepthBuffer = new DepthStencilBuffer(GraphicsDevice, pp.AutoDepthStencilFormat,
5                                            pp.MultiSampleType, pp.MultiSampleQuality);
6// XNA 4.0
7PresentationParameters pp = GraphicsDevice.PresentationParameters;
8
9// 配置一个深度缓冲
1drawBuffer = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, true,
2                                SurfaceFormat.Color,DepthFormat.Depth24Stencil8,
3                                pp.MultiSampleCount, RenderTargetUsage.DiscardContents);
4//NOTE:  DepthStencilBuffer 类不再存在
1// XNA 3.1
2spriteBatch.Draw(myRenderTarget.GetTexture(), Vector2.Zero, Color.White);
3// XNA 4.0
4spriteBatch.Draw(myRenderTarget, Vector2.Zero, Color.White); // NOTE: ".GetTexure()"  不再需要
01// XNA 3.1
02Texture2D myTexture = myRenderTarget.GetTexture();
03// XNA 4.0
04Texture2D myTexture = myRenderTarget; // NOTE: ".GetTexure()"  No longer needed
05
06// XNA 3.1
07GraphicsDevice.SetRenderTarget(0, myRenderTarget);
08// XNA 4.0
09GraphicsDevice.SetRenderTarget(myRenderTarget);
10
11// XNA 3.1
12// 设置两个渲染目标
1GraphicsDevice.SetRenderTarget(0, colorRT);
2GraphicsDevice.SetRenderTarget(1, depthRT);
3// XNA 4.0
4// 设置两个渲染目标
1GraphicsDevice.SetRenderTargets(colorRT, depthRT);
2
3// XNA 3.1
4GraphicsDevice.SetRenderTarget(0, null);
5// XNA 4.0
6GraphicsDevice.SetRenderTarget(null);
7
8// XNA 3.1
9// 将深度缓冲解析为深度图
1GraphicsDevice.ResolveBackBuffer(depthMap);
2
3// 绘制场景图, 用深度图模糊它
1GraphicsDevice.Textures[1] = depthMap;
2Viewport viewport = GraphicsDevice.Viewport;
3dofEffect.CurrentTechnique = depthBlurTechnique;
4DrawFullscreenQuad(sceneMap, viewport.Width, viewport.Height, dofEffect);
5// XNA 4.0
6// 将深度缓冲解析为深度图
1GraphicsDevice.SetRenderTarget(null);
2
3// 绘制场景图, 用深度图模糊它
01GraphicsDevice.Textures[1] = depthMap;
02GraphicsDevice.SamplerStates[1] = SamplerState.PointClamp;
03Viewport viewport = GraphicsDevice.Viewport;
04dofEffect.CurrentTechnique = depthBlurTechnique;
05DrawFullscreenQuad(sceneMap, viewport.Width, viewport.Height, dofEffect);
06
07// XNA 3.1
08ResolveTexture2D resolveTarget;
09RenderTarget2D renderTarget1;
10RenderTarget2D renderTarget2;
11
12// 查找主缓冲的分辨率和格式.
13PresentationParameters pp = GraphicsDevice.PresentationParameters;
14
15int width = pp.BackBufferWidth;
16int height = pp.BackBufferHeight;
17SurfaceFormat format = pp.BackBufferFormat;
18
19// 创建一个材质读取缓冲中的内容.
20resolveTarget = new ResolveTexture2D(GraphicsDevice, width, height, 1, format);
21
22// Create two rendertargets half size for the bloom processing.
23width /= 2;
24height /= 2;
25
26renderTarget1 = new RenderTarget2D(GraphicsDevice, width, height, 1,format);
27renderTarget2 = 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
33RenderTarget2D sceneRenderTarget;
34RenderTarget2D renderTarget1;
35RenderTarget2D renderTarget2;
36
37// 查找主缓冲的分辨率和格式. .
38PresentationParameters pp = GraphicsDevice.PresentationParameters;
39
40int width = pp.BackBufferWidth;
41int height = pp.BackBufferHeight;
42SurfaceFormat format = pp.BackBufferFormat;
43
44// Create a texture for rendering the main scene, prior to applying bloom.
45sceneRenderTarget = 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.
50width /= 2;
51height /= 2;
52
53renderTarget1 = new RenderTarget2D(GraphicsDevice, width, height, false, format, DepthFormat.None);
54renderTarget2 = new RenderTarget2D(GraphicsDevice, width, height, false, format, DepthFormat.None);
55
56// ...In the Draw Method...
57GraphicsDevice.SetRenderTarget(sceneRenderTarget);
58GraphicsDevice.SamplerStates[1] = SamplerState.LinearClamp;
59// ...apply effect and draw pass 1....

VertexDeclaration, Vertices, VertexElements, SizeInBytes

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
09GraphicsDevice.VertexDeclaration = vertexDeclaration;
10GraphicsDevice.Vertices[0].SetSource(vertexBuffer, 0, VertexPositionTexture.SizeInBytes);
11// XNA 4.0
12// set vertex buffer and declaration
13GraphicsDevice.SetVertexBuffer(vertexBuffer);
14
15// XNA 3.1
16// create vertex declaration
17vertexDeclaration = new VertexDeclaration(GraphicsDevice, VertexPositionTexture.VertexElements);
18// XNA 4.0
19// create vertex declaration
20vertexDeclaration = new VertexDeclaration(VertexPositionTexture.VertexDeclaration.GetVertexElements());
21
22// XNA 3.1
23// reset vertex buffer declaration
24GraphicsDevice.VertexDeclaration = null;
25GraphicsDevice.Vertices[0].SetSource(null, 0, 0);
26// XNA 4.0
27// reset vertex buffer declaration
28GraphicsDevice.SetVertexBuffer(null);
29
30// XNA 3.1
31// the vertices array
32VertexPositionNormalTexture[] vertices = new VertexPositionNormalTexture[100];
33
34 // set new particles to vertex buffer
35vertexBuffer.SetData<VertexPositionNormalTexture>(VertexPositionNormalTexture.SizeInBytes * vertexCount,
36                    vertices,vertexCount,count,VertexPositionNormalTexture.SizeInBytes);
37// XNA 4.0
38// the vertices array
39VertexPositionNormalTexture[] vertices = new VertexPositionNormalTexture[100];
40
41// set new particles to vertex buffer
42vertexBuffer.SetData<VertexPositionNormalTexture>(vertices);
1VertexBuffer, StreamOffset, VertexStride, IndexBuffer, BaseVertex
01// XNA 3.1
02// for each mesh part
03foreach (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
14GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap; // may be needed in some cases...
15
16// for each mesh part
17foreach (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
29GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList,
30    meshPart.BaseVertex, 0, meshPart.NumVertices,
31    meshPart.StartIndex, meshPart.PrimitiveCount);
32// XNA 4.0
33// draw primitives
34GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList,
35    meshPart.VertexOffset, 0, meshPart.NumVertices,
36    meshPart.StartIndex, meshPart.PrimitiveCount);

Points, PointSpriteEnable, PointSizeMax, PointList

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

OpenContainer, BeginShowStorageDeviceSelector, EndShowStorageDeviceSelector, Path, TitleLocation, FileStream

001// XNA 3.1
002// open the container
003StorageContainer 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>
010private 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
026StorageContainer storageContainer = OpenContainer(storageDevice, "YourGameName");
027
028// XNA 3.1
029// retrieve the storage device
030Guide.BeginShowStorageDeviceSelector(GetStorageDeviceResult, retrievalDelegate);
031// XNA 4.0
032// retrieve the storage device
033if (!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
050string[] filenames = storageContainer.GetFileNames("LevelSetup*.xml"");
051
052// XNA 3.1
053// save game level data
054using (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
060using (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.
067using (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
076using (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.
088string levelPath;
089
090// Loop here so we can try again when we can't find a level.
091while (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.
108if (level != null)
109    level.Dispose();
110
111// Load the level.
112level = new Level(Services, levelPath);
113// XNA 4.0
114// Load the Next Level...
115
116// move to the next level
117levelIndex = (levelIndex + 1) % numberOfLevels;
118
119// Unloads the content for the current level before loading the next one.
120if (level != null)
121    level.Dispose();
122
123// Load the level.
124string levelPath = string.Format("Content/Levels/{0}.txt", levelIndex);
125using (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
133if ((storageDevice == null) || !storageDevice.IsConnected)
134{
135    return;
136}
137
138// open the container
139using (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
188if ((storageDevice == null) || !storageDevice.IsConnected)
189{
190    return;
191}
192
193// open the container Note: using OpenContainer method from previous examples
194using (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}
1VertexShader, PixelShader, ps_1_x
01// XNA 3.1
02VertexShaderOutput VertexShader(...)
03{
04    //some code
05}
06float4 PixelShader(...)
07{
08   // some code
09}
10// XNA 4.0
11// VertexShader can not be used
12VertexShaderOutput  VertexShaderFunction(...)
13{
14   // some code
15}
16// PixelShader can not be used
17float4 PixelShaderFunction(...)
18{
19   // some code
20}
21
22// XNA 3.1
23technique
24{
25    pass
26    {
27        VertexShader = compile vs_1_1 VertexShader();
28        PixelShader  = compile ps_1_1 PixelShader();
29    }
30}
31// XNA 4.0
32technique
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

1// Set suitable renderstates for drawing a 3D model
2GraphicsDevice.BlendState = BlendState.Opaque;
3GraphicsDevice.DepthStencilState = DepthStencilState.Default;
4
5// your model draw code starts here...
posted on 2011-10-18 10:38  DotNet编程  阅读(682)  评论(0编辑  收藏  举报