Возможно вы искали: 'Тимошка спасает друга'

May 12 2025 01:25:39
  • Как сделать 8Gamers.Ru домашней страницей?
  • Игры
    • База данных по играх
    • Игровые новости
    • Игровая индустрия
    • Обзоры на игры
    • Прохождения игр
    • Гайды к играм
    • Превью о играх
    • Игровые тизеры
    • Игровые арты
    • Игровые обои
    • Игровые скриншоты
    • Игровые обложки
    • Игровые трейлеры
    • Игровое видео
    • Вышедшие игры
    • Ближайшие релизы игр
  • Кино и ТВ
    • База данных по кино
    • Статьи о кино
    • Постеры
    • Кадры из кино
    • Кино трейлеры
    • Сегодня в кино
    • Скоро в кино
  • Комиксы и манга
    • Манга по алфавиту
    • База данных по комиксах
    • Читать онлайн комиксы
    • Читать онлайн манга
    • База персонажей
  • Читы и коды
    • Чит-коды для PC игр
    • Чит-коды для консольных игр
    • Трейнеры
    • Коды Game Genie
  • Моддинг
    • Модификации
    • Карты к играм
    • Программы для моддинга
    • Статьи о моддинге
  • Геймдев
    • Всё о создании игр
    • Список движков
    • Утилиты в помощь игроделу
    • Конструкторы игр
    • Игровые движки
    • Библиотеки разработки
    • 3D-модели
    • Спрайты и тайлы
    • Музыка и звуки
    • Текстуры и фоны
  • Рецензии
    • Игры
    • Кино
    • Аниме
    • Комиксы
    • Мангу
    • Саундтреки
  • Саундтреки
    • Лирика
  • Файлы
    • Патчи к играм
    • Русификаторы к играм
    • Сохранения к играм
    • Субтитры к кино
  • Медиа
    • Видео
    • Фото
    • Аудио
    • Фан-арты
    • Косплей
    • Фото с виставок
    • Девушки из игр
    • Рисунки
    • Рисуем онлайн
    • Фотохостинг
  • Юмор
    • Анекдоты
    • Афоризмы
    • Истории
    • Стишки и эпиграммы
    • Тосты
    • Цитаты
  • Флеш
    • Азартные
    • Аркады
    • Бродилки
    • Гонки
    • Для девочек
    • Для мальчиков
    • Драки
    • Квесты
    • Леталки
    • Логические
    • Мультфильмы
    • Открытки
    • Приколы
    • Разное
    • Спорт
    • Стратегии
    • Стрелялки
Статистика

Статей: 87772
Просмотров: 96030355
Игры
Injustice:  Gods Among Us
Injustice: Gods Among Us
...
Dark Souls 2
Dark Souls 2
Dark Souls II - вторая часть самой хардкорной ролевой игры 2011-2012 года, с новым героем, сюжето...
Battlefield 4
Battlefield 4
Battlefield 4 - продолжение венценосного мультиплеер-ориентированного шутера от первого ли...
Кино
Steins;Gate
Steins;Gate
Любители японской анимации уже давно поняли ,что аниме сериалы могут дать порой гораздо больше пи...
Ку! Кин-дза-дза
Ку! Кин-дза-дза
Начинающий диджей Толик и всемирно известный виолончелист Владимир Чижов встречают на шумной моск...
Обзоры на игры
• Обзор Ibara [PCB/PS2] 18346
• Обзор The Walking ... 18789
• Обзор DMC: Devil M... 19864
• Обзор на игру Valk... 15867
• Обзор на игру Stars! 17754
• Обзор на Far Cry 3 17935
• Обзор на Resident ... 16012
• Обзор на Chivalry:... 17495
• Обзор на игру Kerb... 17970
• Обзор игры 007: Fr... 16604
Превью о играх
• Превью к игре Comp... 17946
• Превью о игре Mage... 14451
• Превью Incredible ... 14706
• Превью Firefall 13462
• Превью Dead Space 3 16325
• Превью о игре SimC... 14717
• Превью к игре Fuse 15432
• Превью Red Orche... 15532
• Превью Gothic 3 16334
• Превью Black & W... 17345
Главная » Статьи » Всё о XNA » 11 проблем перехода с XNA 3.x на XNA 4.0

11 проблем перехода с XNA 3.x на XNA 4.0

В этой статье будут рассмотрены 11 самых распространённых проблем связанных с переходм на XNA 4.0 с более ранних версий (XNA 3.x)

Чаще всего проблемы возникают именно при при адаптации XNA 3.х кода к новой версии API. Мы рассмотрим конкертные примеры таких проблем. Приведённые ниже решения помогут вам быстро исправить многие ошибки компиляции. Вот их общий список -

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
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


1. SpriteBlendMode, SaveStateMode


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// XNA 3.1 
sprite.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Deferred, SaveStateMode.SaveState); 
// XNA 4.0 
sprite.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend); 
 
// XNA 3.1 вывод спрайтов с сортировкой по глубине 
spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.BackToFront, SaveStateMode.None); 
// XNA 4.0 вывод спрайтов с сортировкой по глубине 
spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend); 
 
// XNA 3.1 
sprite.Begin(SpriteBlendMode.None, SpriteSortMode.Immediate, SaveStateMode.SaveState); 
// XNA 4.0 
sprite.Begin(SpriteSortMode.Immediate, BlendState.Opaque); 
 
// XNA 3.1 вывод рисунка на фон 
spriteBatch.Begin(SpriteBlendMode.None); 
Viewport viewport = GraphicsDevice.Viewport; 
spriteBatch.Draw(background, new Rectangle(0, 0, viewport.Width, viewport.Height), Color.White); 
spriteBatch.End(); 
// XNA 4.0 вывод рисунка на фон 
spriteBatch.Begin(0, BlendState.Opaque); 
spriteBatch.Draw(background, GraphicsDevice.Viewport.Bounds, Color.White); 
spriteBatch.End();


2. RenderState

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
57
58
59
60
61
62
63
64
65
66
// XNA 3.1 включаем смешивание по альфаканалу и  запрещаем запись в буфер глубины
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; 
// XNA 4.0 включаем смешивание по альфаканалу и  запрещаем запись в буфер глубины 
raphicsDevice.BlendState = BlendState.AlphaBlend; GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead;   // XNA 3.1 сброс установок смешивания и буфера глубины GraphicsDevice.RenderState.AlphaBlendEnable = false; GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = false; GraphicsDevice.RenderState.DepthBufferWriteEnable = true; // XNA 4.0 сброс установок смешивания и буфера глубины
GraphicsDevice.BlendState = BlendState.Additive; GraphicsDevice.DepthStencilState = DepthStencilState.Default;   // XNA 3.1 включить буфер глубины
GraphicsDevice.RenderState.DepthBufferEnable = true; 
// XNA 4.0 включить буфер глубины 
GraphicsDevice.DepthStencilState = DepthStencilState.Default;   // XNA 3.1 отключить буфер глубины
GraphicsDevice.RenderState.DepthBufferWriteEnable = false; GraphicsDevice.RenderState.DepthBufferEnable = false; // XNA 4.0 отключить буфер глубины
GraphicsDevice.DepthStencilState = DepthStencilState.None;   // XNA 3.1 смешивание по альфе с учетом глубины (zero on alpha) GraphicsDevice.RenderState.DepthBufferWriteEnable = false; GraphicsDevice.RenderState.AlphaBlendEnable = true; GraphicsDevice.RenderState.SourceBlend = Blend.One; GraphicsDevice.RenderState.DestinationBlend = Blend.One; // XNA 4.0 смешивание по альфе с учетом глубины (zero on alpha)
GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead; GraphicsDevice.BlendState = BlendState.AlphaBlend;   // XNA 3.1 сброс настроек к стандартным GraphicsDevice.RenderState.DepthBufferWriteEnable = true; GraphicsDevice.RenderState.AlphaBlendEnable = false; GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = false; // XNA 4.0 сброс настроек к стандартным
GraphicsDevice.BlendState = BlendState.Opaque; GraphicsDevice.DepthStencilState = DepthStencilState.Default;   // XNA 3.1 смешивание по альфе без учета глубины GraphicsDevice.RenderState.DepthBufferEnable = false; GraphicsDevice.RenderState.DepthBufferWriteEnable = false; GraphicsDevice.RenderState.AlphaBlendEnable = true; GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha; GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha; // XNA 4.0 смешивание по альфе без учета глубины
GraphicsDevice.DepthStencilState = DepthStencilState.None; GraphicsDevice.BlendState = BlendState.AlphaBlend;   // XNA 3.1 обычные установки для вывода 3D модели GraphicsDevice.RenderState.AlphaBlendEnable = false; GraphicsDevice.RenderState.AlphaTestEnable = false; GraphicsDevice.RenderState.DepthBufferEnable = true; // XNA 4.0 обычные установки для вывода 3D модели
GraphicsDevice.BlendState = BlendState.Opaque; GraphicsDevice.DepthStencilState = DepthStencilState.Default;
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
// XNA 3.1 аддитивный режим смешивания 
GraphicsDevice.RenderState.AlphaBlendEnable = true; 
GraphicsDevice.RenderState.SourceBlend = Blend.One; 
GraphicsDevice.RenderState.DestinationBlend = Blend.One; 
// XNA 4.0 аддитивный режим смешивания 
GraphicsDevice.BlendState = BlendState.Additive; 
 
// XNA 3.1 смена обычного режима на аддитивный 
GraphicsDevice.RenderState.DestinationBlend = Blend.One; 
// XNA 4.0 смена обычного режима на аддитивный 
GraphicsDevice.BlendState = BlendState.Additive; 
 
// XNA 3.1 установка обычного режима 
GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha; 
// XNA 4.0 установка обычного режима 
GraphicsDevice.BlendState = BlendState.AlphaBlend; 
 
// XNA 3.1 
GraphicsDevice.RenderState.CullMode = CullMode.CullCounterClockwiseFace; 
// XNA 4.0 
GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise; 
 
// XNA 3.1 обычный код вывода графики...
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;         
// тут рисуем..   
// восстанавливаем настройки 
GraphicsDevice.RenderState.DepthBufferEnable = true; 
GraphicsDevice.RenderState.DepthBufferWriteEnable = true; 
GraphicsDevice.RenderState.AlphaBlendEnable = false; 
GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = false; 
// XNA 4.0 вывод графики, сначала сохраняем настройки 
DepthStencilState ds = GraphicsDevice.DepthStencilState; 
BlendState bs = GraphicsDevice.BlendState;   
//устанавливаем новые значения 
GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead; 
GraphicsDevice.BlendState = BlendState.AlphaBlend;          
// тут рисуем..   
// восстанавливаем настройки из ранее сохраненных
GraphicsDevice.DepthStencilState = ds; 
GraphicsDevice.BlendState = bs;
 


3. Effect and EffectPass, Begin(), End(), CommitChanges(), Clone()

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
// использование эффектов (шейдеров) 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(); 
// использование эффектов (шейдеров) XNA 4.0 
blurEffect.CurrentTechnique.Passes[0].Apply(); GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 2);   // XNA 3.1 передача значений параметров если они были изменены между пассами effect.CommitChanges(); // XNA 4.0 если параметры были изменены то перед вызовом Draw*Primitives - EffectPass.Apply()   // XNA 3.1 начинаем использовать эффект effect.Begin(SaveStateMode.SaveState); effect.CurrentTechnique.Passes[0].Begin(); // XNA 4.0 начинаем использовать эффект
effect.CurrentTechnique.Passes[0].Apply();   // XNA 3.1 завершаем effect.CurrentTechnique.Passes[0].End(); effect.End(); // XNA 4.0 больше не используется. нет такого понятия - "завершить эффект"   // XNA 3.1 копируем эффект Effect newEffect = replacementEffect.Clone(replacementEffect.GraphicsDevice); // XNA 4.0 копируем эффект
Effect newEffect = replacementEffect.Clone();   // XNA 3.1 выбор техники эффекта для SpriteBatch postprocessEffect.CurrentTechnique = postprocessEffect.Techniques[effectTechniqueName]; // Рисуем полноэкранный спрайт (для постпроцессинга) 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(); // XNA 4.0 выбор техники эффекта для SpriteBatch
postprocessEffect.CurrentTechnique = postprocessEffect.Techniques[effectTechniqueName]; // Рисуем полноэкранный спрайт (для постпроцессинга)
spriteBatch.Begin(0, BlendState.Opaque, null, null, null, postprocessEffect); spriteBatch.Draw(sceneRenderTarget, Vector2.Zero, Color.White); spriteBatch.End();


4. MinimumShaderProfile, TotalRealTime, TransparentBlack

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// XNA 3.1 
graphics.MinimumPixelShaderProfile = ShaderProfile.PS_3_0; //любая версия PS...
graphics.MinimumVertexShaderProfile = ShaderProfile.VS_3_0;//любая версия VS... 
// XNA 4.0 шейдерные профили более не используются   // XNA 3.1 float myTime = (float)gameTime.TotalRealTime.TotalSeconds * 0.2f; // XNA 4.0 float myTime = (float)gameTime.TotalGameTime.TotalSeconds * 0.2f;   // XNA 3.1 GraphicsDevice.Clear(Color.TransparentBlack); // XNA 4.0 GraphicsDevice.Clear(Color.Transparent);

 

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

 

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
// XNA 3.1 
ResolveTexture2D sceneMap; 
// XNA 4.0 
RenderTarget2D sceneMap; 
 
// XNA 3.1 определяем формат бэкбуфера 
PresentationParameters pp = GraphicsDevice.PresentationParameters;   
// создаем подходящую текстуру 
sceneMap = new ResolveTexture2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, 1, pp.BackBufferFormat); 
// XNA 4.0 определяем формат бэкбуфера 
PresentationParameters pp = GraphicsDevice.PresentationParameters; // создаем подходящую текстуру
sceneMap = http://static.8gamers.net/images/otherimages/art2/new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false, pp.BackBufferFormat, pp.DepthStencilFormat); // или sceneMap = http://static.8gamers.net/images/otherimages/art2/new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false, pp.BackBufferFormat, pp.DepthStencilFormat, pp.MultiSampleCount, RenderTargetUsage.DiscardContents);   // XNA 3.1 GraphicsDevice.ResolveBackBuffer(sceneMap); // XNA 4.0 GraphicsDevice.SetRenderTarget(sceneMap);   // XNA 3.1 int width = GraphicsDevice.Viewport.Width; int height = GraphicsDevice.Viewport.Height; // новый RenderTarget myRenderTarget = http://static.8gamers.net/images/otherimages/art2/new RenderTarget2D(GraphicsDevice, width, height, 1, SurfaceFormat.Color); // XNA 4.0 int width = GraphicsDevice.Viewport.Width; int height = GraphicsDevice.Viewport.Height; // новый RenderTarget myRenderTarget = http://static.8gamers.net/images/otherimages/art2/new RenderTarget2D(GraphicsDevice, width, height, true, SurfaceFormat.Color, DepthFormat.Depth24);   // XNA 3.1 PresentationParameters pp = GraphicsDevice.PresentationParameters; // еще один способ создания RenderTarget
sceneRenderTarget = http://static.8gamers.net/images/otherimages/art2/new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, 1, pp.BackBufferFormat, pp.MultiSampleType, pp.MultiSampleQuality); // XNA 4.0 PresentationParameters pp = GraphicsDevice.PresentationParameters; // еще один способ создания RenderTarget
sceneRenderTarget = http://static.8gamers.net/images/otherimages/art2/new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false, pp.BackBufferFormat, pp.DepthStencilFormat, pp.MultiSampleCount, RenderTargetUsage.DiscardContents);   // XNA 3.1 PresentationParameters pp = GraphicsDevice.PresentationParameters; // RenderTarget + буфер глубины
drawBuffer = http://static.8gamers.net/images/otherimages/art2/new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, 1, SurfaceFormat.Color, pp.MultiSampleType, 
	pp.MultiSampleQuality);   
drawDepthBuffer = http://static.8gamers.net/images/otherimages/art2/new DepthStencilBuffer(GraphicsDevice, pp.AutoDepthStencilFormat, pp.MultiSampleType, pp.MultiSampleQuality); 
// XNA 4.0 
PresentationParameters pp = GraphicsDevice.PresentationParameters;   
// RenderTarget + буфер глубины 
drawBuffer = http://static.8gamers.net/images/otherimages/art2/new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, true, SurfaceFormat.Color, DepthFormat.Depth24Stencil8, pp.MultiSampleCount, RenderTargetUsage.DiscardContents); // !!! DepthStencilBuffer больше не используется   // XNA 3.1 spriteBatch.Draw(myRenderTarget.GetTexture(), Vector2.Zero, Color.White); // XNA 4.0 spriteBatch.Draw(myRenderTarget, Vector2.Zero, Color.White); // !!! ".GetTexure()" больше не используется
  // XNA 3.1 Texture2D myTexture = myRenderTarget.GetTexture(); // XNA 4.0 Texture2D myTexture = myRenderTarget; // !!! ".GetTexure()" больше не используется
  // XNA 3.1 GraphicsDevice.SetRenderTarget(0, myRenderTarget); // XNA 4.0 GraphicsDevice.SetRenderTarget(myRenderTarget);   // XNA 3.1 установка 2-ух RenderTarget
GraphicsDevice.SetRenderTarget(0, colorRT); 
GraphicsDevice.SetRenderTarget(1, depthRT); 
// XNA 4.0 установка 2-ух RenderTarget 
GraphicsDevice.SetRenderTargets(colorRT, depthRT);   // XNA 3.1 GraphicsDevice.SetRenderTarget(0, null); // XNA 4.0 GraphicsDevice.SetRenderTarget(null);   // XNA 3.1 чтение из буфера глубины GraphicsDevice.ResolveBackBuffer(depthMap); // рисуем сцену + блюр с учетом буфера глубины GraphicsDevice.Textures[1] = depthMap; Viewport viewport = GraphicsDevice.Viewport; dofEffect.CurrentTechnique = depthBlurTechnique; DrawFullscreenQuad(sceneMap, viewport.Width, viewport.Height, dofEffect); // XNA 4.0 чтение из буфера глубины
GraphicsDevice.SetRenderTarget(null); // рисуем сцену + блюр с учетом буфера глубины
GraphicsDevice.Textures[1] = depthMap; GraphicsDevice.SamplerStates[1] = SamplerState.PointClamp; Viewport viewport = GraphicsDevice.Viewport; dofEffect.CurrentTechnique = depthBlurTechnique; DrawFullscreenQuad(sceneMap, viewport.Width, viewport.Height, dofEffect);   // XNA 3.1 ResolveTexture2D resolveTarget; RenderTarget2D renderTarget1; RenderTarget2D renderTarget2; // определяем формат бэк буфера PresentationParameters pp = GraphicsDevice.PresentationParameters; int width = pp.BackBufferWidth; int height = pp.BackBufferHeight; SurfaceFormat format = pp.BackBufferFormat; // создадим текстуру куда можно скопировать бэк буфер resolveTarget = http://static.8gamers.net/images/otherimages/art2/new ResolveTexture2D(GraphicsDevice, width, height, 1, format);
// создадим 2 RenderTarget половинного размера 
width /= 2; height /= 2; renderTarget1 = http://static.8gamers.net/images/otherimages/art2/new RenderTarget2D(GraphicsDevice, width, height, 1,format); renderTarget2 = http://static.8gamers.net/images/otherimages/art2/new RenderTarget2D(GraphicsDevice, width, height, 1,format); // ... в коде вывода... GraphicsDevice.ResolveBackBuffer(resolveTarget); // .. тут используем эффект... // XNA 4.0 RenderTarget2D sceneRenderTarget; RenderTarget2D renderTarget1; RenderTarget2D renderTarget2; // определяем формат бэк буфера
PresentationParameters pp = GraphicsDevice.PresentationParameters; int width = pp.BackBufferWidth; int height = pp.BackBufferHeight; SurfaceFormat format = pp.BackBufferFormat; // создадим текстуру куда можно скопировать бэк буфер
sceneRenderTarget = http://static.8gamers.net/images/otherimages/art2/new RenderTarget2D(GraphicsDevice, width, height, false, format, pp.DepthStencilFormat, pp.MultiSampleCount, RenderTargetUsage.DiscardContents); // создадим 2 RenderTarget половинного размера
width /= 2; height /= 2; renderTarget1 = http://static.8gamers.net/images/otherimages/art2/new RenderTarget2D(GraphicsDevice, width, height, false, format, DepthFormat.None); renderTarget2 = http://static.8gamers.net/images/otherimages/art2/new RenderTarget2D(GraphicsDevice, width, height, false, format, DepthFormat.None); // ...код вывода... GraphicsDevice.SetRenderTarget(sceneRenderTarget); GraphicsDevice.SamplerStates[1] = SamplerState.LinearClamp; // ...используем эффект....

 

6. VertexDeclaration, Vertices, VertexElements, SizeInBytes

 

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 3.1 формат вершин для вывода моделей  
GraphicsDevice.VertexDeclaration = http://static.8gamers.net/images/otherimages/art2/new VertexDeclaration(VertexPositionTexture.VertexElements); 
// XNA 4.0 формат вершин более отдельно не используется 
 
// XNA 3.1 установка буфера и формата вершин 
GraphicsDevice.VertexDeclaration = vertexDeclaration; 
GraphicsDevice.Vertices[0].SetSource(vertexBuffer, 0, VertexPositionTexture.SizeInBytes); 
// XNA 4.0 установка буфера и формата вершин 
GraphicsDevice.SetVertexBuffer(vertexBuffer); 
 
// XNA 3.1 создание формата вершин 
vertexDeclaration = http://static.8gamers.net/images/otherimages/art2/new VertexDeclaration(GraphicsDevice, VertexPositionTexture.VertexElements); 
// XNA 4.0 создание формата вершин 
vertexDeclaration = http://static.8gamers.net/images/otherimages/art2/new VertexDeclaration(VertexPositionTexture.VertexDeclaration.GetVertexElements()); 
 
// XNA 3.1 сброс формата и буфера 
GraphicsDevice.VertexDeclaration = null; 
GraphicsDevice.Vertices[0].SetSource(null, 0, 0); 
// XNA 4.0 сброс формата и буфера 
GraphicsDevice.SetVertexBuffer(null); 
 
// XNA 3.1 передача данных в буфер 
VertexPositionNormalTexture[] vertices = http://static.8gamers.net/images/otherimages/art2/new VertexPositionNormalTexture[100];    
vertexBuffer.SetData<VertexPositionNormalTexture>(VertexPositionNormalTexture.SizeInBytes * vertexCount, 
	vertices,vertexCount,count,VertexPositionNormalTexture.SizeInBytes); 
// XNA 4.0 передача данных в буфер 
VertexPositionNormalTexture[] vertices = http://static.8gamers.net/images/otherimages/art2/new VertexPositionNormalTexture[100];   
vertexBuffer.SetData<VertexPositionNormalTexture>(vertices); 

 

 

7. VertexBuffer, StreamOffset, VertexStride, IndexBuffer, BaseVertex

 

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 3.1 для всех частей мэша 
foreach (ModelMeshPart meshPart in mesh.MeshParts) 
{     
if (meshPart.PrimitiveCount > 0)     
{         
// установка вершин и индексов
GraphicsDevice.VertexDeclaration = meshPart.VertexDeclaration;         
GraphicsDevice.Vertices[0].SetSource(mesh.VertexBuffer, meshPart.StreamOffset, meshPart.VertexStride);         
GraphicsDevice.Indices = mesh.IndexBuffer;         
... 
// XNA 4.0 
GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap; // may be needed in some cases...   
// для всех частей мэша 
foreach (ModelMeshPart meshPart in mesh.MeshParts) 
{     
if (meshPart.PrimitiveCount > 0)     
{         
// установка вершин и индексов
GraphicsDevice.SetVertexBuffer(meshPart.VertexBuffer);         
GraphicsDevice.Indices = meshPart.IndexBuffer;         
... 
 
// XNA 3.1 вывод примитивов 
GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, meshPart.BaseVertex, 0, meshPart.NumVertices, 
meshPart.StartIndex, meshPart.PrimitiveCount); 
// XNA 4.0 вывод примитивов 
GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, meshPart.VertexOffset, 0, meshPart.NumVertices, 
meshPart.StartIndex, meshPart.PrimitiveCount);

 

 

8. Points, PointSpriteEnable, PointSizeMax, PointList

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// XNA 3.1  создание буфера вершин
vertexBuffer = http://static.8gamers.net/images/otherimages/art2/new VertexBuffer(GraphicsDevice, typeof(VertexPositionNormalTexture),
                                 250, BufferUsage.WriteOnly | BufferUsage.Points); 
// XNA 4.0 создание буфера вершин 
vertexBuffer = http://static.8gamers.net/images/otherimages/art2/new VertexBuffer(GraphicsDevice, typeof(VertexPositionNormalTexture),
                                 250, BufferUsage.WriteOnly | BufferUsage.None); 
 
// XNA 3.1 PointSprite
GraphicsDevice.RenderState.PointSpriteEnable = true; 
GraphicsDevice.RenderState.PointSizeMax = 128; 
// XNA 4.0 PointSprite более недоступны
 
// XNA 3.1 вывод 
GraphicsDevice.DrawPrimitives(PrimitiveType.PointList, vertexPosition, numberVertices); 
// XNA 4.0 вывод в виде линий 
GraphicsDevice.DrawPrimitives(PrimitiveType.LineList, vertexPosition, numberVertices); 

 

 

9. OpenContainer, BeginShowStorageDeviceSelector, EndShowStorageDeviceSelector, Path, TitleLocation, FileStream

 

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
// XNA 3.1 открываем StorageContainer 
StorageContainer storageContainer = storageDevice.OpenContainer("YourGameName"); 
// XNA 4.0 для простоты создадим собственный метод для замены storageDevice.OpenContainer...    
///  
/// Synchronously opens storage container 
///  
private static StorageContainer OpenContainer(StorageDevice storageDevice, string saveGameName) 
{     
       IAsyncResult result = storageDevice.BeginOpenContainer(saveGameName, null, null);
        // ожидание завершения операции
       result.AsyncWaitHandle.WaitOne();
       StorageContainer container = storageDevice.EndOpenContainer(result);
       result.AsyncWaitHandle.Close();
       return container; 
}   
// открываем StorageContainer 
storageContainer = OpenContainer(storageDevice, "YourGameName"); 
 
// XNA 3.1 выбор устройства хранения 
Guide.BeginShowStorageDeviceSelector(GetStorageDeviceResult, retrievalDelegate); 
// XNA 4.0 выбор устройства хранения 
if (!Guide.IsVisible) 
{
     StorageDevice.BeginShowSelector(GetStorageDeviceResult, retrievalDelegate);
} 
 
// XNA 3.1 закрытие диалога выбора  
storageDevice = Guide.EndShowStorageDeviceSelector(result); 
// XNA 4.0 закрытие диалога выбора 
storageDevice = StorageDevice.EndShowSelector(result); 
 
// XNA 3.1 обзор файлов  
string[] filenames = Directory.GetFiles(storageContainer.Path, "LevelSetup*.xml"); 
// XNA 4.0 обзор файлов 
string[] filenames = storageContainer.GetFileNames("LevelSetup*.xml"); 
 
// XNA 3.1 сохранение 
using (FileStream stream = http://static.8gamers.net/images/otherimages/art2/new FileStream(Path.Combine(storageContainer.Path, levelFilename), FileMode.Create)) 
{
     http://static.8gamers.net/images/otherimages/art2/new XmlSerializer(typeof(SaveGameLevel)).Serialize(stream, levelData); 
} 
// XNA 4.0 сохранение 
using (Stream stream = storageContainer.OpenFile(levelFilename, FileMode.Create)) 
{
     http://static.8gamers.net/images/otherimages/art2/new XmlSerializer(typeof(SaveGameLevel)).Serialize(stream, levelData); 
} 
 
// XNA 3.1 удаление 
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")); 
}
// XNA 4.0 удаление. используем наш метод 
using (StorageContainer storageContainer = OpenContainer(storageDevice, "saveGameName")) 
{
     storageContainer.DeleteFile(saveGameLevel.FileName);
     storageContainer.DeleteFile("SaveGameLevel" + 
	Path.GetFileNameWithoutExtension(saveGameLevel.FileName).Substring(8) + ".xml"); 
} 
 
// XNA 3.1 загрузка уровня...   
string levelPath;   
// цикл по уровням 
while (true) 
{
     // ищем нумерованные файлы
     levelPath = String.Format("Levels/{0}.txt", ++levelIndex);
     levelPath = Path.Combine(StorageContainer.TitleLocation, "Content/" + levelPath);
     if (File.Exists(levelPath))
         break;
 
     if (levelIndex == 0)
         throw http://static.8gamers.net/images/otherimages/art2/new Exception("No levels found.");
 
     levelIndex = -1; 
}
 
// выгружаем старый уровень перед загрузкой нового 
if (level != null)
     level.Dispose();
 
level = http://static.8gamers.net/images/otherimages/art2/new Level(Services, levelPath); 
// XNA 4.0 загрузка уровня...   
levelIndex = (levelIndex + 1) % numberOfLevels;   
// выгружаем старый уровень перед загрузкой нового 
if (level != null)
     level.Dispose();
 
string levelPath = string.Format("Content/Levels/{0}.txt", levelIndex)
using (Stream fieStream = TitleContainer.OpenStream(levelPath))
     level = http://static.8gamers.net/images/otherimages/art2/new Level(Services, fileStream, levelIndex); 
 
// XNA 3.1 сохранение на устройстве
if ((storageDevice == null) || !storageDevice.IsConnected) 
{
     return; 
}   
 
using (StorageContainer storageContainer = storageDevice.OpenContainer(Session.SaveGameContainerName)) 
{
     string filename;
     string descriptionFilename;
 
     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 = http://static.8gamers.net/images/otherimages/art2/new FileStream(filename, FileMode.Create))
     {
         using (XmlWriter xmlWriter = XmlWriter.Create(stream))
         {
             //create and write xml data...
         }
     }
 
     SaveGameDescription description = http://static.8gamers.net/images/otherimages/art2/new SaveGameDescription();
     description.FileName = Path.GetFileName(filename);
     description.ChapterName = IsQuestLineComplete ? "Quest Line Complete" : Quest.Name;
     description.Description = DateTime.Now.ToString();
 
     using (FileStream stream = http://static.8gamers.net/images/otherimages/art2/new FileStream(Path.Combine(storageContainer.Path, descriptionFilename), FileMode.Create))
     {
         http://static.8gamers.net/images/otherimages/art2/new XmlSerializer(typeof(SaveGameDescription)).Serialize(stream, description);
     }
 } 
// XNA 4.0 сохранение на устройстве    
if ((storageDevice == null) || !storageDevice.IsConnected) 
{
     return;
}
 
using (StorageContainer storageContainer = OpenContainer(storageDevice, Session.SaveGameContainerName)) 
{
     string filename;
     string descriptionFilename;
 
     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...
         }
     }
 
     SaveGameDescription description = http://static.8gamers.net/images/otherimages/art2/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))
     {
         http://static.8gamers.net/images/otherimages/art2/new XmlSerializer(typeof(SaveGameDescription)).Serialize(stream, description);
     }
}

 

 

10. VertexShader, PixelShader, ps_1_x

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
// XNA 3.1 
VertexShaderOutput VertexShader(...) 
{
     //some code
}
 
float4 PixelShader(...)
{
    // some code 
}
 
// XNA 4.0 
// "VertexShader" теперь ключевое слово 
VertexShaderOutput  VertexShaderFunction(...) 
{
    // some code 
}
 
// "PixelShader" теперь ключевое слово 
float4 PixelShaderFunction(...) 
{
    // some code
} 
 
// XNA 3.1 
technique 
{
     pass
     {
         VertexShader = compile vs_1_1 VertexShader();
         PixelShader  = compile ps_1_1 PixelShader();
     } 
} 
// XNA 4.0 
technique 
{
     pass
     {
         VertexShader = compile vs_2_0 VertexShaderFunction();
         PixelShader  = compile ps_2_0 PixelShaderFunction();
     } 
}

 

11. Если 3D модель выглядит "наизнанку" или полупрозрачной

1
2
3
// установки для корректного вывода 3D модели 
GraphicsDevice.BlendState = BlendState.Opaque; 
GraphicsDevice.DepthStencilState = DepthStencilState.Default;

 

 

/span/spancolor: #008000; /spanspan style=
2258 Прочтений •  [11 проблем перехода с XNA 3.x на XNA 4.0] [08.08.2012] [Комментариев: 0]
Добавил: Ukraine Vova
Ссылки
HTML: 
[BB Url]: 
Похожие статьи
Название Добавил Добавлено
• 11 проблем перехода с XNA 3.x на XN... Ukraine Vova 08.08.2012
Ни одного комментария? Будешь первым :).
Пожалуйста, авторизуйтесь для добавления комментария.

Проект входит в сеть сайтов «8Gamers Network»

Все права сохранены. 8Gamers.NET © 2011 - 2025

Статьи
Рецензия на Pressure
Рецензия на Pressure
Чтобы обратить на себя внимание, начинающие маленькие разработчики, как правило, уходят в жанры, ...
Рецензия на Lost Chronicles of Zerzura
Рецензия на Lost Chron...
Игры, сделанные без любви и старания, похожи на воздушный шар – оболочка есть, а внутри пусто. Lo...
Рецензия на The Bridge
Рецензия на The Bridge
«Верх» и «низ» в The Bridge — понятия относительные. Прогуливаясь под аркой, можно запросто перей...
Рецензия на SimCity
Рецензия на SimCity
Когда месяц назад состоялся релиз SimCity, по Сети прокатилось цунами народного гнева – глупые ош...
Рецензия на Strategy & Tactics: World War 2
Рецензия на Strategy &...
Название Strategy & Tactics: World War II вряд ли кому-то знакомо. Зато одного взгляда на ее скри...
Рецензия на игру Scribblenauts Unlimited
Рецензия на игру Scrib...
По сложившейся традиции в информационной карточке игры мы приводим в пример несколько похожих игр...
Рецензия на игру Walking Dead: Survival Instinct, The
Рецензия на игру Walki...
Зомби и продукция-по-лицензии — которые и сами по себе не лучшие представители игровой биосферы —...
Обратная связь | RSS | Донейт | Статистика | Команда | Техническая поддержка