SlideShare a Scribd company logo
1 of 47
How to Create Your
First
Windows 8 Metro-style Game
Chas. Boyd
Principal Program Manager
Microsoft Corporation
Three Presentations Today

Step by Step through Game Development
1) How to set up the game
2) How to code it      <- You are here
3) How to optimize it
Agenda
Quick summary of the platform
Step through the process of development
from a programmer’s perspective:
     App Initialization
     Opening a Window
     Rendering Graphics
     Loading and Saving
     Adding Input Controls
     Adding Sound Effects
     Adding an Art Pipeline

This talk’s sample code is in C++
Platform Overview
Metro style apps                         Desktop apps
  View




                        DX          XAML                HTML / CSS
                                                                                            C
Controller




                        C                C#
 Model




                                                        JavaScript      HTML         C      #
                       C++               VB                            JavaScript
                                                                                    C++     V
                                    WinRT APIs                                              B
  System Services




                    Communication       Graphics           Devices
                       & Data           & Media           & Printing
                                                                                            .NE
                                    Application Model                  Internet
                                                                                    Win32    T
                                                                       Explorer              SL
  Kernel




                                        Windows Kernel Services
Your Killer Game


           Movies & Cut                                                    Connected
Graphics                  Game Input       Audio          Local Services                 Tools
             Scenes                                                         Services

             DirectX        Pointer                                        Windows      Visual
Direct3D                                  WASAPI              PLM
             Video           Point                                           Live       Studio

             Media                                                         Windows       Asset
Direct2D                  Sensor API      XAudio2           AppData
           Foundation                                                       Store       Viewers

                                                                                         Asset
 HTML                       XInput                          Contracts      Xbox LIVE
                                                                                       Processors

 XAML
Windows Runtime
All WinRT APIs are native
WinRT APIs feel natural in C++, C#/VB, and JavaScript
Reuse of portable C++ code just works
WinRT APIs provide rich access to devices, OS, and
services
HTML5/CSS/JavaScript and XAML are great for Metro style
apps
     Providing a rich set of controls
Native DirectX is great for Metro style apps
Updated C++ language support
File->New Project templates for native DirectX C++
apps
DirectX HLSL shader compilation and syntax
highlighting
Packaging compiled HLSL shaders into the .appx
package
Support for other asset types in MSBuild and previewer
Win32               WRL                  WinRT
CoCreateInstance   ComPtr<IObject>   Foo^ foo = ref new Foo()
QueryInterface     foo.As(&bar)      N/A
AddRef / Release   N/A               N/A
N/A                std::vector       Platform::Array<>^
Chapter 1/6


App Initialization
ref class MyApp : public IFrameworkView
{
public:

   MyApp();

   // IFrameworkView Methods
   virtual void Initialize(CoreApplicationView^ applicationView);
   virtual void SetWindow(CoreWindow^ window);
   virtual void Load(String^ entryPoint);
   virtual void Run();
   virtual void Uninitialize();
void MyApp::Run()
{
    auto dispatcher = CoreWindow::GetForCurrentThread()->Dispatcher;

    while (!m_windowClosed)
    {
        dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
        m_renderer->Update();
        m_renderer->Render();
        m_renderer->Present();
    }
}
Chapter 2/6


Handling Window
Events
void MyApp::SetWindow(CoreWindow^ window)
{
    window->SizeChanged +=
      ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(
        this, &MyApp::OnWindowSizeChanged);

    ApplicationView::GetForCurrentView()->ViewStateChanged +=
      ref new TypedEventHandler
        <ApplicationView^, ApplicationViewStateChangedEventArgs^>(
          this, &MyApp::OnViewStateChanged);
}
Resize Handler
void DirectXApp::OnWindowSizeChanged(
    _In_ CoreWindow^ sender,
    _In_ WindowSizeChangedEventArgs^ args
    )
{
      if (m_window->Bounds.Width != m_windowBounds.Width ||
         m_window->Bounds.Height != m_windowBounds.Height)
    {
         m_d2dContext->SetTarget(nullptr);
         m_d2dTargetBitmap = nullptr;
         m_renderTargetView = nullptr;
         m_depthStencilView = nullptr;
         CreateWindowSizeDependentResources();
    }
}
void MyApp::OnWindowActivationChanged(
    CoreWindow^ sender,
    WindowActivatedEventArgs^ args)
{
    auto state = args->WindowActivationState;

    if(state == CoreWindowActivationState::Deactivated)
        OutputDebugString("Focus Lost");

    if(state == CoreWindowActivationState::CodeActivated ||
       state == CoreWindowActivationState::PointerActivated)
        OutputDebugString("Focus Regained");
}
{
    DisplayOrientations::None;               // Enable rotation by OS/Accelerometer
    DisplayOrientations::Landscape;          // Lock rotation by OS/Accelerometer
    DisplayOrientations::LandscapeFlipped;   //     and enable this orientation
    DisplayOrientations::Portrait;
    DisplayOrientations::PortraitFlipped;
}

using namespace Windows::Graphics::Display;

DisplayProperties::AutoRotationPreferences = DisplayOrientations::Landscape
                                           | DisplayOrientations::LandscapeFlipped;
Chapter 3/6


Rendering Graphics
3D Graphics via Direct3D 11
3D Graphics uses the same API as on Desktop/Classic
WinRT API set includes only the latest DirectX 11 syntax
DirectX 11 API supports multiple hardware generations
via FeatureLevels: Feature_Level_9, Feature_Level_10, Feature_Level_11
Direct3D 11 updated for Windows 8
Creating a swap chain
                   CoreWindow                           // app’s core window
                ComPtr ID3D11Device1                    // renderer
                ComPtr IDXGISwapChain1                  // front/back buffers of
RT

// Obtain the final swap chain for this window from the DXGI factory.

                                //   the Direct3D device that will render to it
                                //   IUnknown interface on our core window
                                //   double or triple buffered, stereo, etc.
     nullptr                    //   allow on all displays
                                //   the resulting swap chain object
void myApp::Render()
{
     m_d3dContext->OMSetRenderTargets(    // rebind every frame!
        1,
        m_renderTargetView.GetAddressOf(),
        m_depthStencilView.Get() );

     if (!m_loadingComplete)      // only draw the cube once it's loaded
        return;                   // (this is async)

     m_d3dContext->IASetVertexBuffers(
        0, 1,
        m_vertexBuffer.GetAddressOf(),
        &stride,
        &offset );

   m_d3dContext->IASetIndexBuffer(
       m_indexBuffer.Get(),
       DXGI_FORMAT_R16_UINT, 0 );
m_d3dContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

    m_d3dContext->IASetInputLayout(m_inputLayout.Get());

    m_d3dContext->VSSetConstantBuffers(
        0, 1,
        m_constantBuffer.GetAddressOf() );

    m_d3dContext->VSSetShader( m_vertexShader.Get(),
        nullptr, 0 );

    m_d3dContext->PSSetShader( m_pixelShader.Get(),
        nullptr, 0 );

    m_d3dContext->DrawIndexed( m_indexCount, 0, 0 );
}
Chapter 4/7


Loading and Saving
Process Lifetime Management
 Suspend/Resume




  User               suspending
           Running                Suspended                Terminated
Launches                                      Low Memory
             App                     App                      App
  App                  resuming
using namespace Concurrency;




float f = 1.0f;
task<int>([=]()   // task defined with capturing lambda
{
   return foo(f);
}).then([](int x) // continuation lambda argument is return value of previous
{
   bar(x);
}).then(baz);     // continuation using existing function baz()
void MyApp::OnSuspending(Object^ sender, SuspendingEventArgs^ args)
{
    SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral();

    task<void>([=]()
    {
        auto localState = ApplicationData::Current->LocalSettings->Values;
        auto roamingState = ApplicationData::Current->RoamingSettings->Values;
        localState->Insert(
          "GameTime", PropertyValue::CreateSingle(m_gameTime));
        roamingState->Insert(
          "MaxLevel", PropertyValue::CreateUInt32(m_maxLevelUnlocked));
    }).then([=]()
    {
        deferral->Complete();
    });
}
void MyApp::Load(String^ entryPoint)
{
    LoadMyGameStateAsync().then([=]()
    {
        auto localState = ApplicationData::Current->LocalSettings->Values;
        auto roamingState = ApplicationData::Current->RoamingSettings->Values;
        m_gameTime = safe_cast<IPropertyValue^>
             (localState->Lookup("GameTime"))->GetSingle();
        m_maxLevelUnlocked = safe_cast<IPropertyValue^>
             (roamingState->Lookup("MaxLevel"))->GetUInt32();
    }).then([=]()
    {
        m_loadingComplete = true;
    });
}
task<byte*> LoadSkyAsync()
{
    auto folder = Package::Current->InstalledLocation;
    return task<StorageFile^>(
    folder->GetFileAsync("sky.dds")).then([](StorageFile^ file){
        return FileIO::ReadBufferAsync(file);
    }).then([](IBuffer^ buffer){
        auto fileData = ref new Array<byte>(buffer->Length);
        DataReader::FromBuffer(buffer)->ReadBytes(fileData);
        return fileData->Data;
    });
}
...
LoadSkyAsync().then([=](byte* skyTextureData)
{
    CreateTexture(skyTextureData);
    m_loadingComplete = true;
});
Chapter 5/7


Adding Input
Mouse and Touch Input
win->PointerPressed += ref new TypedEventHandler<CoreWindow^,PointerEventArgs^>
                        (this, &LonLatController::OnPointerPressed);

void LonLatController::OnPointerPressed(
    _In_ CoreWindow^ sender,
    _In_ PointerEventArgs^ args
    )
{
    float2 position = float2(              // position of contact
        args->CurrentPoint->Position.X,
        args->CurrentPoint->Position.Y
        );

    m_lonLatLastPoint = position;          // save for use in controller
    m_lonLatPointerID = args->CurrentPoint->PointerId;
}
// Arrow keys or WASD example
auto upKeyState = window->GetKeyAsyncState(VirtualKey::Up);
auto wKeyState = window->GetAsyncKeyState(VirtualKey::W);

if (upKeyState & CoreVirtualKeyStates::Down ||
    wKeyState & CoreVirtualKeyStates::Down)
{
    m_playerPosition.y += 1.0f;
}
using Windows::Devices::Sensors;

// Get current reading from sensor
OrientationSensorReading^ orientationReading = m_orientationsensor->GetCurrentReading();
SensorQuaternion^ quat = orientationReading->Quaternion;

// Transform quaternion from device orientation space to world space
// Orientation space is Z-up, right-handed coordinate system
// World space is Y-up, left-handed coordinate system
XMVECTOR orientationQuat = XMVectorSet(-quat->X, quat->Z, quat->Y, -quat->W);

// Create a rotation matrix from the quaternion
// This matrix can be used to rotate an object inside the scene to match
// the rotation of the device
XMMATRIX rotXMMatrix = XMMatrixRotationQuaternion(orientationQuat);
Windows 8 supports Xbox360 -compatible controller

Check out new ControllerSketch sample
Demonstrates game controller usage from JavaScript app
if ( m_xinputState.Gamepad.wButtons & XINPUT_GAMEPAD_A )
{
    m_aButtonWasPressed = true;
}
else if ( m_aButtonWasPressed )
{
    m_aButtonWasPressed = false;       // Trigger once, only on button release
    TriggerSoundEffect();
}
if (abs(thumbLeftX) < XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE)
    thumbLeftX = 0;

SHORT thumbLeftY = inputState.Gamepad.sThumbLY;
if (abs(thumbLeftY) < XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE)
    thumbLeftY = 0;

combinedTiltX += (float)thumbLeftX / 32768.0f;
combinedTiltY += (float)thumbLeftY / 32768.0f;
Chapter 6/7


Adding Sound Effects
// Create the XAudio2 engine and mastering voice on the default audio device



// Load all audio data for the sound effect into a single in-memory buffer
                          new


// Create a single source voice for a sound effect



// Trigger sound effect: queue in-memory buffer for playback and start the voice
Chapter 7/7


Creating an Asset
Pipeline
Author-time
   Asset       Build Step   Run-time Asset   Packager

 shader.hlsl                  shader.cso

                                                        Package
texture.bmp                   texture.dds

                                                        myApp
 mesh.obj                     mesh.vbo                  .appx



 music.wav                    music.wma
Run-time        Loader     Bindable
          Installer    Asset        Component    API object

                      shader.cso                  Shader

Package
                      texture.dds                 Texture

 myApp
 .appx
                      mesh.vbo                  VertexBuffer



                      music.wma                   Stream
Pro Dev Hints
Find commands in the IDE via the search textport
Set up a multi-monitor dev PC with a touch
monitor as the primary
To work with the samples, set a breakpoint inside
the DX::          macro in DirectSample.h line 18
Time to Act
Biggest opportunity. Ever.

Windows 8 Consumer Preview is now available.

Check out the store.

Go build great games.

http://dev.windows.com
Q&A
Shape12 6

More Related Content

Viewers also liked

Valgen Case Study - Midsized Apparel Manufacturer
Valgen Case Study - Midsized Apparel ManufacturerValgen Case Study - Midsized Apparel Manufacturer
Valgen Case Study - Midsized Apparel ManufacturerValgenMobility
 
Valgen Case Study - Auto Manufacturing OEM
Valgen Case Study - Auto Manufacturing OEMValgen Case Study - Auto Manufacturing OEM
Valgen Case Study - Auto Manufacturing OEMValgenMobility
 
Využití audiovizuálních prvků v činnosti Turistického Oddílu
Využití audiovizuálních prvků v činnosti Turistického OddíluVyužití audiovizuálních prvků v činnosti Turistického Oddílu
Využití audiovizuálních prvků v činnosti Turistického OddíluJakub Weiner
 
Valgen Case Study - Bath Fitting Manufacturer
Valgen Case Study - Bath Fitting ManufacturerValgen Case Study - Bath Fitting Manufacturer
Valgen Case Study - Bath Fitting ManufacturerValgenMobility
 
Powerpoint for data communication
Powerpoint for data communication Powerpoint for data communication
Powerpoint for data communication samanthaanderson21
 
Loaf of bread - Team - 25727
Loaf of bread - Team - 25727Loaf of bread - Team - 25727
Loaf of bread - Team - 25727cheerfultornado
 
Βουλητικές προτάσεις_Μ. Σπανού
Βουλητικές  προτάσεις_Μ. ΣπανούΒουλητικές  προτάσεις_Μ. Σπανού
Βουλητικές προτάσεις_Μ. ΣπανούMaria Spanou
 
Βουλητικές προτάσεις_Μ. Σπανού
Βουλητικές  προτάσεις_Μ. ΣπανούΒουλητικές  προτάσεις_Μ. Σπανού
Βουλητικές προτάσεις_Μ. ΣπανούMaria Spanou
 
Ειδικές Προτάσεις_Μ. Σπανού
Ειδικές Προτάσεις_Μ. ΣπανούΕιδικές Προτάσεις_Μ. Σπανού
Ειδικές Προτάσεις_Μ. ΣπανούMaria Spanou
 
Blogalicious 5: 10 Steps Intensive: Identify your ideal reader or customer
Blogalicious 5: 10 Steps Intensive: Identify your ideal reader or customerBlogalicious 5: 10 Steps Intensive: Identify your ideal reader or customer
Blogalicious 5: 10 Steps Intensive: Identify your ideal reader or customerYoly Mason
 
Cost Accounting for an imaginary dairy company
Cost Accounting for an imaginary dairy companyCost Accounting for an imaginary dairy company
Cost Accounting for an imaginary dairy companyvaravindkulasekhar
 
Properties of 2D shapes
Properties of 2D shapesProperties of 2D shapes
Properties of 2D shapeselliehh
 
Hand presentation, M Martinez 2012
Hand presentation, M Martinez 2012Hand presentation, M Martinez 2012
Hand presentation, M Martinez 2012Elvira Chavaria
 
Group decision making
Group decision makingGroup decision making
Group decision makingluischimal
 

Viewers also liked (20)

Assignment OEP
Assignment OEPAssignment OEP
Assignment OEP
 
Valgen Case Study - Midsized Apparel Manufacturer
Valgen Case Study - Midsized Apparel ManufacturerValgen Case Study - Midsized Apparel Manufacturer
Valgen Case Study - Midsized Apparel Manufacturer
 
Your resume
Your resumeYour resume
Your resume
 
Bungalow Beach Club
Bungalow Beach Club Bungalow Beach Club
Bungalow Beach Club
 
Valgen Case Study - Auto Manufacturing OEM
Valgen Case Study - Auto Manufacturing OEMValgen Case Study - Auto Manufacturing OEM
Valgen Case Study - Auto Manufacturing OEM
 
Využití audiovizuálních prvků v činnosti Turistického Oddílu
Využití audiovizuálních prvků v činnosti Turistického OddíluVyužití audiovizuálních prvků v činnosti Turistického Oddílu
Využití audiovizuálních prvků v činnosti Turistického Oddílu
 
Valgen Case Study - Bath Fitting Manufacturer
Valgen Case Study - Bath Fitting ManufacturerValgen Case Study - Bath Fitting Manufacturer
Valgen Case Study - Bath Fitting Manufacturer
 
Powerpoint for data communication
Powerpoint for data communication Powerpoint for data communication
Powerpoint for data communication
 
Audioconferencia
AudioconferenciaAudioconferencia
Audioconferencia
 
Loaf of bread - Team - 25727
Loaf of bread - Team - 25727Loaf of bread - Team - 25727
Loaf of bread - Team - 25727
 
Βουλητικές προτάσεις_Μ. Σπανού
Βουλητικές  προτάσεις_Μ. ΣπανούΒουλητικές  προτάσεις_Μ. Σπανού
Βουλητικές προτάσεις_Μ. Σπανού
 
Βουλητικές προτάσεις_Μ. Σπανού
Βουλητικές  προτάσεις_Μ. ΣπανούΒουλητικές  προτάσεις_Μ. Σπανού
Βουλητικές προτάσεις_Μ. Σπανού
 
Ειδικές Προτάσεις_Μ. Σπανού
Ειδικές Προτάσεις_Μ. ΣπανούΕιδικές Προτάσεις_Μ. Σπανού
Ειδικές Προτάσεις_Μ. Σπανού
 
Equity research final
Equity research finalEquity research final
Equity research final
 
Blogalicious 5: 10 Steps Intensive: Identify your ideal reader or customer
Blogalicious 5: 10 Steps Intensive: Identify your ideal reader or customerBlogalicious 5: 10 Steps Intensive: Identify your ideal reader or customer
Blogalicious 5: 10 Steps Intensive: Identify your ideal reader or customer
 
Cost Accounting for an imaginary dairy company
Cost Accounting for an imaginary dairy companyCost Accounting for an imaginary dairy company
Cost Accounting for an imaginary dairy company
 
Properties of 2D shapes
Properties of 2D shapesProperties of 2D shapes
Properties of 2D shapes
 
Hand presentation, M Martinez 2012
Hand presentation, M Martinez 2012Hand presentation, M Martinez 2012
Hand presentation, M Martinez 2012
 
Curriculum development.rpc
Curriculum development.rpcCurriculum development.rpc
Curriculum development.rpc
 
Group decision making
Group decision makingGroup decision making
Group decision making
 

Similar to Shape12 6

Criando jogos para o windows 8
Criando jogos para o windows 8Criando jogos para o windows 8
Criando jogos para o windows 8José Farias
 
Windows 8 and windows phone 8 developer story anders bratland
Windows 8 and windows phone 8 developer story anders bratlandWindows 8 and windows phone 8 developer story anders bratland
Windows 8 and windows phone 8 developer story anders bratlandAnastasia Kladova
 
Introduction to Windows 8 Development
Introduction to Windows 8 Development
Introduction to Windows 8 Development
Introduction to Windows 8 Development Naresh Kumar
 
Windows 10 UWP Development Overview
Windows 10 UWP Development OverviewWindows 10 UWP Development Overview
Windows 10 UWP Development OverviewDevGAMM Conference
 
Introduction to Skia by Ryan Chou @20141008
Introduction to Skia by Ryan Chou @20141008Introduction to Skia by Ryan Chou @20141008
Introduction to Skia by Ryan Chou @20141008Ryan Chou
 
Forge - DevCon 2016: Visual Reporting with Connected Design Data
Forge - DevCon 2016: Visual Reporting with Connected Design DataForge - DevCon 2016: Visual Reporting with Connected Design Data
Forge - DevCon 2016: Visual Reporting with Connected Design DataAutodesk
 
Windows Phone 8.1 アプリ開発徹底解説
Windows Phone 8.1 アプリ開発徹底解説Windows Phone 8.1 アプリ開発徹底解説
Windows Phone 8.1 アプリ開発徹底解説shinobu takahashi
 
android-tutorial-for-beginner
android-tutorial-for-beginnerandroid-tutorial-for-beginner
android-tutorial-for-beginnerAjailal Parackal
 
Windows8 metro presentationupdated
Windows8 metro presentationupdatedWindows8 metro presentationupdated
Windows8 metro presentationupdatedDhananjay Kumar
 
426 lecture 4: AR Developer Tools
426 lecture 4: AR Developer Tools426 lecture 4: AR Developer Tools
426 lecture 4: AR Developer ToolsMark Billinghurst
 
Minko stage3d 20130222
Minko stage3d 20130222Minko stage3d 20130222
Minko stage3d 20130222Minko3D
 
Windows 8 App Developer Day
Windows 8 App Developer DayWindows 8 App Developer Day
Windows 8 App Developer DayPatric Boscolo
 
Porting and Maintaining your C++ Game on Android without losing your mind
Porting and Maintaining your C++ Game on Android without losing your mindPorting and Maintaining your C++ Game on Android without losing your mind
Porting and Maintaining your C++ Game on Android without losing your mindBeMyApp
 
Whidbey old
Whidbey old Whidbey old
Whidbey old grenaud
 

Similar to Shape12 6 (20)

Criando jogos para o windows 8
Criando jogos para o windows 8Criando jogos para o windows 8
Criando jogos para o windows 8
 
Windows 8 and windows phone 8 developer story anders bratland
Windows 8 and windows phone 8 developer story anders bratlandWindows 8 and windows phone 8 developer story anders bratland
Windows 8 and windows phone 8 developer story anders bratland
 
Introduction to Windows 8 Development
Introduction to Windows 8 Development
Introduction to Windows 8 Development
Introduction to Windows 8 Development
 
Win8 ru
Win8 ruWin8 ru
Win8 ru
 
Eco system apps
Eco system appsEco system apps
Eco system apps
 
Windows 8
Windows 8Windows 8
Windows 8
 
Windows 10 UWP Development Overview
Windows 10 UWP Development OverviewWindows 10 UWP Development Overview
Windows 10 UWP Development Overview
 
Introduction to Skia by Ryan Chou @20141008
Introduction to Skia by Ryan Chou @20141008Introduction to Skia by Ryan Chou @20141008
Introduction to Skia by Ryan Chou @20141008
 
Introducing Windows Runtime in Windows 8
Introducing Windows Runtime in Windows 8Introducing Windows Runtime in Windows 8
Introducing Windows Runtime in Windows 8
 
Forge - DevCon 2016: Visual Reporting with Connected Design Data
Forge - DevCon 2016: Visual Reporting with Connected Design DataForge - DevCon 2016: Visual Reporting with Connected Design Data
Forge - DevCon 2016: Visual Reporting with Connected Design Data
 
Windows Phone 8.1 アプリ開発徹底解説
Windows Phone 8.1 アプリ開発徹底解説Windows Phone 8.1 アプリ開発徹底解説
Windows Phone 8.1 アプリ開発徹底解説
 
Csharp dot net
Csharp dot netCsharp dot net
Csharp dot net
 
android-tutorial-for-beginner
android-tutorial-for-beginnerandroid-tutorial-for-beginner
android-tutorial-for-beginner
 
Windows8 metro presentationupdated
Windows8 metro presentationupdatedWindows8 metro presentationupdated
Windows8 metro presentationupdated
 
426 lecture 4: AR Developer Tools
426 lecture 4: AR Developer Tools426 lecture 4: AR Developer Tools
426 lecture 4: AR Developer Tools
 
Minko stage3d 20130222
Minko stage3d 20130222Minko stage3d 20130222
Minko stage3d 20130222
 
Windows 8 developer preview
Windows 8 developer previewWindows 8 developer preview
Windows 8 developer preview
 
Windows 8 App Developer Day
Windows 8 App Developer DayWindows 8 App Developer Day
Windows 8 App Developer Day
 
Porting and Maintaining your C++ Game on Android without losing your mind
Porting and Maintaining your C++ Game on Android without losing your mindPorting and Maintaining your C++ Game on Android without losing your mind
Porting and Maintaining your C++ Game on Android without losing your mind
 
Whidbey old
Whidbey old Whidbey old
Whidbey old
 

Shape12 6

  • 1. How to Create Your First Windows 8 Metro-style Game Chas. Boyd Principal Program Manager Microsoft Corporation
  • 2. Three Presentations Today Step by Step through Game Development 1) How to set up the game 2) How to code it <- You are here 3) How to optimize it
  • 3. Agenda Quick summary of the platform Step through the process of development from a programmer’s perspective: App Initialization Opening a Window Rendering Graphics Loading and Saving Adding Input Controls Adding Sound Effects Adding an Art Pipeline This talk’s sample code is in C++
  • 5. Metro style apps Desktop apps View DX XAML HTML / CSS C Controller C C# Model JavaScript HTML C # C++ VB JavaScript C++ V WinRT APIs B System Services Communication Graphics Devices & Data & Media & Printing .NE Application Model Internet Win32 T Explorer SL Kernel Windows Kernel Services
  • 6. Your Killer Game Movies & Cut Connected Graphics Game Input Audio Local Services Tools Scenes Services DirectX Pointer Windows Visual Direct3D WASAPI PLM Video Point Live Studio Media Windows Asset Direct2D Sensor API XAudio2 AppData Foundation Store Viewers Asset HTML XInput Contracts Xbox LIVE Processors XAML
  • 7. Windows Runtime All WinRT APIs are native WinRT APIs feel natural in C++, C#/VB, and JavaScript Reuse of portable C++ code just works WinRT APIs provide rich access to devices, OS, and services HTML5/CSS/JavaScript and XAML are great for Metro style apps Providing a rich set of controls Native DirectX is great for Metro style apps
  • 8. Updated C++ language support File->New Project templates for native DirectX C++ apps DirectX HLSL shader compilation and syntax highlighting Packaging compiled HLSL shaders into the .appx package Support for other asset types in MSBuild and previewer
  • 9. Win32 WRL WinRT CoCreateInstance ComPtr<IObject> Foo^ foo = ref new Foo() QueryInterface foo.As(&bar) N/A AddRef / Release N/A N/A N/A std::vector Platform::Array<>^
  • 11. ref class MyApp : public IFrameworkView { public: MyApp(); // IFrameworkView Methods virtual void Initialize(CoreApplicationView^ applicationView); virtual void SetWindow(CoreWindow^ window); virtual void Load(String^ entryPoint); virtual void Run(); virtual void Uninitialize();
  • 12. void MyApp::Run() { auto dispatcher = CoreWindow::GetForCurrentThread()->Dispatcher; while (!m_windowClosed) { dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent); m_renderer->Update(); m_renderer->Render(); m_renderer->Present(); } }
  • 13.
  • 15.
  • 16. void MyApp::SetWindow(CoreWindow^ window) { window->SizeChanged += ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>( this, &MyApp::OnWindowSizeChanged); ApplicationView::GetForCurrentView()->ViewStateChanged += ref new TypedEventHandler <ApplicationView^, ApplicationViewStateChangedEventArgs^>( this, &MyApp::OnViewStateChanged); }
  • 17. Resize Handler void DirectXApp::OnWindowSizeChanged( _In_ CoreWindow^ sender, _In_ WindowSizeChangedEventArgs^ args ) { if (m_window->Bounds.Width != m_windowBounds.Width || m_window->Bounds.Height != m_windowBounds.Height) { m_d2dContext->SetTarget(nullptr); m_d2dTargetBitmap = nullptr; m_renderTargetView = nullptr; m_depthStencilView = nullptr; CreateWindowSizeDependentResources(); } }
  • 18. void MyApp::OnWindowActivationChanged( CoreWindow^ sender, WindowActivatedEventArgs^ args) { auto state = args->WindowActivationState; if(state == CoreWindowActivationState::Deactivated) OutputDebugString("Focus Lost"); if(state == CoreWindowActivationState::CodeActivated || state == CoreWindowActivationState::PointerActivated) OutputDebugString("Focus Regained"); }
  • 19. { DisplayOrientations::None; // Enable rotation by OS/Accelerometer DisplayOrientations::Landscape; // Lock rotation by OS/Accelerometer DisplayOrientations::LandscapeFlipped; // and enable this orientation DisplayOrientations::Portrait; DisplayOrientations::PortraitFlipped; } using namespace Windows::Graphics::Display; DisplayProperties::AutoRotationPreferences = DisplayOrientations::Landscape | DisplayOrientations::LandscapeFlipped;
  • 21. 3D Graphics via Direct3D 11 3D Graphics uses the same API as on Desktop/Classic WinRT API set includes only the latest DirectX 11 syntax DirectX 11 API supports multiple hardware generations via FeatureLevels: Feature_Level_9, Feature_Level_10, Feature_Level_11 Direct3D 11 updated for Windows 8
  • 22. Creating a swap chain CoreWindow // app’s core window ComPtr ID3D11Device1 // renderer ComPtr IDXGISwapChain1 // front/back buffers of RT // Obtain the final swap chain for this window from the DXGI factory. // the Direct3D device that will render to it // IUnknown interface on our core window // double or triple buffered, stereo, etc. nullptr // allow on all displays // the resulting swap chain object
  • 23. void myApp::Render() { m_d3dContext->OMSetRenderTargets( // rebind every frame! 1, m_renderTargetView.GetAddressOf(), m_depthStencilView.Get() ); if (!m_loadingComplete) // only draw the cube once it's loaded return; // (this is async) m_d3dContext->IASetVertexBuffers( 0, 1, m_vertexBuffer.GetAddressOf(), &stride, &offset ); m_d3dContext->IASetIndexBuffer( m_indexBuffer.Get(), DXGI_FORMAT_R16_UINT, 0 );
  • 24. m_d3dContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); m_d3dContext->IASetInputLayout(m_inputLayout.Get()); m_d3dContext->VSSetConstantBuffers( 0, 1, m_constantBuffer.GetAddressOf() ); m_d3dContext->VSSetShader( m_vertexShader.Get(), nullptr, 0 ); m_d3dContext->PSSetShader( m_pixelShader.Get(), nullptr, 0 ); m_d3dContext->DrawIndexed( m_indexCount, 0, 0 ); }
  • 26. Process Lifetime Management Suspend/Resume User suspending Running Suspended Terminated Launches Low Memory App App App App resuming
  • 27. using namespace Concurrency; float f = 1.0f; task<int>([=]() // task defined with capturing lambda { return foo(f); }).then([](int x) // continuation lambda argument is return value of previous { bar(x); }).then(baz); // continuation using existing function baz()
  • 28. void MyApp::OnSuspending(Object^ sender, SuspendingEventArgs^ args) { SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral(); task<void>([=]() { auto localState = ApplicationData::Current->LocalSettings->Values; auto roamingState = ApplicationData::Current->RoamingSettings->Values; localState->Insert( "GameTime", PropertyValue::CreateSingle(m_gameTime)); roamingState->Insert( "MaxLevel", PropertyValue::CreateUInt32(m_maxLevelUnlocked)); }).then([=]() { deferral->Complete(); }); }
  • 29. void MyApp::Load(String^ entryPoint) { LoadMyGameStateAsync().then([=]() { auto localState = ApplicationData::Current->LocalSettings->Values; auto roamingState = ApplicationData::Current->RoamingSettings->Values; m_gameTime = safe_cast<IPropertyValue^> (localState->Lookup("GameTime"))->GetSingle(); m_maxLevelUnlocked = safe_cast<IPropertyValue^> (roamingState->Lookup("MaxLevel"))->GetUInt32(); }).then([=]() { m_loadingComplete = true; }); }
  • 30. task<byte*> LoadSkyAsync() { auto folder = Package::Current->InstalledLocation; return task<StorageFile^>( folder->GetFileAsync("sky.dds")).then([](StorageFile^ file){ return FileIO::ReadBufferAsync(file); }).then([](IBuffer^ buffer){ auto fileData = ref new Array<byte>(buffer->Length); DataReader::FromBuffer(buffer)->ReadBytes(fileData); return fileData->Data; }); } ... LoadSkyAsync().then([=](byte* skyTextureData) { CreateTexture(skyTextureData); m_loadingComplete = true; });
  • 32. Mouse and Touch Input win->PointerPressed += ref new TypedEventHandler<CoreWindow^,PointerEventArgs^> (this, &LonLatController::OnPointerPressed); void LonLatController::OnPointerPressed( _In_ CoreWindow^ sender, _In_ PointerEventArgs^ args ) { float2 position = float2( // position of contact args->CurrentPoint->Position.X, args->CurrentPoint->Position.Y ); m_lonLatLastPoint = position; // save for use in controller m_lonLatPointerID = args->CurrentPoint->PointerId; }
  • 33. // Arrow keys or WASD example auto upKeyState = window->GetKeyAsyncState(VirtualKey::Up); auto wKeyState = window->GetAsyncKeyState(VirtualKey::W); if (upKeyState & CoreVirtualKeyStates::Down || wKeyState & CoreVirtualKeyStates::Down) { m_playerPosition.y += 1.0f; }
  • 34.
  • 35. using Windows::Devices::Sensors; // Get current reading from sensor OrientationSensorReading^ orientationReading = m_orientationsensor->GetCurrentReading(); SensorQuaternion^ quat = orientationReading->Quaternion; // Transform quaternion from device orientation space to world space // Orientation space is Z-up, right-handed coordinate system // World space is Y-up, left-handed coordinate system XMVECTOR orientationQuat = XMVectorSet(-quat->X, quat->Z, quat->Y, -quat->W); // Create a rotation matrix from the quaternion // This matrix can be used to rotate an object inside the scene to match // the rotation of the device XMMATRIX rotXMMatrix = XMMatrixRotationQuaternion(orientationQuat);
  • 36. Windows 8 supports Xbox360 -compatible controller Check out new ControllerSketch sample Demonstrates game controller usage from JavaScript app
  • 37. if ( m_xinputState.Gamepad.wButtons & XINPUT_GAMEPAD_A ) { m_aButtonWasPressed = true; } else if ( m_aButtonWasPressed ) { m_aButtonWasPressed = false; // Trigger once, only on button release TriggerSoundEffect(); }
  • 38. if (abs(thumbLeftX) < XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE) thumbLeftX = 0; SHORT thumbLeftY = inputState.Gamepad.sThumbLY; if (abs(thumbLeftY) < XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE) thumbLeftY = 0; combinedTiltX += (float)thumbLeftX / 32768.0f; combinedTiltY += (float)thumbLeftY / 32768.0f;
  • 40. // Create the XAudio2 engine and mastering voice on the default audio device // Load all audio data for the sound effect into a single in-memory buffer new // Create a single source voice for a sound effect // Trigger sound effect: queue in-memory buffer for playback and start the voice
  • 41. Chapter 7/7 Creating an Asset Pipeline
  • 42. Author-time Asset Build Step Run-time Asset Packager shader.hlsl shader.cso Package texture.bmp texture.dds myApp mesh.obj mesh.vbo .appx music.wav music.wma
  • 43. Run-time Loader Bindable Installer Asset Component API object shader.cso Shader Package texture.dds Texture myApp .appx mesh.vbo VertexBuffer music.wma Stream
  • 44. Pro Dev Hints Find commands in the IDE via the search textport Set up a multi-monitor dev PC with a touch monitor as the primary To work with the samples, set a breakpoint inside the DX:: macro in DirectSample.h line 18
  • 45. Time to Act Biggest opportunity. Ever. Windows 8 Consumer Preview is now available. Check out the store. Go build great games. http://dev.windows.com
  • 46. Q&A