> ## Documentation Index
> Fetch the complete documentation index at: https://devdocs.xbox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# XBOX One 向け Microsoft Game Development Kit 移植ガイド

> 既存の XBOX One ゲーム タイトルまたはエンジンを GDK に移植するための概要。

# XBOX One 向け Microsoft Game Development Kit 移植ガイド

このトピックでは、既存のコードベースを XBOX 向けの Microsoft Game Development Kit (GDK) プラットフォームに移植するテクニックの概要を説明します。既に XBOX One 開発を行っている開発者にとって、ほとんどのサブシステムは異なる API 設計を使っていても馴染みがあるでしょう。Direct3D グラフィックスなどの一部の領域はほとんど変わっていません。このトピックでは、全体的な移植プロセスの俯瞰、特定領域へのリンク、および一般的な落とし穴を回避するためのヒントとコツをいくつか提供します。

このガイドに関するフィードバックはありますか? [Microsoft Game Development Kit (GDK) 開発者フォーラム](https://aka.ms/gdkforum) でお知らせください。

既存タイトルの移植ではなく Microsoft Game Development Kit (GDK) プラットフォームで新しいタイトルを開発する場合は、GDK での新しいタイトルの開発を参照してください。

## Microsoft Game Development Kit (GDK) について

ゲーム開発パートナーである皆様は、Microsoft のゲーミング チームに対して、当社が上手に行っていることと改善する必要があることについて貴重なフィードバックを提供してくださいました。Microsoft Game Development Kit (GDK) の主要目標は、皆様のフィードバックに直接対応し、次のことを実現できるようにすることです。

* 今日と同じようにゲームの開発を継続する
* 現在のコンソールと PC、および将来のコンソールと XBOX Game Streaming のすべての Microsoft ゲーミング取り組みおよびプログラムで、可能な限り多くのコードを容易に共有する
* 高速で信頼性があり開発者中心の環境を提供する当社の開発ツールとプラットフォームを信頼する
* 新しいマルチ プラットフォームのサービスと体験を可能な限り迅速かつ簡単に活用する

Microsoft は、皆様が既に使用しているプログラミング パラダイムを使って、皆様が望むあらゆるプラットフォームでゲームを開発する支援をしたいと考えています。Microsoft は、皆様のゲームを今日存在するすべてのゲーミング プラットフォーム、そして現在取り組んでいる将来のゲーマーを喜ばせるすべてのプラットフォームに提供する支援をしたいと考えています。

Microsoft Game Development Kit (GDK) の詳細については、What is the Microsoft Game Development Kit? および Microsoft Game Development Kit (GDK) の入門を参照してください。

## 目次

* [移植プロジェクトの計画](#portfrom)
* [開発環境](#devenv)
* [アプリケーションの起動](#appstartup)
* [アプリケーションの初期化](#appinit)
* [Windows メッセージング ループ](#winmsgloop)
* [Direct3D デバイスの作成](#d3ddevicecreate)
* [プレゼンテーション](#presentation)
* [Process lifetime management (PLM)](#plm)
* [メモリ管理](#memmgmt)
* [プログラミング モデル](#appmodel)
* [HLSL シェーダー](#hlsl)
* [ユーザー管理](#user)
* [ネットワークと XBOX サービスの統合](#live)
* [次のステップ](#nextsteps)
* [ヒントとコツ](#tips)
* [バイナリ互換性とコンポーネントの再利用](#bincompat)
* [コーディング スタイルとベスト プラクティス](#codingstyle)
* [関連項目](#seealso)

<Note>
  この移植ガイドでは、Gaming.Xbox.XboxOne.x64 または Gaming.Xbox.Scarlett.x64 プラットフォームをターゲットにしていることを想定します。Microsoft Game Development Kit (GDK) には Gaming.Desktop.x64 プラットフォームも含まれます。これは標準の x64 Win32 プラットフォームの派生で、本移植ガイドでは扱いません。

  Gaming.Desktop.x64 の主要な価値は、PC をターゲットとする場合に、ビルド設定、Visual Studio 統合、loose レイアウトの動作などの点で Gaming.Xbox.\*.x64 と類似の体験を提供することです。代わりに、「stock」x64 プラットフォームを使用し、PC 向けにすべての設定/パッケージングを直接実装することもできます。
</Note>

<a id="portfrom" />

## 移植プロジェクトの計画

When you port an existing codebase to the Microsoft Game Development Kit (GDK), you typically start from either an existing XBOX One Software Development Kit project or a classic Win32 desktop application. For many developers with an existing XBOX One title, they will find their `Durango` codebase is a better place to start as long as the use of Windows Runtime APIs is relatively isolated. Classic Win32 desktop codebases are much closer than the Microsoft Game Development Kit (GDK) programming model, but often assume desktop-centric UI and control schemes that have to be modified for the console. Classic Win32 desktop codebases also tend to have a lot of desktop-centric integration, particularly when they're being used as part of the game's editing tool suite that utilizes API sets not supported for the Microsoft Game Development Kit (GDK) on Xbox. There are pros and cons to starting with each. In some cases, you may find it easier to pull from both types for different parts of your codebase.

### XBOX One Software Development Kit からの移植

If your codebase already supports XBOX One through the XBOX One Software Development Kit (also known as the `Durango` platform), you've already done most of the work of modernizing your application's API usage. The code should also be well-optimized for the specific constraints of the console, and likely makes significant use of XBOX One-specific extensions as follows.

* DirectX 12.X is required. If you are already using DirectX 12.X for your XBOX One title, no changes should be needed beyond the presentation API for your Direct3D usage.

> If you're using DirectX 11.X now, upgrade to DirectX 12.X first. This may be easier to do with your existing XBOX One Software Development Kit build before you move to the Microsoft Game Development Kit (GDK). For details, see these topics: [Porting from Direct3D 11 to Direct3D 12](https://learn.microsoft.com/windows/desktop/direct3d12/porting-from-direct3d-11-to-direct3d-12) and Introduction to Direct3D 12 on XBOX One Xfest talk [(XBOX Developer Downloads->Conference Material->Xfest 2015 GPU Track Videos)](https://aka.ms/gdkdl), and Porting from Direct3D 11 to Direct3D 12 Xfest talk [(XBOX Developer Downloads->Conference Material->Xfest 2015 GPU Track Videos)](https://aka.ms/gdkdl).

* Instead of using a DXGI swap chain, your presentation logic must use the PresentX API.
* Some significant changes have been made to the memory subsystem for the Microsoft Game Development Kit (GDK) GDK Game OS. Revisit your memory manager implementation.
* For controller input, use the new GameInput API rather than `Windows.Xbox.Input`.
* Because Windows Runtime APIs are no longer used for most scenarios, replace your existing C++/CX or C++/WinRT code with the new Win32-style or DirectX-style COM APIs.
  | Area | Microsoft Game Development Kit (GDK) |
  | - | - |
  | Connected Storage | New flat C API |
  | Networking | [WinSock2](https://learn.microsoft.com/windows/desktop/WinSock/) <br /> [WinHTTP](https://learn.microsoft.com/windows/desktop/WinHttp/about-winhttp) |
  | Packaging and streaming installation | New flat C API |
  | Standard UI (title-callable UI (TCUI)) | New flat C API |
  | Store | New flat C API |
  | User management | New flat C API |
  | XBOX services API (XSAPI) | New flat C API; see Introduction to the XBOX services C APIs and XSAPI reference. |
* Core Audio functionality is unchanged. However, some API changes may be required as outlined in the audio API comparison. XAudio2 with XMA extensions, WASAPI, and `ISpatialAudioClient` are supported.
* When building in Visual Studio, add the `Gaming.Xbox.XboxOne.x64` and/or `Gaming.Xbox.Scarlett.x64` platform configurations in place of your `Durango` platform configurations and upgrade to Visual Studio 2019 or Visual Studio 2022.

<Note>
  To assist in adding new platform configurations we have produced a sample called [*SolutionUpdater*](https://aka.ms/xgdsamples). This sample tool takes an existing Visual Studio Solution file and automatically creates the new platform configurations for all associated Project files that are referenced by the Solution, greatly speeding up the process and reducing the possibility for manual errors. For further information please review the document included with the sample.
</Note>

> If your codebase supports the Universal Windows Platform (UWP) app model, you have a similar porting path as from the XBOX One Software Development Kit.

### Porting from the classic Win32 desktop

If your codebase supports only the classic Win32 desktop, the porting process could be quite extensive, depending on how recent the codebase is with respect to deprecated APIs and other features. Keep in mind that classic Win32 desktop codebases can have a very large span of APIs that date all the way back to the Windows 9x/ME-era. This list isn't comprehensive for all the potential issues you might encounter. When targeting XBOX, you'll also have the usual considerations for porting from PC to console: UI, input models, fixed-resolution display, constrained memory, and so on. For more information, see [Coming to XBOX from PC - What You Need to Know](https://aka.ms/comingtoxbox).

* x64 native is required. For more information, see [64-bit programming for Game Developers](https://learn.microsoft.com/windows/desktop/DxTechArts/sixty-four-bit-programming-for-game-developers).
* DirectX 12.X is required. DirectX 11, Direct3D 10, Direct3D 9 or earlier can't be used. In addition, OpenGL and Vulkan are not supported. For details, see the porting guides for [DirectX11](https://learn.microsoft.com/windows/desktop/direct3d11/d3d11-programming-guide-migrating) and [DirectX12](https://learn.microsoft.com/windows/desktop/direct3d12/porting-from-direct3d-11-to-direct3d-12).
* Legacy DirectX SDK components D3DX9, D3DX10, D3DX11, and XACT can't be used. For more information, see [Microsoft Docs](https://learn.microsoft.com/windows/desktop/directx-sdk--august-2009-), [Where is the DirectX SDK (2021 Edition)?](https://aka.ms/dxsdk), [Living without D3DX](https://aka.ms/Kfsdiu), and [The Zombie DirectX SDK](https://aka.ms/AA4gfea).
* `WINAPI_FAMILY_GAMES` is a subset of the full Win32 API family. Restrict yourself to those APIs.
* AppX packaging is required. Update your process for packaging and deployment.
* For controller input, use the new GameInput API rather than `Windows.Gaming.Input` or DirectInput.
* For Audio, use XAudio2, WASAPI, ISpatialAudioClient, or compatible audio middleware.
* Remove instances of registry usage.
* Handling of the `WndProc` messages is to be reduced. Many of the messages, particularly those that deal with windows' positioning, sizing, and shell integration, don't apply to the Microsoft Game Development Kit (GDK) on Xbox.
* If you build with Visual Studio, upgrade your code to work with Visual Studio 2019 or Visual Studio 2022. Otherwise, ensure your build uses the new preprocessor defines and links with libraries in `GXDK\gameKit\lib\amd64`, such as the `xgameplatform.lib` umbrella library.
* For COM components, only the multithreaded apartment (MTA) threading model is supported. Note that `COINITBASE_MULTITHREADED` is typical for a Direct3D application.
* Only a single window instance is supported. Multiple concurrent window instances or dialog boxes aren't supported.

<a id="devenv" />

## 開発環境

Visual Studio 2019 (16.11 update) or Visual Studio 2022 is the development environment supported for the Microsoft Game Development Kit (GDK).

Install the following:

* Workload: Game development with C++ for the core tool set
* Workload: UWP development for the packaging tools.
* Workload (optional): desktop development with C++ PC-side tools and samples.

> XBOX One Software Development Kit development with Visual Studio 2017 also required the optional component *Windows 8.1 SDK and UCRT SDK*. This component is not required for the Microsoft Game Development Kit (GDK).

If you're still using Visual Studio 2015 or earlier, the first step for your porting effort is to upgrade to Visual Studio 2019 or later.

### Visual Studio platform

The Microsoft Game Development Kit (GDK) integrates with Visual Studio to provide the `Gaming.Xbox.XboxOne.x64` and `Gaming.Xbox.Scarlett.x64` platforms for targeting Microsoft GDK Game OS on Xbox. This replaces the XBOX One Software Development Kit `Durango` platform.

### Custom build solutions

For building code outside of Visual Studio, the environment helpers for locations have been changed.

XBOX One Software Development Kit:

```text theme={null}
DurangoXDK=C:\Program Files (x86)\Microsoft Durango XDK\
XboxOneXDKLatest=C:\Program Files (x86)\Microsoft Durango XDK\170614\
XboxOneExtensionSDKLatest=C:\Program Files (x86)\Microsoft SDKs\Durango.170614\v8.0\
```

Microsoft Game Development Kit (GDK):

```text theme={null}
GameDK=C:\Program Files (x86)\Microsoft GDK\
GameDKLatest=C:\Program Files (x86)\Microsoft GDK\build_number\
```

<Note>
  In the example path above, *build\_number* represents the build installed on your system (e.g. 190700).
</Note>

There are several locations in the Microsoft Game Development Kit (GDK) that will need to be referenced by custom build systems. `%GameDKLatest%\GXDK\gameKit` contains all the headers and libs for console-specific extensions, and the main platform umbrella lib for linking a Microsoft Game Development Kit (GDK) binary. `%GameDKLatest%\GRDK\gameKit` similarly contains the headers and libs for all functionality that isn't specific to console development. The Microsoft Game Development Kit (GDK) requires the Windows 10 SDK (10.0.19041.0) or later to be installed as a dependency. Some additional headers/libs are available in `%GameDKLatest%\GXDK\toolKit` for PC-side console tools.

> As of the October 2023 release, the Windows 11 SDK (10.0.22000.0) is the minimum supported version.

There are also a number of options and defines you should use. See Visual C++ compiler and linker switch recommendations for all the details, as well as the [*CMakeExample*](https://github.com/microsoft/Xbox-GDK-Samples/tree/main/Samples/Tools/CMakeExample) sample.

#### Compiler (cl.exe)

* `/D_GAMING_XBOX` replaces both `/D_XBOX_ONE /D_TITLE` and `/D_DURANGO`.
* `/D_GAMING_XBOX_XBOXONE` is defined only for the `Gaming.Xbox.XboxOne.x64` platform.
* `/D_GAMING_XBOX_SCARLETT` is defined only for the `Gaming.Xbox.Scarlett.x64` platform.
* `/DWINAPI_FAMILY=WINAPI_FAMILY_GAMES` controls the API partitioning in place of the `WINAPI_FAMILY_TV_TITLE` API family.
* You should define `/DWIN32_LEAN_AND_MEAN`, `/D_ATL_NO_DEFAULT_LIBS`, and `/D__WRL_NO_DEFAULT_LIB__`
* For the Microsoft Game Development Kit (GDK), you no longer use any Windows Runtime switches such as `/AI`, `/FU`, or `/ZW`.
* Continue to use `/favor:AMD64`, `/EHsc`, and `/fp:fast`.
* For the `Gaming.Xbox.XboxOne.x64` platform continue to use `/arch:AVX`
* For the `Gaming.Xbox.Scarlett.x64` platform use `/arch:AVX2`

> With VS 2019 Update 3 or later and the `Gaming.Xbox.Scarlett.x64` platform, also use `/d2vzeroupper`. If you are using Whole Program Optimization (WPO) / Link Time Code Generation (LTCG) then it needs to be `/d2:-vzeroupper`.

> With VS 2022 and the `Gaming.Xbox.XboxOne.x64` platform, also use `/d2vzeroupper-`. If you are using Whole Program Optimization (WPO) / Link Time Code Generation (LTCG) then it needs to be `/d2:-vzeroupper-`.

#### Linker (link.exe)

* Link against `xgameplatform.lib`, `xgameruntime.lib`, `d3d12_x.lib` or `d3d12_xs.lib`, `xmem.lib`, and `pixevt.lib`. Don't use `kernel32.lib`, `kernelx.lib`, `onecore.lib`, or `WindowsApp.lib`.
* For the XGraphics library use `xg_x.lib` or `xg_xs.lib`.
* You don't need to use `/WINMD` or `/WINMDFILE`, which were for Windows Runtime APIs.
* The Microsoft Game Development Kit (GDK) on XBOX doesn't use embedded manifests, so use `/MANIFEST:NO`.
* Continue to use `/DYNAMICBASE`, `/NXCOMPAT`.

> You should consider using `/NODEFAULTLIB` to ensure you aren't linking with any unsupported Win32 libraries including `advapi32.lib comctl32.lib comsupp.lib dbghelp.lib gdi32.lib gdiplus.lib guardcfw.lib kernel32.lib mmc.lib msimg32.lib msvcole.lib msvcoled.lib mswsock.lib ntstrsafe.lib ole2.lib ole2autd.lib ole2auto.lib ole2d.lib ole2ui.lib ole2uid.lib ole32.lib oleacc.lib oleaut32.lib oledlg.lib oledlgd.lib oldnames.lib runtimeobject.lib shell32.lib shlwapi.lib strsafe.lib urlmon.lib user32.lib userenv.lib wlmole.lib wlmoled.lib onecore.lib`.

### Optimizing Windows header Usage

The Microsoft Game Development Kit (GDK) uses the standard `<Windows.h>` header. It's useful to define the various lean and mean preprocessor defines in addition to `WIN32_LEAN_AND_MEAN` as previously mentioned to keep the overall number of Win32 system headers you pull in under control.

```cpp theme={null}
// Use the C++ standard templated min/max.
#define NOMINMAX

// DirectX apps don't need GDI.
#define NODRAWTEXT
#define NOGDI
#define NOBITMAP

// Include <mcx.h> if you need this.
#define NOMCX

// Include <winsvc.h> if you need this.
#define NOSERVICE

// WinHelp is deprecated.
#define NOHELP

#include <Windows.h>
```

### Visual C++ runtime

With the XBOX One Software Development Kit, the Visual C++ Runtime headers and libraries were part of the XBOX One Software Development Kit, with the runtime DLLs placed inside the Game OS. This required updating to a newer XBOX One Software Development Kit release or QFE level to match the minor update version of Visual Studio being used to build the code.

With the Microsoft Game Development Kit (GDK), the Visual C++ Runtime DLLs are included as part of your game package and match whatever version of Visual Studio that is installed locally on the build machine.

* `VCRuntime*.dll` and `msvcp*.dll` are the Visual C++ compiler runtime and Standard C++ Library DLLs. There is a `ucrtbase.dll` included in the Game OS that is also used.
* For debug builds, your package will contain `VCRuntime*d.dll`, `msvcp*d.dll`, and `ucrbased.dll`

> If you make use of the *ERA Migration Library*, you also need `vccorlib*.dll` which is used by the compiler when building with `/ZW`.

<Note>
  AMP is not supported for XBOX, and has been deprecated in the latest Visual C++ release.
</Note>

<a id="appstartup" />

## アプリケーションの起動

Microsoft Game Development Kit (GDK) projects use a streamlined version of the Win32 desktop-style application startup and message loop, not Windows Runtime-style CoreWindow events. Your existing codebase should have one of the following entry-points.

### Win32 desktop development

```cpp theme={null}
int WINAPI wWinMain(
    _In_ HINSTANCE hInstance,
    _In_opt_ HINSTANCE hPrevInstance,
    _In_ LPWSTR lpCmdLine,
    _In_ int nCmdShow)
{
...
```

### XBOX One Software Development Kit or UWP app using C++/CX

```cpp theme={null}
int __cdecl main(Platform::Array<Platform::String^>^ /*argv*/)
{
    auto viewProviderFactory = ref new ViewProviderFactory();
    CoreApplication::Run(viewProviderFactory);
    return 0;
}
```

### XBOX One Software Development Kit or UWP app using C++/WinRT

```cpp theme={null}
int WINAPIV WinMain()
{
    winrt::init_apartment();

    ViewProviderFactory viewProviderFactory;
    CoreApplication::Run(viewProviderFactory);

    winrt::uninit_apartment();
    return 0;
}
```

### Microsoft Game Development Kit (GDK) on XBOX

For GDK titles, the entry point is the same as the Win32 classic desktop.

```cpp theme={null}
int WINAPI wWinMain(
    _In_ HINSTANCE hInstance,
    _In_opt_ HINSTANCE hPrevInstance,
    _In_ LPWSTR lpCmdLine,
    _In_ int nCmdShow)
{
...
}
```

<a id="appinit" />

## アプリケーションの初期化

A typical, very basic Win32 entry point function looks like this.

```cpp theme={null}
int WINAPI wWinMain(
    _In_ HINSTANCE hInstance,
    _In_opt_ HINSTANCE hPrevInstance,
    _In_ LPWSTR lpCmdLine,
    _In_ int nCmdShow)
{
    HRESULT hr = CoInitializeEx(nullptr, COINITBASE_MULTITHREADED);
    if (FAILED(hr))
        return 1;

    // Register a class and create a window.
    {
        // Register class
        WNDCLASSEXW wcex = {};
        wcex.cbSize = sizeof(WNDCLASSEXW);
        wcex.style = CS_HREDRAW | CS_VREDRAW;
        wcex.lpfnWndProc = WndProc;
        wcex.hInstance = hInstance;
        wcex.hIcon = LoadIconW(hInstance, L"IDI_ICON");
        wcex.hCursor = LoadCursorW(nullptr, IDC_ARROW);
        wcex.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_WINDOW + 1);
        wcex.lpszClassName = L"MyGameWindowClass";
        wcex.hIconSm = LoadIconW(wcex.hInstance, L"IDI_ICON");
        if (!RegisterClassExW(&wcex))
            return 1;

        // Create a window.
        RECT rc = { 0, 0, static_cast<LONG>(1280), static_cast<LONG>(720) };

        AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE);

        HWND hwnd = CreateWindowExW(0, L"MyGameWindowClass", L"My Game",
            WS_OVERLAPPEDWINDOW,
            CW_USEDEFAULT, CW_USEDEFAULT,
            rc.right - rc.left, rc.bottom - rc.top, nullptr, nullptr, hInstance,
            nullptr);
        if (!hwnd)
            return 1;

        ShowWindow(hwnd, nCmdShow);

        SetWindowLongPtr(hwnd, GWLP_USERDATA, /* some object */ );

        GetClientRect(hwnd, &rc);

        // Initialize a device and more by using rc as the "real" size of the swap chain.
    }

    // Main message loop.
    MSG msg = {};
    while (WM_QUIT != msg.message)
    {
        if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        else
        {
            // Update and Render
        }
    }

    CoUninitialize();

    return static_cast<int>(msg.wParam);
}
```

This pattern is mostly the same for Microsoft Game Development Kit (GDK) titles on XBOX, but we can simplify it somewhat:

* Minimal use of window class and styles
* UTF-8 rather than UTF-16LE strings
* Initialization of the Game Runtime subsystem

```cpp theme={null}
int WINAPI wWinMain(
    _In_ HINSTANCE hInstance,
    _In_opt_ HINSTANCE hPrevInstance,
    _In_ LPWSTR lpCmdLine,
    _In_ int nCmdShow)
{
    // Initialize the Game Runtime APIs.
    if (FAILED(InitializeGameRuntime())) // Function in GameRuntimeInit.h
        return 1;

    // Register a class and create a window.
    {
        // Register class
        WNDCLASSEXA wcex = {};
        wcex.cbSize = sizeof(WNDCLASSEXA);
        wcex.style = CS_HREDRAW | CS_VREDRAW;
        wcex.lpfnWndProc = WndProc;
        wcex.hInstance = hInstance;
        wcex.lpszClassName = "MyGameWindowClass";
        wcex.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_WINDOW + 1);
        if (!RegisterClassExA(&wcex))
            return 1;

        // Create a window.

        HWND hwnd = CreateWindowExA(0, u8"MyGameWindowClass", u8"My Game",
            WS_OVERLAPPEDWINDOW,
            CW_USEDEFAULT, CW_USEDEFAULT,
            1920, 1080, nullptr, nullptr, hInstance,
            nullptr);
        if (!hwnd)
            return 1;

        ShowWindow(hwnd, nCmdShow);

        SetWindowLongPtr(hwnd, GWLP_USERDATA, /* some object of type SomeClass */ );

        // Initialize a device and more.
        // Assume a swap chain of 1080p, 1440p, or 4K.
    }

    // Main message loop.
    MSG msg = {};
    while (WM_QUIT != msg.message)
    {
        if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        else
        {
            // Update and Render
        }
    }

    UninitializeGameRuntime();

    return static_cast<int>(msg.wParam);
}
```

> For Microsoft Game Development Kit (GDK) titles on XBOX, you can have only one Win32 window.

<a id="winmsgloop" />

## Windows メッセージング ループ

Because many messages don't apply, Microsoft Game Development Kit (GDK) applications on XBOX can use a very basic Win32 messaging loop.

```cpp theme={null}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    auto appPtr = reinterpret_cast<SomeClass*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));

    switch (message)
    {
    case WM_CREATE:
        break;

    case WM_ACTIVATEAPP:
        break;

    // WM_USER messages the application posts to itself.

    return DefWindowProc(hWnd, message, wParam, lParam);
}
```

The use of a Win32 messaging loop is optional, but it's a useful place to start if you're moving from an existing Win32 codebase.

The following table shows a list of common Win32 messages found in classic Win32 desktop games, and the application (or lack thereof) of these messages to Microsoft Game Development Kit (GDK) titles on Xbox.

| Message | Description |
| - | - |
| WM\_CREATE | This message is sent when the window is created. |
| WM\_DESTROY <br /> WM\_CLOSE | These messages don't apply to Microsoft Game Development Kit (GDK) titles on XBOX, which uses a process lifetime management (PLM) suspend/terminate model. |
| WM\_CHAR <br /> WM\_KEYDOWN <br /> WM\_KEYUP | These messages are sent for keyboard input and GamePad virtual keys. |
| WM\_SYSKEYDOWN <br /> WM\_SYSKEYUP <br /> WM\_CHAR | These messages are sent for keyboard input. |
| WM\_USER | Applications can send their own messages to the message loop. Applications can take advantage of this because they are processed on the main loop thread context. |
| WM\_SIZE | This message relates to minimized, maximized, and restored settings. However, Microsoft Game Development Kit (GDK) titles on XBOX don't encounter these scenarios. |
| WM\_ENTERSIZEMOVE <br /> WM\_EXITSIZEMOVE <br /> WM\_GETMINMAXINFO | These messages relate to rubber-band resizing on desktop. However, a Microsoft Game Development Kit (GDK) title on XBOX doesn't encounter this scenario. |
| WM\_PAINT | For Win32 desktop apps, this message is typically implemented to redraw the window for paused or rubber-band scenarios, which don't apply. |
| WM\_POWERBROADCAST | Microsoft Game Development Kit (GDK) titles on XBOX use the PLM notifications for suspend/resume, not the desktop model of sleep power-modes. |
| WM\_SETFOCUS <br /> WM\_KILLFOCUS <br /> WM\_ACTIVATE <br /> WM\_ACTIVATEAPP <br /> WM\_SHOWWINDOW | For Microsoft Game Development Kit (GDK) titles on XBOX, these messages are sent when the user is interacting with the guide or returning from other title-callable UI (TCUI). |
| WM\_TIMER | This message is supported for Microsoft Game Development Kit (GDK) titles on XBOX if you use `SetTimer` / `KillTimer`. |

<a id="d3ddevicecreate" />

## Direct3D デバイスの作成

Games built with the Microsoft Game Development Kit (GDK) on XBOX use the Direct3D 12.X API, which is implemented as the monolithic runtime, just as it's implemented with the XBOX One Software Development Kit.

| Stock Direct3D 12 | DirectX 12.X extensions |
| - | - |
| `#include <d3d12.h>` <br /> `#include <dxgi1_4.h>` | `#include <d3d12_x.h>` or `#include <d3d12_xs.h>` |
| `#include <d3dx12.h>` | `#include <d3dx12_x.h>` or `#include <d3dx12_xs.h>` |
| D3D12CreateDevice | D3D12XboxCreateDevice |
| IDD\_PPV\_ARGS macro | IDD\_GRAPHICS\_PPV\_ARGS macro |

Stock Direct3D 12 and Direct3D 11 aren't supported for games built with the Microsoft Game Development Kit (GDK) on Xbox. When you create a Direct3D 12 device for DirectX 12.X, use the `D3D12XboxCreateDevice` method.

```cpp theme={null}
ComPtr<ID3D12Device> device;

...

D3D12XBOX_CREATE_DEVICE_PARAMETERS params = {};
params.Version = D3D12_SDK_VERSION;

#if defined(_DEBUG)
// Enable the debug layer.
params.ProcessDebugFlags = D3D12_PROCESS_DEBUG_FLAG_DEBUG_LAYER_ENABLED;
#elif defined(PROFILE)
// Enable the instrumented driver.
params.ProcessDebugFlags = D3D12XBOX_PROCESS_DEBUG_FLAG_INSTRUMENTED;
#endif

params.GraphicsCommandQueueRingSizeBytes = static_cast<UINT>(D3D12XBOX_DEFAULT_SIZE_BYTES);
params.GraphicsScratchMemorySizeBytes = static_cast<UINT>(D3D12XBOX_DEFAULT_SIZE_BYTES);
params.ComputeScratchMemorySizeBytes = static_cast<UINT>(D3D12XBOX_DEFAULT_SIZE_BYTES);

ThrowIfFailed(D3D12XboxCreateDevice(
    nullptr,
    &params,
    IID_GRAPHICS_PPV_ARGS(device.GetAddressOf())
    ));
```

From here, the command queue, command list, and other items will continue to be created as they would with standard Direct3D 12.

To support 4k rendering, you simply use a larger swapchain width & height, but you should continue to support 1080p for lower-end consoles. A recommended way to determine when to use 4k vs. 1440p vs. 1080p is as follows:

```cpp theme={null}
RECT outputSize = { 0, 0, 1920, 1080 };
switch (XSystemGetDeviceType())
{
case XSystemDeviceType::XboxOne:
case XSystemDeviceType::XboxOneS:
    break;

case XSystemDeviceType::XboxScarlettLockhart /* Xbox Series S */:
    outputSize = { 0, 0, 2560, 1440 };
    break;

case XSystemDeviceType::XboxScarlettAnaconda /* Xbox Series X */:
case XSystemDeviceType::XboxOneXDevkit:
case XSystemDeviceType::XboxScarlettDevkit:
default:
   outputSize = { 0, 0, 3840, 2160 };
   break;
}
```

For more details, see the [*SimpleDeviceAndSwapChain*](https://github.com/microsoft/Xbox-GDK-Samples/tree/main/Samples/IntroGraphics/SimpleDeviceAndSwapChain) sample.

### XMem\* APIs

Any calls to `XMem*` APIs that use `XMEM_GRAPHICS` require that the Direct3D device has been created before they are used. Alternatively, you can call D3DConfigureVirtualMemory if you need to use those calls before the Direct3D device exists.

```cpp theme={null}
D3D11X_VIRTUAL_MEMORY_CONFIGURATION vmConfig = {};
vmConfig.PageTableMemory4MBPageCount = 5;
ThrowIfFailed(
      D3DConfigureVirtualMemory(&VMConfig)
    );
```

### CPU/GPU Reservation

All Microsoft Game Development Kit (GDK) titles get full resources (that is, no Kinect GPU reservation) and the seventh CPU core. By default, you get the equivalent of the following XBOX One Software Development Kit manifest settings.

```xml theme={null}
<mx:Extension Category="xbox.system.resources">
  <mx:XboxSystemResources resourceConfiguration="extended">
    <mx:GpuAvailability>variable</mx:GpuAvailability>
  </mx:XboxSystemResources>
</mx:Extension>
```

### XBOX One vs. XBOX Series X|S Direct3D Differences

The Direct3D 12.x monolithic runtime implementation for the `Gaming.Xbox.XboxOne.x64` platform is almost identical to the XBOX One Software Development Kit implementation of Direct3D 12.x. For your initial port to the Microsoft Game Development Kit (GDK) on XBOX this platform is likely the easiest place to start.

* `Gaming.Xbox.Scarlett.x64` supports up to ID3D12Device8 and ID3D12GraphicsCommandList5 interface or later versions.
* `Gaming.Xbox.XboxOne.x64` supports up to ID3D12Device, ID3D12Device1, ID3D12Device2 and ID3D12GraphicsCommandList.

When moving to the `Gaming.Xbox.Scarlett.x64` platform, there are some additional capabilities as well as some differences in the Direct3D 12.x implementation.

* You need to use a different version of the Direct3D headers and libraries (i.e. `d3d12_xs.h`, `d3dx12_xs.h`, `xg_xs.h`, `d3d12_xs.lib`, etc.). You cannot mix the two versions of Direct3D 12.x in the same binary.
* When the Direct3D 12.x monolithic runtime was first implemented, it was built on top of the Direct3D 11.x monolithic runtime, so a number of Direct3D 11 types are defined when building with the `Durango` or `Gaming.Xbox.XboxOne.x64` platforms. These have been removed from the XBOX Series X|S implementation so you may encounter build issues with any lingering references to the `d3d11_x.h` header, `D3D11_*` defines, `CD3D11_*` classes or `ID3D11*` interfaces. These can be removed and still build for both platforms.
* ESRAM is not a feature of XBOX Series X|S so extensions related to ESRAM are not defined for this platform. This also means `xgmemory.h` (a helper for utilizing ESRAM) is only supported for the `Gaming.Xbox.XboxOne.x64` platform.

<Note>
  It remains important to utilize ESRAM on XBOX One / XBOX One S devices for optimal rendering performance. See the SimpleESRAM and [*AdvancedESRAM*](https://github.com/microsoft/Xbox-GDK-Samples/tree/main/Samples/Graphics/AdvancedESRAM) samples.
</Note>

* There are a number of differences in GPU memory layouts, in particular H-tile and C-Mask techniques. For details, see the *CMaskDecode*, *HiZDecode*, *HiStencil*, and *PrimeHTile* samples.

<a id="presentation" />

## プレゼンテーション

The Microsoft Game Development Kit (GDK) on XBOX doesn't support legacy DXGI swap chains for presentation, but it does use the PresentX API. The new PresentX APIs are designed to address latency concerns with DXGI swap chains, and provides the developer more direct control of the presentation buffers. This API is also designed to scale for future streaming applications.

The first step in using PresentX is to register for frame events after the Direct3D device is created.

```cpp theme={null}
// First, retrieve the underlying DXGI device from the D3D device.
ComPtr<IDXGIDevice1> dxgiDevice;
ThrowIfFailed(device.As(&dxgiDevice));

// Identify the physical adapter (GPU or card) that this device is running on.
ComPtr<IDXGIAdapter> dxgiAdapter;
ThrowIfFailed(dxgiDevice->GetAdapter(dxgiAdapter.GetAddressOf()));

// Retrieve the outputs for the adapter.
ComPtr<IDXGIOutput> dxgiOutput;
ThrowIfFailed(dxgiAdapter->EnumOutputs(0, dxgiOutput.GetAddressOf()));

// Set the frame interval, and register for frame events.
ThrowIfFailed(device->SetFrameIntervalX(
    dxgiOutput.Get(),
    D3D12XBOX_FRAME_INTERVAL_60_HZ,
    2 /* Allow 2 frames of latency */,
    D3D12XBOX_FRAME_INTERVAL_FLAG_NONE));

ThrowIfFailed(device->ScheduleFrameEventX(
    D3D12XBOX_FRAME_EVENT_ORIGIN,
    0U,
    nullptr,
    D3D12XBOX_SCHEDULE_FRAME_EVENT_FLAG_NONE));
```

Instead of creating a DXGI swap chain and requesting the back-buffer resources, create them directly with the `D3D12_HEAP_FLAG_ALLOW_DISPLAY` flag.

```cpp theme={null}
ComPtr<ID3D12Resource> renderTargets[MAX_BACK_BUFFER_COUNT];

...

CD3DX12_HEAP_PROPERTIES swapChainHeapProperties(D3D12_HEAP_TYPE_DEFAULT);

D3D12_RESOURCE_DESC swapChainBufferDesc = CD3DX12_RESOURCE_DESC::Tex2D(
    backBufferFormat,
    backBufferWidth,
    backBufferHeight,
    1, // This resource has only one texture.
    1  // Use a single mipmap level.
);
swapChainBufferDesc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;

D3D12_CLEAR_VALUE swapChainOptimizedClearValue = {};
swapChainOptimizedClearValue.Format = backBufferFormat;

for (UINT n = 0; n < m_backBufferCount; n++)
{
    ThrowIfFailed(m_d3dDevice->CreateCommittedResource(
        &swapChainHeapProperties,
        D3D12_HEAP_FLAG_ALLOW_DISPLAY,
        &swapChainBufferDesc,
        D3D12_RESOURCE_STATE_PRESENT,
        &swapChainOptimizedClearValue,
        IID_GRAPHICS_PPV_ARGS(renderTargets[n].GetAddressOf())));

    D3D12_RENDER_TARGET_VIEW_DESC rtvDesc = {};
    rtvDesc.Format = m_backBufferFormat;
    rtvDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2D;

    CD3DX12_CPU_DESCRIPTOR_HANDLE rtvDescriptor(rtvDescriptorHeap->GetCPUDescriptorHandleForHeapStart(), n,
         rtvDescriptorSize);
    device->CreateRenderTargetView(renderTargets[n].Get(), &rtvDesc, rtvDescriptor);
}
```

At the start of each rendering frame, set a pipeline token first by using `WaitFrameEventX`.

```cpp theme={null}
D3D12XBOX_FRAME_PIPELINE_TOKEN framePipelineToken = {};

...

framePipelineToken = D3D12XBOX_FRAME_PIPELINE_TOKEN_NULL;
ThrowIfFailed(device->WaitFrameEventX(D3D12XBOX_FRAME_EVENT_ORIGIN, INFINITE, nullptr,
      D3D12XBOX_WAIT_FRAME_EVENT_FLAG_NONE, &framePipelineToken));
```

At the end of the frame, use the same token to call PresentX.

```cpp theme={null}
D3D12XBOX_PRESENT_PLANE_PARAMETERS planeParameters = {};
planeParameters.Token = framePipelineToken;
planeParameters.ResourceCount = 1;
planeParameters.ppResources = renderTargets[backBufferIndex].GetAddressOf();

ThrowIfFailed(commandQueue->PresentX(1, &planeParameters, nullptr));
```

As with XBOX One Software Development Kit titles, Microsoft Game Development Kit (GDK) games on XBOX don't encounter `DXGI_ERROR_DEVICE_REMOVED` and `DXGI_ERROR_DEVICE_RESET` errors, which must be handled for PC games.

Some other related DXGI functionality has been removed, and the previously mentioned `ScheduleFrameEventX` function supersedes `DXGIXSetFrameNotification` from the XBOX One Software Development Kit.

Here's the XBOX One Software Development Kit code for frame flip notification.

```cpp theme={null}
FlipEvent = CreateEvent(nullptr, false, false, "DXGIXFrameFlipEvent");
VERIFYD3D12RESULT(DXGIXSetFrameNotification(FRAME_NOTIFICATION_FLIPPED, FlipEvent));
```

Equivalent code for Microsoft Game Development Kit (GDK) titles on Xbox.

```cpp theme={null}
FlipEvent = CreateEventA(nullptr, false, false, u8"ScheduleFrameEventX");
D3D12XBOX_SCHEDULE_FRAME_OBJECT_LIST objList = { 1, &FlipEvent };
VERIFYD3D12RESULT(GetD3D12Device()->ScheduleFrameEventX(D3D12XBOX_FRAME_EVENT_DISPLAY_FLIP, 0, &objList, D3D12XBOX_SCHEDULE_FRAME_EVENT_FLAG_NONE));
```

For more details, see Frame scheduling and presentation on XBOX One, and the [*SimpleDeviceAndSwapChain*](https://github.com/microsoft/Xbox-GDK-Samples/tree/main/Samples/IntroGraphics/SimpleDeviceAndSwapChain), [*HDR10*](https://github.com/microsoft/Xbox-GDK-Samples/tree/main/Samples/Graphics/HDR10), and [*SimpleHDR*](https://github.com/microsoft/Xbox-GDK-Samples/tree/main/Samples/Graphics/SimpleHDR) samples.

<a id="plm" />

## Process lifetime management (PLM)

Games built with the Microsoft Game Development Kit (GDK) on XBOX use the same basic process lifetime management (PLM) model that's used by XBOX One XDK apps and UWP apps. Apps run unconstrained, constrained, suspended, or terminated; that is, no code executes for termination, and the process is simply destroyed.

XBOX One Software Development Kit apps and UWP apps receive notifications through their Windows Runtime CoreWindow. Microsoft Game Development Kit (GDK) games on XBOX receive notifications through registered callbacks. Note that there is only a suspend and a resume event, and there's no longer an explicit activation phase.

A simple implementation approach is to handle this by posting a `WM_USER` message.

```cpp theme={null}
#include <appnotify.h>

...

PAPPSTATE_REGISTRATION hPLM = {};
HANDLE plmSuspendComplete = nullptr;
HANDLE plmSignalResume = nullptr;

...

// Create a window.

plmSuspendComplete = CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE);
plmSignalResume = CreateEventEx(nullptr, nullptr, 0, EVENT_MODIFY_STATE | SYNCHRONIZE);
if (!plmSuspendComplete || !plmSignalResume)
    return 1;

if (RegisterAppStateChangeNotification([](BOOLEAN quiesced, PVOID context)
{
    if (quiesced)
    {
        ResetEvent(plmSuspendComplete);
        ResetEvent(plmSignalResume);

        // To ensure we use the main UI thread to process the notification, we self-post a message.
        PostMessage(reinterpret_cast<HWND>(context), WM_USER, 0, 0);

        // To defer suspension, we must wait to exit this callback.
        (void)WaitForSingleObject(plmSuspendComplete, INFINITE);
    }
    else
    {
        SetEvent(plmSignalResume);
    }
}, hwnd, &hPLM))
    return 1;

// Message loop.

UnregisterAppStateChangeNotification(hPLM);

CloseHandle(plmSuspendComplete);
CloseHandle(plmSignalResume);
```

Subsequently, the message loop would handle the `WM_USER` message to ensure that the loop is paused until Resume, and that the proper GPU suspend/resume behavior takes place at a safe time in the render loop.

```cpp theme={null}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
...
    switch (message)
    {
    case WM_USER:
        // Call SuspendX(0) on your command queue, and cease all GPU submissions.

        // Complete deferral.
        SetEvent(plmSuspendComplete);

        (void)WaitForSingleObject(plmSignalResume, INFINITE);

        // Before picking up rendering again, call ResumeX on your command queue.

        // You'll also need to register again for frame events
        // via SetFrameIntervalX and ScheduleFrameEventX.
        break;
    }
...
}
```

For more details, see the [*SimplePLM*](https://github.com/microsoft/Xbox-GDK-Samples/tree/main/Samples/System/SimplePLM) sample.

### Constrained vs. full

Notification of constrained versus full resources is handled through a similar API.

```cpp theme={null}
#include <appnotify.h>

PAPPCONSTRAIN_REGISTRATION hPLM2 = {};

// Create a window.

if (RegisterAppConstrainedChangeNotification([](BOOLEAN constrained, PVOID context)
{
    SendMessage(reinterpret_cast<HWND>(context), WM_USER+1, (constrained) ? 1 : 0, 0);
}, hwnd, &hPLM2))
    return 1;

// Message loop

UnregisterAppConstrainedChangeNotification(hPLM2);
```

Here we use a message for the same reasons as we did previously in the suspend/resume case.

```cpp theme={null}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_USER+1:
        if (wParam)
        {
          // Constrained resources mode
        }
        else
        {
          // Full resource mode
        }
        break;
    }
}
```

For more details, see the [*SimplePLM*](https://github.com/microsoft/Xbox-GDK-Samples/tree/main/Samples/System/SimplePLM) sample.

### Process termination

For retail titles, process termination is handled the same as it was for the older XBOX One Software Development Kit platform. The process is suspended and then terminated. None of the C++ destructors or cleanup are processed. This was true if you also called `Windows::ApplicationModel::Core::CoreApplication::Exit`.

With the Microsoft Game Development Kit (GDK), you can achieve a clean exit like you can with classic Win32 desktop apps via `PostQuitMessage`. This results in your message loop exiting and normal code cleanup and process teardown will take place. This is useful for development to help detect leaks and other cleanup problems that can otherwise be difficult to find. This behavior, however, likely invokes code paths that are never executed in the older XBOX One Software Development Kit platform.

<a id="memmgmt" />

## メモリ管理

For more information about memory management, see Memory Overview.

### Changes in the memory model

The Microsoft Game Development Kit (GDK) platform includes many changes made to the memory model from the original XBOX One Game OS. Most of this effort has been spent on improving the isolation of memory used by the title from memory used by the system. Improving isolation would make memory usage more predictable across the title and system, and would prevent unexpected usage by system calls.

As part of this work, we're moving to the latest version of the Windows Memory Management subsystem. Although many games won't require any major changes, you should examine your use of these memory APIs carefully. The meanings and behavior of the flags have changed.

If you're allocating and mapping physical pages manually, keep in mind that some constraints on mappings have changed, and that a different pattern is to be followed for the APIs.

* When physical pages are mapped into the Virtual Address Space more than once, all allocations must share the same cache coherency settings. For example, you can't mix and match Write Combined and normal CPU Read/Write page settings on the same physical memory.
* Page settings and cache coherency values now live in the virtual-address region that the pages are mapped into. This region must be reserved ahead of time by calling XMemVirtualAlloc and using the `MEM_RESERVE` pattern. This step wasn't required in the previous version of the OS.

For all allocations that are mapped for access by the GPU, explicit GPU access flags are now required. There is no longer a default based on the CPU protection settings.

Take care to identify, anywhere in your codebase, that you've used the `MEM_LARGE_PAGES` constant. Its values and meanings have changed to match the meanings used across Windows.

| Name | Meaning in XBOX One Software Development Kit API | Meaning in the Microsoft Game Development Kit (GDK) on XBOX | Meaning on desktop Windows |
| :- | -: | -: | -: |
| MEM\_LARGE\_PAGES | 64-KB page | 2-MB page (ambiguous, may be removed) | 2-MB page |
| MEM\_4MB\_PAGES | 4-MB page | Not defined | Not defined |
| MEM\_64K\_PAGES | Not defined | 64-KB page | Not defined |
| MEM\_2MB\_PAGES | Not defined | 2-MB page | Not defined |

With the change of large pages from 4 MB in the XBOX One Game OS to 2 MB in the Microsoft Game Development Kit (GDK) on XBOX OS, the XMemAlloc size specifiers have also changed for large pages from `XALLOC_PAGESIZE_4MB` to `XALLOC_PAGESIZE_2MB`.

Our memory map has also changed and is no longer segmented into Legacy, Title, Graphics, and Physical regions. They now cover the entire 8-TB address space.

### Changes in APIs

The Microsoft Game Development Kit (GDK) memory APIs begin with the **XMem** prefix and, for the most part, mirror the APIs already in the existing XBOX One XDK OS, even though their behavior has changed.

| XBOX One Software Development Kit API | Microsoft Game Development Kit (GDK) on XBOX |
| :- | :- |
| VirtualAlloc | XMemVirtualAlloc |
| VirtualFree | [VirtualFree](https://learn.microsoft.com/windows/desktop/api/memoryapi/nf-memoryapi-virtualfree) |
| AllocateTitlePhysicalPages | XMemAllocatePhysicalPages |
| MapTitlePhysicalPages | XMemMapPhysicalPages |
| FreeTitlePhysicalPages | XMemFreePhysicalPages |
| TitleMemoryStatus | XMemGetWorkingSetStatistics |

The new APIs are shown in the following table.

| Name | Description |
| :- | :- |
| XMemVirtualQuery | Queries the Virtual Address Space and returns information on how its pages are mapped. It's similar to VirtualQuery in Win32, but is used mainly for debugging and diagnostics. |

### Use XMemVirtualAlloc instead of VirtualAlloc

In the Microsoft Game Development Kit (GDK), the new `XMemVirtualAlloc` API replaces all uses of `VirtualAlloc` for allocating XBOX graphics memory. Note the previous requirements for specifying GPU page and cache coherency requirements for reserves later backed by physical mappings.

A comparison of such a reservation on XBOX One Software Development Kit:

```cpp theme={null}
void * memPool = VirtualAlloc(nullptr,
    size,
    MEM_LARGE_PAGES | MEM_GRAPHICS | MEM_RESERVE,
    PAGE_READONLY);
```

and Microsoft Game Development Kit (GDK):

```cpp theme={null}
void * memPool = XMemVirtualAlloc(nullptr,
    size,
    MEM_64K_PAGES | MEM_RESERVE,
    XMEM_GRAPHICS | XMEM_MAPPABLE,
    PAGE_READONLY | PAGE_GRAPHICS_COHERENT | PAGE_GRAPHICS_READWRITE);
```

Or for an allocation not backed by mapped physical pages and committed at reserve time:

```cpp theme={null}
void* memory = VirtualAlloc(nullptr,
    size,
    MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES | MEM_GRAPHICS,
    PAGE_READWRITE | PAGE_WRITECOMBINE);
```

Changes to:

```cpp theme={null}
void* memory = XMemVirtualAlloc(nullptr,
    size,
    MEM_RESERVE | MEM_COMMIT | MEM_64K_PAGES,
    TITLE_MEM_GRAPHICS,
    PAGE_READWRITE | PAGE_WRITECOMBINE | PAGE_GRAPHICS_READWRITE);
```

### Use VirtualFree

The memory allocated by `VirtualAlloc` or XMemVirtualAlloc is still freed with `VirtualFree`. There's no `XMemVirtualFree` API.

### XMemAlloc usage

The Attributes macro now has an additional parameter. For example:

```cpp theme={null}
const uint64_t c_XMemAllocAttributes = MAKE_XALLOC_ATTRIBUTES(
    eXALLOCAllocatorId_MiddlewareReservedMin,
    0,
    XALLOC_MEMTYPE_GRAPHICS_WRITECOMBINE_GPU_READONLY,
    XALLOC_PAGESIZE_64KB,
    XALLOC_ALIGNMENT_64K);
```

Changes to:

```cpp theme={null}
const uint64_t c_XMemAllocAttributes = MAKE_XALLOC_ATTRIBUTES(
    eXALLOCAllocatorId_MiddlewareReservedMin,
    0,
    XALLOC_MEMTYPE_GRAPHICS_WRITECOMBINE_GPU_READONLY,
    XALLOC_PAGESIZE_64KB,
    XALLOC_ALIGNMENT_64K,
    0);
```

### XMemAllocatePhysicalPages and XMemMapPhysicalPages

With the change of moving page flags and cache coherency to reservation time, the calls for allocating and mapping physical memory are simplified, but otherwise is similar to XBOX One Software Development Kit. `XMemAllocatePhysicalPages` replaces `AllocateTitlePhysicalPages`. XMemMapPhysicalPages replaces `MapTitlePhysicalPages`.

This XBOX One Software Development Kit code:

```cpp theme={null}
void * memPool = VirtualAlloc(nullptr, size, MEM_LARGE_PAGES | MEM_GRAPHICS | MEM_RESERVE, PAGE_READONLY);
AllocateTitlePhysicalPages(GetCurrentProcess(), MEM_LARGE_PAGES, &NumPages64, PageArray);
MapTitlePhysicalPages(memPool, NumPages64, MEM_GRAPHICS | MEM_LARGE_PAGES, PAGE_READONLY, PageArray);
```

Changes to this for Microsoft Game Development Kit (GDK) titles:

```cpp theme={null}
void * memPool = XMemVirtualAlloc(nullptr, size, MEM_64K_PAGES | MEM_RESERVE, XMEM_GRAPHICS | XMEM_MAPPABLE, PAGE_READONLY | PAGE_GRAPHICS_COHERENT | PAGE_GRAPHICS_READWRITE);
XMemAllocatePhysicalPages(MEM_64K_PAGES, &NumPages64, PageArray);
XMemMapPhysicalPages(memPool, NumPages64, PageArray);
```

<a id="appmodel" />

## プログラミング モデル

For more information about the programming model, see the Asynchronous Programming Model topic.

### Synchronous (blocking) code with GameRuntime

For APIs where blocking is a reasonable option, the blocking (synchronous) versions of all library functionality have been provided, even if the calls would be long-running. The developer can spawn threads and call the blocking functions from those threads by using the scheduler to manage concurrency, which is often simpler to implement than C++11 style futures and promises. There are some cases (such as network calls) where the runtime of the functions is known to be non-deterministic, so only asynchronous versions are provided.

### Asynchronous code with GameRuntime

The Microsoft Game Development Kit (GDK) platform includes a new model for performing asynchronous tasks and reporting their results via callbacks. This model replaces Windows Runtime. Use the GameRuntime APIs to specify how and where asynchronous work and callbacks occur.

The following sample code includes simple boiler-plate examples of how a Game Runtime Task Queue is set up to process your system calls. This queue can be used to process system tasks *and* as the location where callbacks are executed. Conceptually, a callback is a task that runs *your* code in response to system actions. If necessary, you can create multiple Task Queues to manage work on different cores, or to specify the queue that executes callbacks on a call-by-call basis.

Dispatching queued work items can be pumped manually by your code (this is similar to a Windows message queue), or pumped automatically. The following are simple examples of how a manually pumped queue is created and then pumped.

```cpp theme={null}
XTaskQueueHandle queue;

// This one allows async work to use the default thread pool, but completion is explicit.
ThrowIfFailed(
    XTaskQueueCreate(XTaskQueueDispatchMode::ThreadPool, XTaskQueueDispatchMode::Manual, &queue)
);

...

// This pumps the completion work, which takes place on the calling thread.
while (XTaskQueueDispatch(m_queue, XTaskQueuePort::Completion, 0))
{
    // ... do other work ...
}
```

For more information, see the [*SimplePLM*](https://github.com/microsoft/Xbox-GDK-Samples/tree/main/Samples/System/SimplePLM) sample, which triggers the settings as well as title-callable UI (TCUI) for sign-in using an XTask async queue.

For details on the Asynchronous Programming Model, see the Asynchronous Programming Model and Async task queue design topics. See also the [*AsynchronousProgramming*](https://github.com/microsoft/Xbox-GDK-Samples/tree/main/Samples/System/AsynchronousProgramming) sample.

### General naming pattern for asynchronous API calls

The following table shows the general pattern used by the Microsoft Game Development Kit (GDK) and the Game Runtime for naming asynchronous calls.

| Function Schema | Meaning |
| :- | :- |
| QueryUpdateStatus | Synchronous, long-running call |
| QueryUpdateStatusAsync | Asynchronous, likely non-deterministic, long-running call |
| QueryUpdateStatusAsyncResultSize | Called before the results are obtained from the operation, if it varies in size |
| QueryUpdateStatusAsyncResult | Obtains the result from the asynchronous operation |

### XAsyncBlock replaces IAsyncOperation and IAsyncAction

When calling an asynchronous function, create an `XAsyncBlock` structure, which must be kept alive for the duration of the call until it has completed, been canceled, or failed.

The `XAsyncBlock` type contains three parameters of immediate relevance.

| Type | Field | Usage |
| -: | :- | :- |
| XTaskQueueHandle | queue | The queue you've designated as the one that the asynchronous work will be performed on. <br /> A null value implies running on the system thread pool. |
| void\* | context | A field you can use to identify which call you made to cause the asynchronous operation to be performed. <br /> Typically, it's a *this* pointer of an object, or a unique identifier. |
| XAsyncCompletionRoutine\* | callback | The function pointer of the routine to be called when the callback executes. |

Example usage:

```cpp theme={null}
auto b = new XAsyncBlock{};
b->context = this;
b->queue = queue;
b->callback = [](XAsyncBlock* async)
{
    UpdateStatus status;
    if(SUCCEEDED(QueryUpdateStatusAsyncResult(async, &status)))
    {
       printf("Update Status: %d\r\n", status);
    }
    delete async;
};
QueryUpdateStatusAsync("Foo", b);
```

> Note that it is critical that you 'zero-fill' the XAsyncBlock structure when you create it, hence the use of `{}` instead of `()`.

### Time sensitive operations

The Microsoft Game Development Kit (GDK) libraries let you specify whether the thread you're calling from is time sensitive. Runtime warnings can be reported if you call functions that are *not* time sensitive from a time sensitive thread.

```cpp theme={null}
HRESULT SetTimeSensitiveThread(bool isTimeSensitive);
HRESULT VerifyNotTimeSensitiveThread();
```

To mark a thread as time sensitive, call `SetTimeSensitiveThread(true)` on the thread. You can also call `VerifyNotTimeSensitiveThread()` from within long-running functions in your own code to report improper usage from time-critical threads.

<a id="hlsl" />

## HLSL シェーダー

The XBOX One Software Development Kit platform used a customized version of the `FXC.EXE` HLSL compiler that supported precompiling of Shader Model 5.1 programmable shaders to ATI microcode. In addition, preview was supported for the `DXC.EXE` DXIL compiler for Shader Model 6.

For the Microsoft Game Development Kit (GDK) on XBOX, use of the DXIL compiler and Shader Model 6 is recommended via `DXC.EXE`. The `FXC.EXE` Shader Model 5.1 compiler is now considered legacy. The new compiler supports most of the command-line flags supported by the old compiler, although some of the Xbox-specific extension `defines` are not applicable or not supported. For details on Shader Model 6 and DXIL, see the [GitHub](https://github.com/Microsoft/DirectXShaderCompiler) project.

<Note>
  For PC usage of Shader Model 6: Windows 10 Creators Update and later versions support Shader Model 6.x DXIL shaders, as do many retail drivers. Instead of relying on the Windows Update WHQL drivers for this feature, you need to install the latest driver directly from its vendor. The `DXC.EXE` compiler for Windows is included in the Windows 10 April 2018 Update SDK and later versions. At runtime, you can determine whether your PC supports Shader Model 6.x via `CheckFeatureSupport` using `D3D12_FEATURE_SHADER_MODEL`, but be sure to initialize `shaderModel.HighestShaderModel` before calling the function!
</Note>

The XBOX One version of the DXIL compiler is located here: `%GameDKLatest%\GXDK\bin\XboxOne\DXC.exe`.

The XBOX Series X|S version of the DXIL compiler is located here: `%GameDKLatest%\GXDK\bin\Scarlett\DXC.exe`.

### D3DCompile APIs

For Shader Model 6, you should use the `dxcompiler_x.lib` or `dxcompiler_xs.lib` library rather than `d3dcompiler_x.lib`.

<a id="user" />

## User Management

The user model has changed for the Microsoft Game Development Kit (GDK) from what you may be used to in the XBOX One Software Development Kit. This is in part to better manage users' privacy expectations and to ease the burden of always keeping track of what the system is doing in the background with users that the title shouldn't care about. Rather than having titles monitor a system-wide collection of which users and guests are signed into the console, the system only exposes users on-demand.

To acquire a user for your title (for example, when the user presses the A button on a controller to start a game session, and the controller has not yet been associated with a user), make a call to XUserAddAsync. This call will perform two important actions: it signs users into the title and updates user input device pairing.

Users may have any number of input devices paired to them at a time. However, the title is only made aware of associations for users that have been signed in with XUserAddAsync. If the system Guide is used to sign in a user or change associations outside of the title to a user that the title is unaware of, then the title is only told that the input device has been unpaired. The system outside of the title, however, still knows of the pairing for system usage.

Titles can monitor changes in a user's state, or a user's associated *information* (such as their Gamertag, Gamer Picture, or Privileges) by subscribing to `XUserChangeEvent` (although some of this information, such as user sign-in state, could be monitored by polling). You do this by calling XUserRegisterForChangeEvent.

Most titles should expect to need to build their own collection of users, track when users become signed in to the title, track input device associations, and handle when users are signed out.

For an in-depth discussion of these changes, see Users and input devices. See also the *UserManagement* sample.

<a id="live" />

## Networking and XBOX services Integration

### Networking Transport

The Microsoft Game Development Kit (GDK) on XBOX supports both WinSock2 and BCrypt via CNG. If using UDP, rather than hard-coding a port such as 3074 for your multiplayer socket binding, for the Microsoft Game Development Kit (GDK) you should make use of this new flat C API:

```cpp theme={null}
uint16_t port;
hr = XNetworkingQueryPreferredLocalUdpMultiplayerPort(&port);
if (FAILED(hr))
    // NAT traversal failure
```

To detect network connectivity with the Microsoft Game Development Kit (GDK), make use of [IPHelper](https://learn.microsoft.com/windows/desktop/IpHlp/ip-helper-start-page) rather than the `Windows.Networking.Connectivity` namespace. For sample code, see Network Initialization & Connectivity.

<Note>
  Secure Sockets (`Windows.Xbox.Networking` namespace) has been removed for the Microsoft Game Development Kit (GDK).
</Note>

For more details, see Introduction to WinSock networking.

### Web Requests via HTTP

The Microsoft Game Development Kit (GDK) no longer supports `IXMLHTTPRequest2` or `MessageWebSocket` / `StreamWebSocket` (`Windows.Networking.Sockets` namespace). Instead you should make use of [WinHTTP](https://learn.microsoft.com/windows/desktop/WinHttp/about-winhttp).

For more details, see Web Requests.

### XBOX services APIs

Developers currently using the Windows Runtime or C++ versions of XSAPI will need to move to using the flat C version for XBOX services integration features:

* Achievements
* Presence
* Profile
* Social
* Social Manager

See Introduction to the XBOX services C APIs and XSAPI reference.

If you are making use of Game Chat 2, be aware that a few classes were renamed as shown in the following table.

| XBOX One Software Development Kit name | Microsoft Game Development Kit (GDK) on XBOX name |
| :- | :- |
| game\_chat\_audio\_encoding\_type\_and\_bitrate | game\_chat\_audio\_encoding\_bitrate |
| set\_audio\_encoding\_type\_and\_bitrate | set\_audio\_encoding\_bitrate |
| audio\_encoding\_type\_and\_bitrate | audio\_encoding\_bitrate |

<a id="nextsteps" />

## 次のステップ

After completing your initial port from ERA, you will be in a great position to enable a number of features for Microsoft Game Development Kit (GDK) on Xbox. If your title is running well on XBOX One S / XBOX One X hardware, these are easy ways to improve the experience on XBOX Series X|S consoles.

**Note that many of these features are enabled automatically for legacy ERA titles, but are opt-in for Microsoft Game Development Kit (GDK) on XBOX titles. Now that your title is native Microsoft Game Development Kit (GDK) on XBOX, be sure to enable them!**

* **AutoHDR**: This feature automatically converts an SDR title to HDR at a system level, enhancing the visual quality of the game when played on an HDR10 capable display. It uses XBOX Series X|S specific hardware so there is no extra CPU, GPU, memory, bandwidth or latency. The visual enhancement doesn't change the original artistic intent and expands brightness up to 1000 nits and colors into the P3-D65 color space. A native HDR implementation will always be better, allowing full artistic control, but if you don't have the resources or time to implement native HDR, AutoHDR is an easy and effective way to achieve an enhanced experience.

```cpp theme={null}
// Try to switch the display into HDR mode
auto result = XDisplayTryEnableHdrMode(XDisplayHdrModePreference::PreferHdr, nullptr);

if (result == XDisplayHdrModeResult::Enabled)
{
   // Specify the Auto HDR flag during D3D device creation
   params.CreateDeviceFlags = D3D12XBOX_CREATE_DEVICE_FLAG_ENABLE_AUTO_HDR;
}

// Create the D3D device
HRESULT hr = D3D12XboxCreateDevice(...);
```

See High dynamic range (HDR) output and the *AutoHDR* sample for more details.

* **Aniso Boost**: An improvement in image quality on XBOX Series X|S consoles is given by promoting linear texture filtering to full anisotropic filtering. This is a quick & easy way to apply extra GPU power to an existing game title. As a Microsoft Game Development Kit (GDK) on XBOX title, you achieve this by using the `D3D12_FILTER_ANISOTROPIC` setting for your sampler states instead of `D3D12_FILTER_MIN_MAG_MIP_LINEAR` when running on XBOX Series X|S:

```cpp theme={null}
D3D12_SAMPLER_DESC desc = { D3D12_FILTER_ANISOTROPIC,
    D3D12_TEXTURE_ADDRESS_MODE_WRAP,
    D3D12_TEXTURE_ADDRESS_MODE_WRAP,
    D3D12_TEXTURE_ADDRESS_MODE_WRAP,
    0, D3D12_MAX_MAXANISOTROPY, D3D12_COMPARISON_FUNC_NEVER,
    { 0, 0, 0, 0 }, 0, D3D12_FLOAT32_MAX };

D3D12_SAMPLER_DESC desc = { D3D12_FILTER_ANISOTROPIC,
    D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
    D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
    D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
    0, D3D12_MAX_MAXANISOTROPY, D3D12_COMPARISON_FUNC_NEVER,
    { 0, 0, 0, 0 }, 0, D3D12_FLOAT32_MAX };
```

* **FPS Boost**: Another simple improvement is increasing the render framerate on XBOX Series X|S consoles. If your title runs at 30 fps on XBOX One S / XBOX One X (`D3D12XBOX_FRAME_INTERVAL_30_HZ`), then it can usually run at 60 fps on XBOX Series X|S (`D3D12XBOX_FRAME_INTERVAL_60_HZ`). If it's running 60 fps on XBOX One S/X, then it can likely run at 120 fps on XBOX Series X|S. See 120Hz Support and the Simple120Hz sample for more information.

> In addition to frame-rate boost, you can likely also render at 4K on XBOX One X and XBOX Series X at the same performance that you can at 1080p on XBOX One S / XBOX Series S.

* **Quick Resume**: This feature is automatic for the most part, as long as your title properly implements Process Lifecycle Management (PLM). See [XBOX Game Life Cycle](/ja-jp/build/console-features/console-workflows/xbox-game-life-cycle) for more details.

<a id="tips" />

## ヒントとコツ

### Microsoft Game Config packaging file

The Microsoft Game Development Kit (GDK) no longer uses a `Package.appxmanifest` file during the Visual Studio build toolchain to generate `AppxManifest.xml`. Instead, a MicrosoftGameConfig file is used to house all app package settings at development time.

```xml theme={null}
<?xml version="1.0" encoding="utf-8"?>
<Game configVersion="1">

  <Identity Name="<project identifier or name>"
            Publisher="CN=<Publisher>"
            Version="1.0.0.0"/>

  <ExecutableList>
    <Executable Name="<name of title>.exe"
                Id="Game"/>
  </ExecutableList>

</Game>
```

The `Executable Name` element must match the name of the EXE in the package layout.

> Note you can create a new project by using Visual Studio. Select **File**, **New Project**, and then select the Direct3D 12 XBOX Game template from the Microsoft Game Development Kit (GDK). You can then add `MicrosoftGame.config` that was created by the template to your project.

As an option, you can add the various UI and Store-related assets, which need to be present in the package, by adding a `<ShellVisuals>` section.

```xml theme={null}
  <ShellVisuals DefaultDisplayName="<name of title>"
                PublisherDisplayName="<publisher name>"
                StoreLogo="StoreLogo.png"
                Square150x150Logo="Logo.png"
                Square44x44Logo="SmallLogo.png"
                Square480x480Logo="LargeLogo.png"
                Description="<desc of title>"
                ForegroundText="light"
                BackgroundColor="#464646"
                SplashScreenImage="SplashScreen.png"/>
```

> Note that the XBOX One Software Development Kit had a `WideLogo` element, this is now referenced as the Square480x480Logo attribute.

For XBOX services integration, you also need to provide a Title ID.

```xml theme={null}
    <TitleId>hex-number</TitleId>
```

As noted above, you no longer need to use manifest elements to get 7th core and extended GPU resource availability, but you can use the manifest to control title memory.

```xml theme={null}
    <mx:Extension Category="xbox.system.resources">
        <mx:XboxSystemResources resourceConfiguration="extended">
          <mx:GpuAvailability>variable</mx:GpuAvailability>
          <mx:TitleMemory ConsoleType="Xbox_One_X" Size="9"/>
        </mx:XboxSystemResources>
    </mx:Extension>
```

The appxmanifest element above has been replaced by an element which defaults to "Standard" for the title memory control.

```xml theme={null}
    <VirtualMachine>
      <XboxOneXTitleMemory>Advanced</XboxOneXTitleMemory>
    </VirtualMachine>
```

Some manifest extensions from the XBOX One Software Development Kit can also be transferred into the `.config` file. For a full definition of allowable options, see MicrosoftGameConfig file.

### Getting the device type

The **GetConsoleType** method in the XBOX One Software Development Kit isn't available for the Microsoft Game Development Kit (GDK). Use the GameRuntime API **XSystemGetDeviceType** instead.

```cpp theme={null}
#include <XSystem.h>

XSystemDeviceType deviceType = XSystemGetDeviceType();

switch (deviceType)
{
case XSystemDeviceType::Pc:                     ... break;
case XSystemDeviceType::XboxOne:                ... break;
case XSystemDeviceType::XboxOneS:               ... break;
case XSystemDeviceType::XboxOneX:               ... break;
case XSystemDeviceType::XboxOneXDevkit:         ... break;
case XSystemDeviceType::XboxScarlettLockhart: /* Xbox Series S */ ... break;
case XSystemDeviceType::XboxScarlettAnaconda: /* Xbox Series X */ ... break;
case XSystemDeviceType::XboxScarlettDevkit:     ... break;
case XSystemDeviceType::Unknown:                ... break;
}
```

### GDK replacement for xdk.h and `_XDK_VER`

In the XBOX One Software Development Kit, the `xdk.h` header provided a number of build symbols related to the XDK build number, QFE level, etc.

For `Gaming.*.x64` platforms, you can make use of `grdk.h`:

* `_GRDK_VER` is the version encoding of the Gaming GDK used to build the binary (HIWORD.LOWORD). For example, `0x4A610479` is build number 19041.1145.
* `_GRDK_VER_STRING` for this build is "April 2020 GRDK".
* `_GRDK_VER_STRING_W` UTF16-LE wide string equivalent to `_GRDK_VER_STRING`.
* `_GRDK_VER_STRING_COMPACT_W` for that build is a UTF16-LE wide string containing "April 2020".

For `Gaming.Xbox.*.x64` platforms, you can also make use of `gxdk.h`:

* `_GXDK_VER` is the version encoding of the Gaming GDK used to build the binary (HIWORD.LOWORD). For example, `0x4A610479` is build number 19041.1145.
* `_GXDK_VER_STRING` for this build is "April 2020 GXDK".
* `_GXDK_VER_STRING_W` UTF16-LE wide string equivalent to `_GXDK_VER_STRING`.
* `_GXDK_VER_STRING_COMPACT_W` for that build is a UTF16-LE wide string containing "April 2020".

### Getting the default audio rendering endpoint ID

The Windows Runtime APIs Windows.Media.Devices and Windows.Devices.Enumeration aren't used for the Microsoft Game Development Kit (GDK) on Xbox. To obtain the default renderer, use the following code.

```cpp theme={null}
#include <mmdeviceapi.h>

ComPtr<IMMDeviceEnumerator> devEnum;
hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(devEnum.GetAddressOf()));
// Check hr for errors

ComPtr<IMMDeviceCollection> devices;
hr = devEnum->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &devices);
// Check hr for errors

ComPtr<IMMDevice> endpoint;
hr = devices->Item(0, endpoint.GetAddressOf();
// Check hr for errors

LPWSTR id = nullptr;
hr = endpoint->GetId(&id);
// Check hr for errors

// The id variable contains the device identifier used by XAudio2

CoTaskMemFree(id);
```

### MapVirtualKey

The `MapVirtualKey` and `MapVirtualKeyEx` methods aren't supported for the Microsoft Game Development Kit (GDK) on Xbox. Most commonly, they're used to detect the left and right `VK_SHIFT` keys in the code that handles the keyboard.

```cpp theme={null}
int vk = static_cast<int>(wParam);
switch (vk)
{
    case VK_SHIFT:
    #if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_GAMES)
        vk = (((lParam & 0x00ff0000) >> 16) == 0x36) ? VK_RSHIFT : VK_LSHIFT;
    #else
        vk = MapVirtualKey((lParam & 0x00ff0000) >> 16, MAPVK_VSC_TO_VK_EX);
    #endif
        break;

    case VK_CONTROL:
        vk = (lParam & 0x01000000) ? VK_RCONTROL : VK_LCONTROL;
        break;

    case VK_MENU:
        vk = (lParam & 0x01000000) ? VK_RMENU : VK_LMENU;
        break;
}
```

### MultiByteToWideChar and WideCharToMultiByte

When converting between wide-character strings (UTF-16 LE) and narrow-character strings, Win32 developers often use [MultiByteToWideChar](https://learn.microsoft.com/windows/desktop/api/stringapiset/nf-stringapiset-multibytetowidechar) and [WideCharToMultiByte](https://learn.microsoft.com/windows/desktop/api/stringapiset/nf-stringapiset-widechartomultibyte). For modern codebases, we recommend that you use `CP_UTF8` instead of a specific code page or `CP_ACP`.

The following code works on Windows 7 Service Pack 1 and later.

```cpp theme={null}
// Name is a char array as input.
wchar_t wname[MAX_PATH] = {};
int result = MultiByteToWideChar(CP_UTF8, 0, name, -1, wname, MAX_PATH);
if (result <= 0) // Error
```

Sometimes 437 and 1252 are used directly. 437 isn't supported for the XBOX One Software Development Kit or for the Microsoft Game Development Kit (GDK) on Xbox. 1252 worked on the XBOX One XDK but isn't supported for the Microsoft Game Development Kit (GDK) on Xbox. For the Microsoft Game Development Kit (GDK) on XBOX, `CP_ACP` is treated as an alias for `CP_UTF8`. On modern Windows 10 and with the Microsoft Game Development Kit (GDK), you can usually replace all instances of `CP_ACP` with `CP_UTF8` by using find and replace. To simplify this kind of porting, the validation of other `CP_UTF8`-related parameters was removed.

C++11 added the `<codecvt>` header as a more portable solution to the problem of converting strings, but this has already been deprecated in C++17. The recommendation is to stick with platform string functions.

### Localization and globalization APIs

In ERA, the majority of built-in Windows support for localization beyond simple code-page selection, codepoint translation (the conversion of multibyte to widechar), and system/user locale reporting was missing. For the Microsoft Game Development Kit (GDK), this localization functionality is fully supported, as are `GetCurrencyFormatEx`, `GetNumberFormatEx`, the date and time format enumeration, and other features.

### XMA2 audio notes

If you're missing the definition of `SHAPE_XMA_INPUT_BUFFER_ALIGNMENT`, you'll have to explicitly add a reference to the shapexmacontext.h header.

```cpp theme={null}
#include <shapexmacontext.h>
```

With the XBOX One Software Development Kit, this header was implicitly included by some other audio headers.

### UI message box support

To help improve debugging of crashes and early initialization failures within a title, `XGameUiShowMessageDialogAsync` has been added to the collection of title-callable UI (TCUI) APIs. This API can be used at any point after XGameRuntimeInitialize has been called, even before D3D initialization. The API renders within the system partition and is composited over the game's output. It still functions even if the game loop is halted or not yet rendering. This can be highly useful for reporting crashing error information, or even for prompting for debugger attach while blocking at the site of the error. It's intended primarily as a development-time diagnostic tool.

This example shows a blocking style error dialog, prompting for the developer to attach for investigation.

```cpp theme={null}
XTaskQueueHandle queue;
ThrowIfFailed(
    XTaskQueueCreate(XTaskQueueDispatchMode::ThreadPool, XTaskQueueDispatchMode::Immediate, &queue)
);

XAsyncBlock* ab = new XAsyncBlock;
ZeroMemory(ab, sizeof(XAsyncBlock));
ab->queue = queue;

// Show dialog, wait for completion, get result.

XGameUiMessageDialogButton button;
if (SUCCEEDED(XGameUiShowMessageDialogAsync(ab, u8"This is a title", u8"This is content text", u8"Option #1", u8"Option #2", u8"Option #3", XGameUiMessageDialogButton::First, XGameUiMessageDialogButton::Third)) &&
    SUCCEEDED(XAsyncGetStatus(ab, true)) &&
    SUCCEEDED(XGameUiShowMessageDialogResult(ab, &button)))
{
    DoSomethingWithResponse(button);
}
```

### Extension libraries

In the XBOX One Software Development Kit with the use of Windows Runtime APIs, adding extension libraries like XSAPI or Game Chat required using the 'References...' dialog in Visual Studio. For Microsoft Game Development Kit (GDK) this mechanism is no longer used. Instead these can be added via the Visual Studio project properties. This edits a property element in the Globals section of the `vcxproj`:

```text theme={null}
<PropertyGroup Label="Globals">
    <GDKExtLibNames>Xbox.Game.Chat.2.Cpp.API;Xbox.Services.API.C</GDKExtLibNames>
</PropertyGroup>
```

If this element is not present, the default is to include only XSAPI.

<a id="bincompat" />

## バイナリ互換性とコンポーネントの再利用

One of the guiding principles of the Microsoft Game Development Kit (GDK) is maximizing developers' ability to reuse their work between desktop Windows and XBOX console titles. One aspect of this not previously discussed is that work has been done to improve binary compatibility between desktop Windows and the Microsoft Game Development Kit (GDK) on XBOX OS.

Unlike XBOX One Software Development Kit titles, Microsoft Game Development Kit (GDK) on XBOX can reuse a variety of components that were originally built for x64 desktop Windows. This can be a valuable time-saving feature for prototyping, tooling, or other scenarios that aren't performance-critical.

There is no tooling in the Microsoft Game Development Kit (GDK) to determine whether a desktop Windows component can be reused, but it's determined by the operating system APIs that are consumed by the component in question.

The supported APIs of the Microsoft Game Development Kit (GDK) on XBOX OS can be obtained by running `dumpbin.exe /exports` on the libs that ship with the Microsoft Game Development Kit (GDK). While some area-specific APIs reside in their own libs (such as D3D12XboxCreateDevice within `d3d12_x.lib` or `d3d12_xs.lib`), the majority of legacy Win32 APIs are aggregated in a single library named `xgameplatform.lib`. The following command, when run from a Visual Studio Developer Command Prompt, shows the main pool of supported Win32 APIs (aside from those that reside in another import lib).

`dumpbin.exe /exports "c:\Program Files (x86)\Microsoft GDK\build_number\GXDK\gameKit\lib\amd64\xgameplatform.lib"`

<Note>
  In the example path above, *build\_number* represents the build installed on your system (e.g. 190700).
</Note>

Static libraries originally built for desktop Windows, which only make use of APIs within the approved list, can generally be linked directly into a Microsoft Game Development Kit (GDK) binary intended for Xbox. However, this isn't universally true, as behavior differences (such as the single window limitation) may cause runtime failures of the component if it hasn't been designed to handle such differences.

Dynamic-link libraries (DLLs) that have an import list that falls entirely within the supported APIs will also generally load and function as-is. The Microsoft Game Development Kit (GDK) on XBOX OS contains forwarding logic to correctly retarget this set of APIs to their implementation locations if different from desktop Windows.

While being able to reuse desktop Windows components on the console can save time in many scenarios, this isn't advised for performance-critical paths within a shipping title. Most components built with desktop Windows in mind will not have been built with the most optimal flags for execution with the Microsoft Game Development Kit (GDK). Most notably, because desktop components target a broader range of CPUs, those components may have been built without AVX optimizations. Reusing desktop DLLs may also lead to larger overall code size, compared with rebuilding for the Microsoft Game Development Kit (GDK).

<a id="codingstyle" />

## コーディング スタイルとベスト プラクティス

The guidance in Code Generation for XBOX One - Best Practices [(XBOX Developer Downloads->XBOX One->All XBOX One XDK CHMs)](https://aka.ms/gdkdl) applies to the Microsoft Game Development Kit (GDK). The primary difference in compiler settings is that these projects don't require the use of C++/CX (`/ZW`) or C++/WinRT, because most game APIs are styled as Win32 or DirectX-style COM. Here are some general recommendations:

* Take advantage of C++14 and, optionally, of C++17 language conformance. Note that the API design for the Microsoft Game Development Kit (GDK) assumes a C++11 or better compiler.
* The process for generating x64-native, floating-point code always uses SSE/SSE2. XBOX One supports `/arch:AVX` as well as F16C.
* C++ Exception Handling (`/EHsc`) has little to no overhead in x64-native code. Throwing of exceptions at runtime, however, isn't a performance scenario, so it shouldn't be used to control the flow.
* The use of exception-safe coding techniques like those described in [Objects Own Resources (RAII)](https://learn.microsoft.com/cpp/cpp/objects-own-resources-raii) and [Resource Acquisition Is Initialization](https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization) is a strongly recommended best practice using `std::unique_ptr`, `Microsoft::WRL::ComPtr`, and other smart-pointer classes.
* Give preference to the use of standard portable types like `size_t`, `ptrdiff_t`, `int8_t`, `uint8_t`, `int16_t`, `uint16_t`, `int32_t`, `uint32_t`, `int64_t`, `uint64_t`, `intptr_t`, and `uintptr_t`.
* To minimize internal padding, group pointers into structures and classes.
* Instead of legacy C-style casting, give preference to C++ casts like `const_cast<>`, `static_cast<>`, `reinterpret_cast<>`, and `dynamic_cast<>`.
* Use intrinsics where possible. x64-native code doesn't support inline assembly.

### Compiler and linker switches

Use the following switches:

* `/O1 /Oi` for general optimization and `/O2` for hot modules
* `/fp:fast`
* `/arch:AVX` for the XBOX One family of devices; `/arch:AVX2` for XBOX Series X|S.
* `/favor:AMD`
* Whole Program Optimization and Profile-guided Optimization
* `/OPT:REF,ICF` linker switches

For historical reasons, `/Ox` is almost the same as `/O2` but is missing both `/GF` (Eliminate Duplicate Strings) and `/Gy` (Enable Function-Level Linking). Give preference to `/O2` over `/Ox`. If you use `/Ox`, be sure to explicitly enable at least `/Gy`, which is important for enabling linker optimization.

There have also been a number of new compiler switches added to Visual C++ since the launch of the XBOX One Software Development Kit, so be sure to read up on them: `/Zc:inline`, [/Zc:throwingNew](https://blogs.msdn.com/b/vcblog/archive/2015/08/06/new-in-vs-2015-zc-throwingnew.aspx), [/Zc:\_\_cplusplus](https://blogs.msdn.microsoft.com/vcblog/2018/04/09/msvc-now-correctly-reports-__cplusplus/), `/volatile:iso`, [/permissive-](https://blogs.msdn.microsoft.com/vcblog/2016/11/16/permissive-switch/), [/Zc:twoPhase-](https://blogs.msdn.microsoft.com/vcblog/2017/09/11/two-phase-name-lookup-support-comes-to-msvc/), and [/Debug:FASTLINK](https://blogs.msdn.microsoft.com/vcblog/2015/10/16/debugfastlink-for-vs2015-update-1/).

### Conditional code

For conditional code where paths diverge, keep the following conventions in mind.

| Platform | Conditional compilation |
| - | - |
| Win32 desktop development | `#if !defined(WINAPI_FAMILY) \|\| (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP)` |
| XBOX One Software Development Kit | `#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_TV_TITLE)` <br /> -or- <br /> `#if defined(_XBOX_ONE) && defined(_TITLE)` |
| Microsoft Game Development Kit (GDK) on XBOX One or XBOX Series X\|S | `#ifdef _GAMING_XBOX` |
| Microsoft Game Development Kit (GDK) on XBOX One only | `#ifdef _GAMING_XBOX_XBOXONE` |
| Microsoft Game Development Kit (GDK) on XBOX Series X\|S only | `#ifdef _GAMING_XBOX_SCARLETT` |

If your codebase already supports the XBOX One Software Development Kit, a good place to start is to do the following:

1. Search for all instances of `_XBOX_ONE` in your codebase
2. Change instances like `#if defined(_XBOX_ONE) && defined(_TITLE)` where the code is using DirectX 12.X extensions, and making these cases: <br /> `#if (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX)`

### UTF-8 everywhere

In the long history of the Windows platform, the original ANSI functions have long been deprecated in favor of the wide-character Unicode solution, also known as CreateFileW rather than CreateFileA. This resolved the problem of dealing with a myriad of different code pages and simplified all localizable strings to `wchar_t*` (UTF-16 LE, little endian). The [UTF-8 Everywhere manifesto](https://utf8everywhere.org/) makes the case that the UTF-8 multibyte encoding with `char*` is a better solution in terms of memory footprint and portability.

For the Microsoft Game Development Kit (GDK) on XBOX platform, the default code page is set to `CP_UTF8`, so any ANSI versions of Win32 platform APIs use UTF-8. You can continue to use the wide-character APIs with UTF-16 LE, but you also have the option to use UTF-8.

<Note>
  Full UTF-8 support for Windows is a very recent addition, so it's not yet widely used. It's also something that a user has to opt in for at this time, so you might find that keeping your low-level use of Win32 APIs to the wide-character APIs is the best option for portability.
</Note>

We recommend the following:

* Give preference to the use of UTF-8 in your APIs, and convert to UTF-16 LE only when calling Win32 wide-character APIs. Instead of using `std::wstring` and `wchar_t*`, use `std::string` and `char*` as UTF-8.
* For narrow string literals, ensure adherence to UTF-8 by using the C++ prefix `u8` rather than no prefix or `L`.
* Keep the `UNICODE` and `_UNICODE` build preprocessor `defines` that are in place (in Visual Studio, this is the `<CharSet>` property) as a safety measure, but instead of relying on the macros, always explicitly call the `W()` or `A()` version.
* Avoid `TCHAR`, `TEXT()`, `LPTSTR`, and other legacy text types and macros. For more information, see UTF-8 support in the Microsoft Game Development Kit (GDK).

### Naming convention: performance and behavioral hints

The APIs for the Microsoft Game Development Kit (GDK) on XBOX platform have been designed for the purpose of having function names make implicit statements about the performance of functions that are called.

A function that includes the phrase `Get` or `Set` in its name is expected to be low-overhead and predictable. It's also expected to have roughly the same level of performance as if called in place of a C++ property-wrapper function with any `memcpy` operation for copying the result. If a function were to use `Query` rather than `Get`, this would imply that it's a long-running operation that might block until it's completed.

For functions that perform calculations rather than simple queries, we usually assume that performance is roughly what you'd expect after inspecting their input parameters and the kinds of operations they perform, unless the documentation states otherwise.

A function whose name ends in `Async` is an asynchronous operation and could take a very long or an indeterminate amount of time to complete. In most cases, we provide blocking and asynchronous versions of functions that can take a long time to execute. We let you decide which variety works best for your codebase. In some cases (as with network APIs), we might omit the blocking version entirely, because providing one would make no sense.

If a function's name begins with `Show` and ends with `Async`, the function displays UI affordances and, to return, typically requires interaction from the user. In some cases, the system can cancel UI operations.

<a id="seealso" />

## 関連項目

* What is the Microsoft Game Development Kit?
* Getting started with the Microsoft Game Development Kit (GDK)


## Related topics

- [XBOX Series X|S および XBOX One 向けに Visual Studio を構成する](/ja-jp/tools/tools-console/visualstudio/vs-cross-gen.md)
- [XBOX One Software Development Kit 移行ガイド](/ja-jp/build/console-features/networking/xdk-migration/xdk-migration-toc.md)
- [XBOX GDK への移植ガイド](/ja-jp/home/build-first-title/porting-guides.md)
- [Steam 移植ガイド概要](/ja-jp/build/steam-porting-guide/overview.md)
- [一般的な移植ガイド](/ja-jp/paths/porting/guides.md)
