XNA
Microsoft XNA is a set of tools with a managed runtime XNA Initialization environment for computer game development and management. XNA Framework i s b ased on nati ve i mpl ementati on of .NET Compact Framework 2.0 for Xbox 360 development and .NET Framework 2 .0 on Windows . XNA games can run on any platform that supports the 305890 XNA Framework with minimal or no modification . Spring 2014 But, only C# in XNA Game Studio Express IDE and all 3/04/2014 versions of Visual Studio 2008 and 2010 (()as of XNA 4.0) Kyoung Shin Park are officially supported.
XNA Framework XNA 3.0 =>XNA4.0> XNA 4.0 What’sNewinXNAGameStudio40 s New in XNA Game Studio 4.0 XNA 4.0 Profiles Reach HiDef Supported platforms Windows Phone 7 Series, Xbox 360, and any Wind Xbox 360, and any Windows PC with a DirectX 10 ( ows PC with a DirectX 9 GPU that supports at lea or equivalent: see below) GPU Develop Games for Windows Phone 7 st shader model 2.0 Shader model 2.0 (but Windows Phone does not support custo 3.0+ (Xbox 360 supports custom shader extensions s Leverage Windows Phone-specific Features Through m shaders) uch as vfetch, which are not available on Windows) Max texture size 2048 4096 Silverlight Max cubemap size 512 4096 Max volume texture size Volume textures are not supported 256 Non power of two textures Conditional: cannot use wrap addressing mode, m Yes Simplified Graphics Interfaces ipmaps, or DXT compression when the size is not a power of two Reach profile is designed for compatibility across the largest Non power of two cubemaps No Yes possible range of devices Non power of two volume textures Volume textures are not supported Yes Max primitives per draw call 65535 1048575 HiDef profile allows you to use platform showcase features Index buffer formats 16 bit 16 and 32 bit Vertex element formats Color, Byte4, Single, Vector2, Vector3, Vector4, Sh All of the Reach formats, plus HalfVector2, HalfVecto ort2, Short4, NormalizedShort2, NormalizedShort4 r4 Configurable Effects TtTexture f ormat s Col or, B gr 565, B gra 5551, B gra4444 , N ormali zedB yt All of th e R each f ormat s, pl us Al ph a8 , R g32 , R gb a64 , e2, NormalizedByte4, Dxt1, Dxt3, Dxt5 Rgba1010102, Single, Vector2, Vector4, HalfSingle, H alfVector2, HalfVector4. Floating point texture format Built-in State Objects s do not support filtering. Vertex texture formats Vertex texturing is not supported Single, Vector2, Vector4, HalfSingle, HalfVector2, Hal System Support for Scalars and Orientation fVec tor 4 Render target formats Variable (see below) Variable (see below) Multiple render targets No Up to 4. Must all have the same bit depth. Supports Cross-Platform Input API alpha blending and independent write masks per re ndertarget. Enhanced Audio Support Occlilusion quer ies No Yes Separate alpha blend No Yes Music and Picture Enumeration and Video Playback Blend.SourceAlphaSaturation Only for SourceBlend, not DestinationBlend Yes Max vertex streams 16 16 Max stream stride 255 255
XNA 4 .0 Effects XNA 4 .0 Built -in State Objects
Basic Effects BlendState Contains a basic rendering effect Controls how color and alpha values are blended when combining rendered data with existing render target data Dual Texture Effects Contains a configurable effect that supports two-layer DepthStencilState multitexturing Controls how the depth buffer and the stencil buffer are used Alpha Test Effects RasterizerState Contains a configurable effects that supports alpha testing Gets/Sets rasterizer state – The default value is RasterizerState.CullCounterClockwise Skinned Effects Contains a configurable effect for rendering skinned character SamplerState models Contains sampler state, which determines how to sample texture data Environment Map Effects Contains a configurable effect that supports environment mapping Installing XNA Getting Started with XNA 4. 0
Start a Visual Studio 2010 VC# Visual Studio 2010 Installation & Rebooting Create a new XNA4.0 project DirectX9.0c Runtime Installation File->New->Projects directx_Jun2010 _redist .exe Visual C#->XNA Game Studio 4 .0 ->Windows Game (4. 0) http://www.microsoft.com/en-us/download/details.aspx?id=8109 Specify the project name XNA Game Studio 4.0 Installation Build (()F7) & Execute ( ()F5) http://www.microsoft.com/en-us/download/details.aspx?id=23714 Create a new project & Run Visual Studio 2010 메뉴에서 File->New->Projects Visual C#->XNA Game Studio 4.0 ->Windows Game (4.0) 선택 프로젝트 이름 지정
9
///
Your First XNA Game Your First XNA Game
Add the 500x500 screen size & “Test1” title Add a code for ESC-key to exit program
protected override void Initialize() // keyboard & gamepad variables { private KeyboardState currentKeyboardState =new= new KeyboardState(); // TODO: Add your initialization logic here private GamePadState currentGamePadState = new GamePadState(); graphics.PreferredBackBufferWidth = 500; graphics.PreferredBackBufferHeight = 500; // add HandleInput graphics.IsFullScreen = false; protected override void Update(GameTime gameTime) graphics. ApplyChanges(); { Window.Title = "Test1"; // Allows the game to exit HandleInput(); base.Initialize(); } // TODO: Add your update logic here base.Update(gameTime); } Your First XNA Game XNA Example
// ESC-key 또는 게임패드의 버튼1이 눌렸을 경우 프로그램 종료 #region Handle Input ///
// Check f or exit . if (currentKeyboardState.IsKeyDown(Keys.Escape) || currentGamePadState.Buttons.Back == ButtonState.Pressed) { this.Exit(); } } #endregion
XNA Example Your First XNA Game
Add a sprite // texture Add an image (eg: CAHUFOZY.jpg) into the Content private Texture2D myTexture; // set texture we can render private Vector2 spritePosition = Vector2.Zero; // set coordinates
protected override void LoadContent() { // Create a new SpriteBatch, which can be used for draw texture spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here myTexture = Content.Load
// TODO: Add your drawing code here // draw the sprite spriteBatch.Begin(SpriteSortMode.BackToFront,BlendState.AlphaBlend); spriteBatch.Draw(myTexture, spritePosition, Color.White); spriteBatch.End();
base.Draw (gameTime); }
Your First XNA Game Your First XNA Game
Add the sprite’s movement // Check for bounce. // sprite’s motion if (spritePosition.X > MaxX) { private Vector2 spriteSpeed = new Vector2(50.0f, 50.0f); spriteSpeed.X *= -1; spritePosition.X = MaxX; void UpdateSprite(GameTime gameTime) } else if (spritePosition.X < MinX) { { // Move the sprite by speed, scaled by elapsed time. spppriteSpeed.X *= -1; spritePosition += spriteSpeed * spritePosition.X = MinX; (float)gameTime.ElapsedGameTime.TotalSeconds; } if (spritePosition.Y > MaxY) { int MaxX = graphics.GraphicsDevice.Viewport.Width – spriteSpeed.Y *= -1; myTexture.Width; spritePosition.Y = MaxY; int MinX =0;= 0; }elseif(} else if (spritePosition.Y < MinY){) { int MaxY = graphics.GraphicsDevice.Viewport.Height - myTexture.Heigh spriteSpeed.Y *= -1; int MinY = 0; spritePosition.Y = MinY; } } Your First XNA Game Your First XNA Game protected override void Update(GameTime gameTime) { // 중간생략 // add UpdateSprite UpdateSprite(gameTime); // 중중생략간생략 }
XNA’s Game Loop What is a Game Loop?
The XNA’s game loop is managed by the Game class. The Game class implements a game loop, which The basic game loop is as follows: provides no t on ly the w in dow w hich di spl ays your game, but also provides overloadable methods that your game imppylements to facilitate communication between your game and OS. Creating a new game is to make a class that derives from Game. The new class needs to override Update, Draw, Initialize. A fixed-steppp Game tries to call its Update method on the fixed interval specified in TargetElapsedTime. Game components provide a modular way of adding functionality to a game . Game services are a mechanism for maintaining loose couppgling between obj ects that need to interact with each other. XNA Game Components XNA Game Components
XNA game component allows us to separate pieces of class FpsCounter : Microsoft.Xna.Framework.DrawableGameComponent logic into their own file that will be called automatically { by the XNA Framework. FpsCounter(Game game) : base(game) {…} Initialize() { … } YdihYou derive the new component from GCGameComponent class, or, if the component loads and draws graphics Update(GameTime gameTime) { … } content, from DrawableGameComponent class Draw(GameTime gameTime)){ { ... } // only for DrawableGameComponent Method } Constructor // Add XNA G ame C omponent s Initialize() – called by the Framework when the component starts static FpsCounter fpsCounter; Update() – called by the Framework when the component needs protected override void Initialize() to be updated { // .. 중간 생략 Draw() – called by the Framework when the component needs fpsCounter = new FpsCounter(this); to be drawn (for only DrawableGameComponent) Components.Add(fpsCounter); }
XNA Game Components XNA Game Services
XNA GameComponent class XNA game services are a mechanism for maintaining http://msdn.microsoft.com/en- loose coupling between objects that need to interact us/library/microsoft.xna.framework.gamecomponent_members.aspx with each other. XNA DrawableGameComponent class A serv ice is reg istere d by calli ng http://msdn.microsoft.com/en- Game.Services.AddService specifying the type of service us/library/microsoft.xna .framework .drawablegamecomponent _memb being implemented and a reference to the object ers.aspx providing the service. CCeateareate a XNA Gam eCompo ne nt Services.AddService( typeof( IMyService ), myyjobject ); http://msdn.microsoft.com/en- Once a service is registered, the object providing the us/library/bb199634(v=xnagamestudio.40).aspx service can be retrieved by Game.Services.GetService IGraphicsDeviceService graphicsservice = (IGraphicsDeviceService)Game.Services.GetService( typeof( IGraph icsDeviceService ));) ); XNA Game Services Your First XNA Game
// add gamecomponents into the services in (Game1.cs) Add a text for fpsCounter on the screen inputs = new InputHandler(this); Add a font (eg: Font1.spritefont) into the Content Components.Add(inputs); Servi ces. AddServi ce( typeof(I nput Han dler ), i nputs) ;
// getti ng th e component b ack out f rom anoth er i n (FpsCounter.cs) inputs = (InputHandler)Game.Services.GetService(typeof(InputHan dler));
if (inputs.IsKeyPressed(Keys.F)) …
Your First XNA Game Your First XNA Game
// font private SpriteFont font1; private Vector2 textPosition = new Vector2(10, 10); // set coordinates protected override void LoadContent() { // 중간 생략 font1= Content.Load
The XNA Game Studio Content Pipeline is a set of The chief reason XNA Game Studio uses a Content processes applied to a game's art and data assets when Pipeline is to help your game run fast. the game is built. Game artists can use the DCC tools of their choice. Content illhis all the parts of your game t hat are not If all game assets are in file formats supported by the executing managed code. It includes all art assets, such Standard Importers and Processors provided by XNA as textures, sprites , meshes , effects , and fonts ;and; and GStdithdlGame Studio, the game developer never need dtbs to be includes sound assets, such as music or brief sound concerned with the specifics of that file format, nor effects. It also can include data assets, such as tables of possess a detailed knowledge of how the Content levels or character attributes. Pipeline works. Most content will be created using a digital content If reqq,uired, the Content Pippyeline can easily be creation (DCC) tool, such as a paint program or a 3D customized or extended to import a new file format or model editor. The content your game uses is stored in a to produce custom output. variety of file formats: e. g., JPEG, FBX.
XNA Content Pipeline XNA Content Pipeline
XNA Content Pipeline Standard Importers XNA Content Pipeline Standard Processors Name Type name Output type Description Imports game assets specified with the Autodesk FBX file format (.fbx). Name Type name Output type Description Autodesk FBX FbxImporter NodeContent This importer is designed to work with assets exported with the 2006.11 versio A parameterized processor that outputs models as a ModelContent Class n of the FBX exporter. object. Available parameters: Effect EffectImporter EffectContent Imports a game asset specified with the DirectX Effect file format (.fx). Color Key Color–Any valid Color. Magenta is the default value. ModelContent MdlPModelProcessor ClColor K ey Ena bldbled–ABA Boo lean va lue in dica ting if co lor key ing is ena bldbled. The Sprite Font Model Class FontDescriptionImporter FontDescription Imports a font description specified in a .spritefont file. default value is true. Description Generate Mipmaps–A Boolean value indicating if mipmaps are generated. The Imports a texture. These file types are supported: .bmp, .dds, .dib, .hdr, .jpg, .pf TextureImporter TextureContent default value is false. ….. Texture m, .png, .ppm, and .tga. Sprite Font FontDescriptionProcess Imports ga me assets spec ifi ed wi th th e Dir ectX X fil e f orm at (.x ). Thi s im por ter SpriteFontContent Converts a .spritefont file specifying a font description into a font. XImpor ter NdCNodeCont ent or XFilX File expects the coordinate system to be left-sided. DiiDescription Imports game audio specified in the Microsoft Cross-Platform Audio Creation Sprite Font A parameterized processor that outputs a sprite font texture as a Tool (XACT) format (.xap file). FontTextureProcessor SpriteFontContent SpriteFontContent object. Available parameters: Associating an .xap file with XACT allows you to automatically open XACT whe Texture First Character–Any valid character. The space character is the default value. n editing any .xap file. To associate the file in XNA Game Studio Sprite Font FontTextureProcessor SpriteFontContent Converts a sppyecially marked 2D bitmap p(p) file (.bmp) into a font. Pixels of 1.In Solution Explorer, right-click the .xap file, and then click Open With. Texture Color.Magenta are converted to Color.Transparent. XACT Project N/A N/A 2.In the dialog box, select the XACT-specific string, and then click Set As Defa ult. A parameterized processor that outputs textures as a TextureContent Class object. Available parameters: To run XACT: If the XACT-specific option is unavailable, you must run XACT be TextureContent TextureProcessor Color Key Color–Any valid Color. Magenta is the default value. fore this option appears. The application is available from the Microsoft XNA Texture Class Game Studio group . On the Start menu , click Tools , and then click Microsoft C Color Key Enabled–A Boolean value indicatinggyg if color keying is enabled. The ross-Platform Audio Creation Tool (XACT) . default value is true. ….. Imports XML content used for editing the values of a custom object at run tim XACT Project N/A N/A Generates audio assets from an XACT project. e. For instance, you could pass XML code to this importer that looks for the sp ecified property of a custom type and changes it to the specified value. You c ould then process the custom object with a processor or pass it to your game XML Content XmlImporter object untouched using the No Processing Required processor. This importer is designed for scenarios like importing an XML file that describ es game data at run time (similar to the Sprite Font Description importer) or i mporting terrain data in an XML file that then is passed to a processor that ge nerates a random terrain grid using that data. XNA Content Pipeline Components Design-Time Components
A game asset is made available to an XNA Game Studio Design-time components use the Content Pipeline game after it is added to the Content project. Once the Class Library, which can be used and extended to create asset is part of the game solution, it is included in the custom Content Pipeline design-time components. Content Pipeline. Component Description An importer converts art assets from a particular DCC file for mat to objects i n th e XNA Game S tudi o CDContent Document Importer Object Model(DOM) that standard content processors can co nsume, or to some other custom form that a particular custo m p rocesso r can consume .
A processor takes one specific type of imported art asset, suc Content h as a set of meshes, and compiles it into a managed code o processor bject that can be loaded and used by XNA Game Studio gam es on Windows, Xbox 360, or Windows Phone.
Runtime Components Using Localization Sample
Runtime components of the Content Pipeline support Download Localization Sample from loading and using the transformed game asset by your http://xbox.create.msdn.com/ko- XNA Game Studio game. These components use the KR/education/catalog/sample/localization XNA library , which can be extended to create custom Create LliiPilidllLocalizationPipeline.dll components.
Component Description When the game needs the game asset's managed code object, it must call the ContentManager.Load method to invoke the Content content loader, specifying the object type it expects. The Loader content loader then locates and loads the asset from the compact binary format (.XNB) file into the memory space of the game where it can be used. Using Localization Sample Using Localization Sample
Copy “LocalizationPipeline.dll” into your program Add “LocalizationPipeline.dll” Reference into your content directory program content project
Using Localization Sample Using Localization Sample
Edit “LocalizationFont.spritefont” property Edit “LocalizationFont.spritefont” Content Processor => LocalizedFontProcessor
Add “LocalizationFont.spritefont” into your program Add “LocalizationFontStrings.resx” into your game content (Add -> New Item -> Sprite Font) program (Add -> New Item -> 리소스 파일)
Using Localization Sample Using Localization Sample
Add “LocalizationFontStrings.resx” for your game Edit “Game1.cs” program SpriteFont font1 = Content.Load
protected override void Draw(GameTime gameTime) { // 중간생략... spriteBatch.Begin(); spriteBatch.DrawString(font2, LocalizationFontStrings.Test, textPosition2, Color.White); spriteBatch.DrawString(font2, LocalizationFontStrings.Game, textPosition3, Color.White); spriteBatch.End(); } Your First XNA Game w/ Korean Font Reference
http://msdn.microsoft.com/en- us/library/bb417503(v=xnagamestudio.40).aspx http://msdn.microsoft.com/en- us/library/bb203893( v=xnagamestudi o.40) .aspx http://msdn.microsoft.com/en- us/library/bb203873( v=xnagamest udi o.40) .aspx http://msdn.microsoft.com/en-us/library/bb447756.aspx http:// msd n.mi crosoft .com/ en-us/library/bb447745 .aspx