From 7e8019ba4e25e96a12e586e38ffa5f8a0ce63a8d Mon Sep 17 00:00:00 2001 From: Liu Chao Date: Sun, 2 Jul 2017 20:11:38 +0800 Subject: [PATCH] Add Universal Windows Platform (UWP) support code --- .gitignore | 2 + build/windows/LCUI.sln | 14 + build/windows/LCUIUWP/LCUIUWP.vcxproj | 23 +- build/windows/LCUIUWP/LCUIUWP.vcxproj.filters | 12 + build/windows/LCUIUWPApp/LCUIUWPApp.vcxproj | 264 +++++++ .../LCUIUWPApp/LCUIUWPApp.vcxproj.filters | 69 ++ include/LCUI/platform.h | 6 +- include/LCUI/platform/windows/uwp.h | 14 + src/main.c | 8 + .../windows/Common/DeviceResources.cpp | 702 ++++++++++++++++++ src/platform/windows/Common/DeviceResources.h | 102 +++ src/platform/windows/Common/DirectXHelper.h | 63 ++ src/platform/windows/Common/StepTimer.h | 183 +++++ src/platform/windows/pch.cpp | 1 + src/platform/windows/pch.h | 17 + src/platform/windows/uwp_app.cpp | 384 ++++++++++ src/platform/windows/uwp_app.h | 96 +++ src/platform/windows/uwp_input.cpp | 310 ++++++++ src/platform/windows/uwp_input.h | 68 ++ src/platform/windows/uwp_main.cpp | 124 ++++ src/platform/windows/uwp_main.h | 67 ++ src/platform/windows/uwp_renderer.cpp | 297 ++++++++ src/platform/windows/uwp_renderer.h | 70 ++ 23 files changed, 2886 insertions(+), 10 deletions(-) create mode 100644 build/windows/LCUIUWPApp/LCUIUWPApp.vcxproj create mode 100644 build/windows/LCUIUWPApp/LCUIUWPApp.vcxproj.filters create mode 100644 include/LCUI/platform/windows/uwp.h create mode 100644 src/platform/windows/Common/DeviceResources.cpp create mode 100644 src/platform/windows/Common/DeviceResources.h create mode 100644 src/platform/windows/Common/DirectXHelper.h create mode 100644 src/platform/windows/Common/StepTimer.h create mode 100644 src/platform/windows/pch.cpp create mode 100644 src/platform/windows/pch.h create mode 100644 src/platform/windows/uwp_app.cpp create mode 100644 src/platform/windows/uwp_app.h create mode 100644 src/platform/windows/uwp_input.cpp create mode 100644 src/platform/windows/uwp_input.h create mode 100644 src/platform/windows/uwp_main.cpp create mode 100644 src/platform/windows/uwp_main.h create mode 100644 src/platform/windows/uwp_renderer.cpp create mode 100644 src/platform/windows/uwp_renderer.h diff --git a/.gitignore b/.gitignore index 3c3e4063..a16af50e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ *.lo *.o +*.dll +*.lib *.db *.opendb *.dirstamp diff --git a/build/windows/LCUI.sln b/build/windows/LCUI.sln index cc5598fe..a31e3896 100644 --- a/build/windows/LCUI.sln +++ b/build/windows/LCUI.sln @@ -12,6 +12,8 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LCUIMain", "LCUIMain\LCUIMa {1B527CF3-CF0E-482A-BA63-1AF04AB8F4E9} = {1B527CF3-CF0E-482A-BA63-1AF04AB8F4E9} EndProjectSection EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LCUIUWPApp", "LCUIUWPApp\LCUIUWPApp.vcxproj", "{6BA8BA7C-5D52-4926-BE88-B8EAA02B87D7}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|ARM = Debug|ARM @@ -54,6 +56,18 @@ Global {41884B84-1C73-418E-A572-0B4A27866BB2}.Release|Win32.Build.0 = Release|Win32 {41884B84-1C73-418E-A572-0B4A27866BB2}.Release|x64.ActiveCfg = Release|x64 {41884B84-1C73-418E-A572-0B4A27866BB2}.Release|x64.Build.0 = Release|x64 + {6BA8BA7C-5D52-4926-BE88-B8EAA02B87D7}.Debug|ARM.ActiveCfg = Debug|ARM + {6BA8BA7C-5D52-4926-BE88-B8EAA02B87D7}.Debug|ARM.Build.0 = Debug|ARM + {6BA8BA7C-5D52-4926-BE88-B8EAA02B87D7}.Debug|Win32.ActiveCfg = Debug|Win32 + {6BA8BA7C-5D52-4926-BE88-B8EAA02B87D7}.Debug|Win32.Build.0 = Debug|Win32 + {6BA8BA7C-5D52-4926-BE88-B8EAA02B87D7}.Debug|x64.ActiveCfg = Debug|x64 + {6BA8BA7C-5D52-4926-BE88-B8EAA02B87D7}.Debug|x64.Build.0 = Debug|x64 + {6BA8BA7C-5D52-4926-BE88-B8EAA02B87D7}.Release|ARM.ActiveCfg = Release|ARM + {6BA8BA7C-5D52-4926-BE88-B8EAA02B87D7}.Release|ARM.Build.0 = Release|ARM + {6BA8BA7C-5D52-4926-BE88-B8EAA02B87D7}.Release|Win32.ActiveCfg = Release|Win32 + {6BA8BA7C-5D52-4926-BE88-B8EAA02B87D7}.Release|Win32.Build.0 = Release|Win32 + {6BA8BA7C-5D52-4926-BE88-B8EAA02B87D7}.Release|x64.ActiveCfg = Release|x64 + {6BA8BA7C-5D52-4926-BE88-B8EAA02B87D7}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/build/windows/LCUIUWP/LCUIUWP.vcxproj b/build/windows/LCUIUWP/LCUIUWP.vcxproj index 8cbf8593..672205f9 100644 --- a/build/windows/LCUIUWP/LCUIUWP.vcxproj +++ b/build/windows/LCUIUWP/LCUIUWP.vcxproj @@ -98,9 +98,11 @@ + + @@ -109,9 +111,11 @@ + + @@ -254,16 +258,17 @@ NotUsing false _CRT_SECURE_NO_WARNINGS;LCUI_EXPORTS;_WINDLL;%(PreprocessorDefinitions) - $(SolutionDir)..\..\vendor\include;$(SolutionDir)..\..\include;%(AdditionalIncludeDirectories) + $(SolutionDir)..\..\src\platform\windows;$(SolutionDir)..\..\vendor\include;$(SolutionDir)..\..\include;%(AdditionalIncludeDirectories) Console - false + + false - kernel32.lib;freetype.lib;zlib.lib;libpng16.lib;jpeg.lib;libxml2.lib;WindowsApp.lib;%(AdditionalDependencies) + kernel32.lib;freetype.lib;zlib.lib;libpng16.lib;jpeg.lib;libxml2.lib;WindowsApp.lib;vccorlibd.lib;msvcrtd.lib;%(AdditionalDependencies) $(SolutionDir)..\..\vendor\lib\uwp;%(AdditionalLibraryDirectories) NotSet - MSVCRT + msvcrt;vccorlibd.lib;msvcrtd.lib @@ -271,16 +276,16 @@ NotUsing false _CRT_SECURE_NO_WARNINGS;LCUI_EXPORTS;_WINDLL;%(PreprocessorDefinitions) - $(SolutionDir)..\..\vendor\include;$(SolutionDir)..\..\include;%(AdditionalIncludeDirectories) + $(SolutionDir)..\..\src\platform\windows;$(SolutionDir)..\..\vendor\include;$(SolutionDir)..\..\include;%(AdditionalIncludeDirectories) Console - false + + false - kernel32.lib;freetype.lib;zlib.lib;libpng16.lib;jpeg.lib;libxml2.lib;WindowsApp.lib;%(AdditionalDependencies) + kernel32.lib;freetype.lib;zlib.lib;libpng16.lib;jpeg.lib;libxml2.lib;vccorlibd.lib;msvcrt.lib;WindowsApp.lib;%(AdditionalDependencies) $(SolutionDir)..\..\vendor\lib\uwp;%(AdditionalLibraryDirectories) - - + vccorlib;msvcrt;msvcrtd diff --git a/build/windows/LCUIUWP/LCUIUWP.vcxproj.filters b/build/windows/LCUIUWP/LCUIUWP.vcxproj.filters index bb6b3a29..d273c3fc 100644 --- a/build/windows/LCUIUWP/LCUIUWP.vcxproj.filters +++ b/build/windows/LCUIUWP/LCUIUWP.vcxproj.filters @@ -395,5 +395,17 @@ 源文件\gui + + 源文件\gui + + + 源文件\gui + + + 源文件\gui + + + 源文件\gui + \ No newline at end of file diff --git a/build/windows/LCUIUWPApp/LCUIUWPApp.vcxproj b/build/windows/LCUIUWPApp/LCUIUWPApp.vcxproj new file mode 100644 index 00000000..d09f3a96 --- /dev/null +++ b/build/windows/LCUIUWPApp/LCUIUWPApp.vcxproj @@ -0,0 +1,264 @@ + + + + + Debug + ARM + + + Debug + Win32 + + + Debug + x64 + + + Release + ARM + + + Release + Win32 + + + Release + x64 + + + + + + + + + + + + + + + Use + CompileAsCpp + true + CompileAsCpp + true + + + CompileAsCpp + true + Create + + + CompileAsCpp + true + Use + CompileAsCpp + true + + + CompileAsCpp + true + Use + CompileAsCpp + true + + + CompileAsCpp + true + Use + CompileAsCpp + true + + + CompileAsCpp + true + Use + CompileAsCpp + true + + + + {6BA8BA7C-5D52-4926-BE88-B8EAA02B87D7} + DynamicLibrary + LCUIUWP + zh-CN + 14.0 + true + Windows Store + 10.0.14393.0 + 10.0.10586.0 + 10.0 + + + + DynamicLibrary + true + v141 + + + DynamicLibrary + true + v141 + + + DynamicLibrary + true + v141 + + + DynamicLibrary + false + true + v141 + + + DynamicLibrary + false + true + v141 + + + DynamicLibrary + false + true + v141 + + + + + + + + + + + + + + + + + + + + + + + + + + + + false + false + LCUIApp + $(SolutionDir)..\..\bin\$(Configuration)\uwp\ + $(ProjectDir)\$(Configuration)\ + + + false + false + LCUIApp + $(SolutionDir)..\..\bin\$(Configuration)\uwp\ + $(ProjectDir)\$(Configuration)\ + + + false + false + + + false + false + + + false + false + + + false + false + + + + Use + true + _CRT_SECURE_NO_WARNINGS;LCUI_EXPORTS;_WINDLL;%(PreprocessorDefinitions) + $(SolutionDir)..\..\src\platform\windows;$(SolutionDir)..\..\vendor\include;$(SolutionDir)..\..\include;%(AdditionalIncludeDirectories) + + + Console + + + false + LCUI.lib;WindowsApp.lib;vccorlibd.lib;msvcrtd.lib;%(AdditionalDependencies) + $(OutDir);%(AdditionalLibraryDirectories) + NotSet + msvcrt;vccorlibd.lib;msvcrtd.lib + + + + + Use + true + _CRT_SECURE_NO_WARNINGS;LCUI_EXPORTS;_WINDLL;%(PreprocessorDefinitions) + $(SolutionDir)..\..\src\platform\windows;$(SolutionDir)..\..\vendor\include;$(SolutionDir)..\..\include;%(AdditionalIncludeDirectories) + + + Console + + + false + LCUI.lib;vccorlibd.lib;msvcrt.lib;WindowsApp.lib;%(AdditionalDependencies) + $(OutDir);%(AdditionalLibraryDirectories) + vccorlib;msvcrt;msvcrtd + + + + + Use + false + + + Console + false + false + + + + + Use + false + + + Console + false + false + + + + + Use + false + + + Console + false + false + + + + + Use + false + + + Console + false + false + + + + + + \ No newline at end of file diff --git a/build/windows/LCUIUWPApp/LCUIUWPApp.vcxproj.filters b/build/windows/LCUIUWPApp/LCUIUWPApp.vcxproj.filters new file mode 100644 index 00000000..1d9c3b27 --- /dev/null +++ b/build/windows/LCUIUWPApp/LCUIUWPApp.vcxproj.filters @@ -0,0 +1,69 @@ + + + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + {55f58a5e-9a60-4e9d-b65e-7377c4486a7f} + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {75bc899d-297d-4a47-912c-e7b4e424f07f} + + + + + 源文件\Common + + + 源文件\Common + + + 源文件\Common + + + 源文件 + + + 源文件 + + + 源文件 + + + 源文件 + + + 源文件 + + + + + 源文件\Common + + + 源文件 + + + 源文件 + + + 源文件 + + + 源文件 + + + 源文件 + + + \ No newline at end of file diff --git a/include/LCUI/platform.h b/include/LCUI/platform.h index c9feb35d..39702c79 100644 --- a/include/LCUI/platform.h +++ b/include/LCUI/platform.h @@ -46,7 +46,7 @@ #define LCUI_DestroyAppDriver(X) NULL #define LCUI_PreInitApp() NULL #define LCUI_CreateDisplayDriver() NULL -#define LCUI_DestroyDisplayDriver() NULL +#define LCUI_DestroyDisplayDriver(X) NULL #define LCUI_InitMouseDriver() #define LCUI_ExitMouseDriver() #define LCUI_InitKeyboardDriver() @@ -62,10 +62,14 @@ #define LCUI_InitKeyboardDriver LCUI_InitWinKeyboard #define LCUI_ExitKeyboardDriver LCUI_ExitWinKeyboard #endif +#if defined(WINAPI_PARTITION_APP) +#define LCUI_APP_H +#else #define LCUI_EVENTS_H #define LCUI_MOUSE_H #define LCUI_KEYBOARD_H #define LCUI_DISPLAY_H +#endif #elif defined(LCUI_BUILD_IN_LINUX) #define LCUI_CreateAppDriver LCUI_CreateLinuxAppDriver #define LCUI_DestroyAppDriver LCUI_DestroyLinuxAppDriver diff --git a/include/LCUI/platform/windows/uwp.h b/include/LCUI/platform/windows/uwp.h new file mode 100644 index 00000000..4e11bb6e --- /dev/null +++ b/include/LCUI/platform/windows/uwp.h @@ -0,0 +1,14 @@ +#pragma once +namespace LCUI { + +class LCUI_API Application { +public: + Application(); + virtual void Load( Platform::String^ entryPoint ); + virtual void Run(); +}; + +LCUI_API void Initialize(); +LCUI_API void Run( Application &app ); + +}; diff --git a/src/main.c b/src/main.c index 8736fdf4..1dbd7ab9 100644 --- a/src/main.c +++ b/src/main.c @@ -51,10 +51,18 @@ #include #include #include +#ifdef LCUI_EVENTS_H #include LCUI_EVENTS_H +#endif +#ifdef LCUI_MOUSE_H #include LCUI_MOUSE_H +#endif +#ifdef LCUI_KEYBOARD_H #include LCUI_KEYBOARD_H +#endif +#ifdef LCUI_DISPLAY_H #include LCUI_DISPLAY_H +#endif #define STATE_ACTIVE 1 #define STATE_KILLED 0 diff --git a/src/platform/windows/Common/DeviceResources.cpp b/src/platform/windows/Common/DeviceResources.cpp new file mode 100644 index 00000000..333f03dc --- /dev/null +++ b/src/platform/windows/Common/DeviceResources.cpp @@ -0,0 +1,702 @@ +#include "pch.h" +#include "DeviceResources.h" +#include "DirectXHelper.h" + +using namespace D2D1; +using namespace DirectX; +using namespace Microsoft::WRL; +using namespace Windows::Foundation; +using namespace Windows::Graphics::Display; +using namespace Windows::UI::Core; +using namespace Windows::UI::Xaml::Controls; +using namespace Platform; + +namespace DisplayMetrics +{ + //高分辨率显示可能需要大量 GPU 和电量才能呈现。 + // 例如,出现以下情况时,高分辨率电话可能会缩短电池使用时间 + // 游戏尝试以全保真度按 60 帧/秒的速度呈现。 + // 跨所有平台和外形规格以全保真度呈现的决定 + // 应当审慎考虑。 + static const bool SupportHighResolutions = false; + + // 用于定义“高分辨率”显示的默认阈值,如果该阈值 + // 超出范围,并且 SupportHighResolutions 为 false,将缩放尺寸 + // 50%。 + static const float DpiThreshold = 192.0f; // 200% 标准桌面显示。 + static const float WidthThreshold = 1920.0f; // 1080p 宽。 + static const float HeightThreshold = 1080.0f; // 1080p 高。 +}; + +// 用于计算屏幕旋转的常量 +namespace ScreenRotation +{ + // 0 度 Z 旋转 + static const XMFLOAT4X4 Rotation0( + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f + ); + + // 90 度 Z 旋转 + static const XMFLOAT4X4 Rotation90( + 0.0f, 1.0f, 0.0f, 0.0f, + -1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f + ); + + // 180 度 Z 旋转 + static const XMFLOAT4X4 Rotation180( + -1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, -1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f + ); + + // 270 度 Z 旋转 + static const XMFLOAT4X4 Rotation270( + 0.0f, -1.0f, 0.0f, 0.0f, + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f + ); +}; + +// DeviceResources 的构造函数。 +DX::DeviceResources::DeviceResources() : + m_screenViewport(), + m_d3dFeatureLevel(D3D_FEATURE_LEVEL_9_1), + m_d3dRenderTargetSize(), + m_outputSize(), + m_logicalSize(), + m_nativeOrientation(DisplayOrientations::None), + m_currentOrientation(DisplayOrientations::None), + m_dpi(-1.0f), + m_effectiveDpi(-1.0f), + m_deviceNotify(nullptr) +{ + CreateDeviceIndependentResources(); + CreateDeviceResources(); +} + +// 配置不依赖于 Direct3D 设备的资源。 +void DX::DeviceResources::CreateDeviceIndependentResources() +{ + // 初始化 Direct2D 资源。 + D2D1_FACTORY_OPTIONS options; + ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS)); + +#if defined(_DEBUG) + // 如果项目处于调试生成阶段,请通过 SDK 层启用 Direct2D 调试。 + options.debugLevel = D2D1_DEBUG_LEVEL_INFORMATION; +#endif + + // 初始化 Direct2D 工厂。 + DX::ThrowIfFailed( + D2D1CreateFactory( + D2D1_FACTORY_TYPE_SINGLE_THREADED, + __uuidof(ID2D1Factory3), + &options, + &m_d2dFactory + ) + ); + + // 初始化 DirectWrite 工厂。 + DX::ThrowIfFailed( + DWriteCreateFactory( + DWRITE_FACTORY_TYPE_SHARED, + __uuidof(IDWriteFactory3), + &m_dwriteFactory + ) + ); + + // 初始化 Windows 图像处理组件(WIC)工厂。 + DX::ThrowIfFailed( + CoCreateInstance( + CLSID_WICImagingFactory2, + nullptr, + CLSCTX_INPROC_SERVER, + IID_PPV_ARGS(&m_wicFactory) + ) + ); +} + +// 配置 Direct3D 设备,并存储设备句柄和设备上下文。 +void DX::DeviceResources::CreateDeviceResources() +{ + // 此标志为颜色通道排序与 API 默认设置不同的图面 + // 添加支持。要与 Direct2D 兼容,必须满足此要求。 + UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; + +#if defined(_DEBUG) + if (DX::SdkLayersAvailable()) + { + // 如果项目处于调试生成过程中,请通过带有此标志的 SDK 层启用调试。 + creationFlags |= D3D11_CREATE_DEVICE_DEBUG; + } +#endif + + // 此数组定义此应用程序将支持的 DirectX 硬件功能级别组。 + // 请注意,应保留顺序。 + // 请不要忘记在应用程序的说明中声明其所需的 + // 最低功能级别。除非另行说明,否则假定所有应用程序均支持 9.1。 + D3D_FEATURE_LEVEL featureLevels[] = + { + D3D_FEATURE_LEVEL_12_1, + D3D_FEATURE_LEVEL_12_0, + D3D_FEATURE_LEVEL_11_1, + D3D_FEATURE_LEVEL_11_0, + D3D_FEATURE_LEVEL_10_1, + D3D_FEATURE_LEVEL_10_0, + D3D_FEATURE_LEVEL_9_3, + D3D_FEATURE_LEVEL_9_2, + D3D_FEATURE_LEVEL_9_1 + }; + + // 创建 Direct3D 11 API 设备对象和对应的上下文。 + ComPtr device; + ComPtr context; + + HRESULT hr = D3D11CreateDevice( + nullptr, // 指定 nullptr 以使用默认适配器。 + D3D_DRIVER_TYPE_HARDWARE, // 创建使用硬件图形驱动程序的设备。 + 0, // 应为 0,除非驱动程序是 D3D_DRIVER_TYPE_SOFTWARE。 + creationFlags, // 设置调试和 Direct2D 兼容性标志。 + featureLevels, // 此应用程序可以支持的功能级别的列表。 + ARRAYSIZE(featureLevels), // 上面的列表的大小。 + D3D11_SDK_VERSION, // 对于 Windows 应用商店应用,始终将此值设置为 D3D11_SDK_VERSION。 + &device, // 返回创建的 Direct3D 设备。 + &m_d3dFeatureLevel, // 返回所创建设备的功能级别。 + &context // 返回设备的即时上下文。 + ); + + if (FAILED(hr)) + { + // 如果初始化失败,则回退到 WARP 设备。 + // 有关 WARP 的详细信息,请参阅: + // http://go.microsoft.com/fwlink/?LinkId=286690 + DX::ThrowIfFailed( + D3D11CreateDevice( + nullptr, + D3D_DRIVER_TYPE_WARP, // 创建 WARP 设备而不是硬件设备。 + 0, + creationFlags, + featureLevels, + ARRAYSIZE(featureLevels), + D3D11_SDK_VERSION, + &device, + &m_d3dFeatureLevel, + &context + ) + ); + } + + // 将指针存储到 Direct3D 11.3 API 设备和即时上下文中。 + DX::ThrowIfFailed( + device.As(&m_d3dDevice) + ); + + DX::ThrowIfFailed( + context.As(&m_d3dContext) + ); + + // 创建 Direct2D 设备对象和对应的上下文。 + ComPtr dxgiDevice; + DX::ThrowIfFailed( + m_d3dDevice.As(&dxgiDevice) + ); + + DX::ThrowIfFailed( + m_d2dFactory->CreateDevice(dxgiDevice.Get(), &m_d2dDevice) + ); + + DX::ThrowIfFailed( + m_d2dDevice->CreateDeviceContext( + D2D1_DEVICE_CONTEXT_OPTIONS_NONE, + &m_d2dContext + ) + ); +} + +// 每次更改窗口大小时需要重新创建这些资源。 +void DX::DeviceResources::CreateWindowSizeDependentResources() +{ + // 清除特定于上一窗口大小的上下文。 + ID3D11RenderTargetView* nullViews[] = {nullptr}; + m_d3dContext->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr); + m_d3dRenderTargetView = nullptr; + m_d2dContext->SetTarget(nullptr); + m_d2dTargetBitmap = nullptr; + m_d3dDepthStencilView = nullptr; + m_d3dContext->Flush1(D3D11_CONTEXT_TYPE_ALL, nullptr); + + UpdateRenderTargetSize(); + + // 交换链的宽度和高度必须基于窗口的 + // 面向本机的宽度和高度。如果窗口不在本机 + // 方向,则必须使尺寸反转。 + DXGI_MODE_ROTATION displayRotation = ComputeDisplayRotation(); + + bool swapDimensions = displayRotation == DXGI_MODE_ROTATION_ROTATE90 || displayRotation == DXGI_MODE_ROTATION_ROTATE270; + m_d3dRenderTargetSize.Width = swapDimensions ? m_outputSize.Height : m_outputSize.Width; + m_d3dRenderTargetSize.Height = swapDimensions ? m_outputSize.Width : m_outputSize.Height; + + if (m_swapChain != nullptr) + { + // 如果交换链已存在,请调整其大小。 + HRESULT hr = m_swapChain->ResizeBuffers( + 2, // 双缓冲交换链。 + lround(m_d3dRenderTargetSize.Width), + lround(m_d3dRenderTargetSize.Height), + DXGI_FORMAT_B8G8R8A8_UNORM, + 0 + ); + + if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) + { + // 如果出于任何原因移除了设备,将需要创建一个新的设备和交换链。 + HandleDeviceLost(); + + // 现在一切都已设置完毕。不要继续执行此方法。HandleDeviceLost 将重新呈现此方法 + // 并正确设置新设备。 + return; + } + else + { + DX::ThrowIfFailed(hr); + } + } + else + { + // 否则,使用与现有 Direct3D 设备相同的适配器新建一个。 + DXGI_SCALING scaling = DisplayMetrics::SupportHighResolutions ? DXGI_SCALING_NONE : DXGI_SCALING_STRETCH; + DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0}; + + swapChainDesc.Width = lround(m_d3dRenderTargetSize.Width); // 匹配窗口的大小。 + swapChainDesc.Height = lround(m_d3dRenderTargetSize.Height); + swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; // 这是最常用的交换链格式。 + swapChainDesc.Stereo = false; + swapChainDesc.SampleDesc.Count = 1; // 请不要使用多采样。 + swapChainDesc.SampleDesc.Quality = 0; + swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; + swapChainDesc.BufferCount = 2; // 使用双缓冲最大程度地减小延迟。 + swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; // 所有 Windows 应用商店应用都必须使用此 SwapEffect。 + swapChainDesc.Flags = 0; + swapChainDesc.Scaling = scaling; + swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_IGNORE; + + // 此序列获取用来创建上面的 Direct3D 设备的 DXGI 工厂。 + ComPtr dxgiDevice; + DX::ThrowIfFailed( + m_d3dDevice.As(&dxgiDevice) + ); + + ComPtr dxgiAdapter; + DX::ThrowIfFailed( + dxgiDevice->GetAdapter(&dxgiAdapter) + ); + + ComPtr dxgiFactory; + DX::ThrowIfFailed( + dxgiAdapter->GetParent(IID_PPV_ARGS(&dxgiFactory)) + ); + + ComPtr swapChain; + DX::ThrowIfFailed( + dxgiFactory->CreateSwapChainForCoreWindow( + m_d3dDevice.Get(), + reinterpret_cast(m_window.Get()), + &swapChainDesc, + nullptr, + &swapChain + ) + ); + DX::ThrowIfFailed( + swapChain.As(&m_swapChain) + ); + + // 确保 DXGI 不会一次对多个帧排队。这样既可以减小延迟, + // 又可以确保应用程序将只在每个 VSync 之后渲染,从而最大程度地降低功率消耗。 + DX::ThrowIfFailed( + dxgiDevice->SetMaximumFrameLatency(1) + ); + } + + // 为交换链设置正确方向,并生成 2D 和 3D 矩阵 + // 转换以渲染到旋转交换链。 + // 请注意,2D 和 3D 转换的旋转角度不同。 + // 这是由坐标空间的差异引起的。此外, + // 显式指定 3D 矩阵可以避免舍入误差。 + + switch (displayRotation) + { + case DXGI_MODE_ROTATION_IDENTITY: + m_orientationTransform2D = Matrix3x2F::Identity(); + m_orientationTransform3D = ScreenRotation::Rotation0; + break; + + case DXGI_MODE_ROTATION_ROTATE90: + m_orientationTransform2D = + Matrix3x2F::Rotation(90.0f) * + Matrix3x2F::Translation(m_logicalSize.Height, 0.0f); + m_orientationTransform3D = ScreenRotation::Rotation270; + break; + + case DXGI_MODE_ROTATION_ROTATE180: + m_orientationTransform2D = + Matrix3x2F::Rotation(180.0f) * + Matrix3x2F::Translation(m_logicalSize.Width, m_logicalSize.Height); + m_orientationTransform3D = ScreenRotation::Rotation180; + break; + + case DXGI_MODE_ROTATION_ROTATE270: + m_orientationTransform2D = + Matrix3x2F::Rotation(270.0f) * + Matrix3x2F::Translation(0.0f, m_logicalSize.Width); + m_orientationTransform3D = ScreenRotation::Rotation90; + break; + + default: + throw ref new FailureException(); + } + + DX::ThrowIfFailed( + m_swapChain->SetRotation(displayRotation) + ); + + // 创建交换链后台缓冲区的渲染目标视图。 + ComPtr backBuffer; + DX::ThrowIfFailed( + m_swapChain->GetBuffer(0, IID_PPV_ARGS(&backBuffer)) + ); + + DX::ThrowIfFailed( + m_d3dDevice->CreateRenderTargetView1( + backBuffer.Get(), + nullptr, + &m_d3dRenderTargetView + ) + ); + + // 根据需要创建用于 3D 渲染的深度模具视图。 + CD3D11_TEXTURE2D_DESC1 depthStencilDesc( + DXGI_FORMAT_D24_UNORM_S8_UINT, + lround(m_d3dRenderTargetSize.Width), + lround(m_d3dRenderTargetSize.Height), + 1, // 此深度模具视图只有一个纹理。 + 1, // 使用单一 mipmap 级别。 + D3D11_BIND_DEPTH_STENCIL + ); + + ComPtr depthStencil; + DX::ThrowIfFailed( + m_d3dDevice->CreateTexture2D1( + &depthStencilDesc, + nullptr, + &depthStencil + ) + ); + + CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(D3D11_DSV_DIMENSION_TEXTURE2D); + DX::ThrowIfFailed( + m_d3dDevice->CreateDepthStencilView( + depthStencil.Get(), + &depthStencilViewDesc, + &m_d3dDepthStencilView + ) + ); + + // 设置用于确定整个窗口的 3D 渲染视区。 + m_screenViewport = CD3D11_VIEWPORT( + 0.0f, + 0.0f, + m_d3dRenderTargetSize.Width, + m_d3dRenderTargetSize.Height + ); + + m_d3dContext->RSSetViewports(1, &m_screenViewport); + + // 创建与交换链后台缓冲区关联的 Direct2D 目标位图 + // 并将其设置为当前目标。 + D2D1_BITMAP_PROPERTIES1 bitmapProperties = + D2D1::BitmapProperties1( + D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW, + D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED), + m_dpi, + m_dpi + ); + + ComPtr dxgiBackBuffer; + DX::ThrowIfFailed( + m_swapChain->GetBuffer(0, IID_PPV_ARGS(&dxgiBackBuffer)) + ); + + DX::ThrowIfFailed( + m_d2dContext->CreateBitmapFromDxgiSurface( + dxgiBackBuffer.Get(), + &bitmapProperties, + &m_d2dTargetBitmap + ) + ); + + m_d2dContext->SetTarget(m_d2dTargetBitmap.Get()); + m_d2dContext->SetDpi(m_effectiveDpi, m_effectiveDpi); + + // 建议将灰度文本抗锯齿用于所有 Windows 应用商店应用。 + m_d2dContext->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE); +} + +// 确定呈现器目标的尺寸及其是否将缩小。 +void DX::DeviceResources::UpdateRenderTargetSize() +{ + m_effectiveDpi = m_dpi; + + // 为了延长高分辨率设备上的电池使用时间,请呈现到较小的呈现器目标 + // 并允许 GPU 在显示输出时缩放输出。 + if (!DisplayMetrics::SupportHighResolutions && m_dpi > DisplayMetrics::DpiThreshold) + { + float width = DX::ConvertDipsToPixels(m_logicalSize.Width, m_dpi); + float height = DX::ConvertDipsToPixels(m_logicalSize.Height, m_dpi); + + // 当设备纵向显示时,高度大于宽度。请将 + // 较大维度与宽度阈值比较,并将较小维度 + // 与高度阈值进行比较。 + if (max(width, height) > DisplayMetrics::WidthThreshold && min(width, height) > DisplayMetrics::HeightThreshold) + { + // 为了缩放应用,我们更改了有效 DPI。逻辑大小不变。 + m_effectiveDpi /= 2.0f; + } + } + + // 计算必要的呈现目标大小(以像素为单位)。 + m_outputSize.Width = DX::ConvertDipsToPixels(m_logicalSize.Width, m_effectiveDpi); + m_outputSize.Height = DX::ConvertDipsToPixels(m_logicalSize.Height, m_effectiveDpi); + + // 防止创建大小为零的 DirectX 内容。 + m_outputSize.Width = max(m_outputSize.Width, 1); + m_outputSize.Height = max(m_outputSize.Height, 1); +} + +// 当创建(或重新创建) CoreWindow 时调用此方法。 +void DX::DeviceResources::SetWindow(CoreWindow^ window) +{ + DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView(); + + m_window = window; + m_logicalSize = Windows::Foundation::Size(window->Bounds.Width, window->Bounds.Height); + m_nativeOrientation = currentDisplayInformation->NativeOrientation; + m_currentOrientation = currentDisplayInformation->CurrentOrientation; + m_dpi = currentDisplayInformation->LogicalDpi; + m_d2dContext->SetDpi(m_dpi, m_dpi); + + CreateWindowSizeDependentResources(); +} + +// 在 SizeChanged 事件的事件处理程序中调用此方法。 +void DX::DeviceResources::SetLogicalSize(Windows::Foundation::Size logicalSize) +{ + if (m_logicalSize != logicalSize) + { + m_logicalSize = logicalSize; + CreateWindowSizeDependentResources(); + } +} + +// 在 DpiChanged 事件的事件处理程序中调用此方法。 +void DX::DeviceResources::SetDpi(float dpi) +{ + if (dpi != m_dpi) + { + m_dpi = dpi; + + // 显示 DPI 更改时,窗口的逻辑大小(以 Dip 为单位)也将更改并且需要更新。 + m_logicalSize = Windows::Foundation::Size(m_window->Bounds.Width, m_window->Bounds.Height); + + m_d2dContext->SetDpi(m_dpi, m_dpi); + CreateWindowSizeDependentResources(); + } +} + +// 在 OrientationChanged 事件的事件处理程序中调用此方法。 +void DX::DeviceResources::SetCurrentOrientation(DisplayOrientations currentOrientation) +{ + if (m_currentOrientation != currentOrientation) + { + m_currentOrientation = currentOrientation; + CreateWindowSizeDependentResources(); + } +} + +// 在 DisplayContentsInvalidated 事件的事件处理程序中调用此方法。 +void DX::DeviceResources::ValidateDevice() +{ + // 如果默认适配器更改,D3D 设备将不再有效,因为该设备 + // 已创建或该设备已移除。 + + // 首先,获取自设备创建以来的默认适配器信息。 + + ComPtr dxgiDevice; + DX::ThrowIfFailed(m_d3dDevice.As(&dxgiDevice)); + + ComPtr deviceAdapter; + DX::ThrowIfFailed(dxgiDevice->GetAdapter(&deviceAdapter)); + + ComPtr deviceFactory; + DX::ThrowIfFailed(deviceAdapter->GetParent(IID_PPV_ARGS(&deviceFactory))); + + ComPtr previousDefaultAdapter; + DX::ThrowIfFailed(deviceFactory->EnumAdapters1(0, &previousDefaultAdapter)); + + DXGI_ADAPTER_DESC1 previousDesc; + DX::ThrowIfFailed(previousDefaultAdapter->GetDesc1(&previousDesc)); + + // 接下来,获取当前默认适配器的信息。 + + ComPtr currentFactory; + DX::ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(¤tFactory))); + + ComPtr currentDefaultAdapter; + DX::ThrowIfFailed(currentFactory->EnumAdapters1(0, ¤tDefaultAdapter)); + + DXGI_ADAPTER_DESC1 currentDesc; + DX::ThrowIfFailed(currentDefaultAdapter->GetDesc1(¤tDesc)); + + // 如果适配器 LUID 不匹配,或者该设备报告它已被移除, + // 则必须创建新的 D3D 设备。 + + if (previousDesc.AdapterLuid.LowPart != currentDesc.AdapterLuid.LowPart || + previousDesc.AdapterLuid.HighPart != currentDesc.AdapterLuid.HighPart || + FAILED(m_d3dDevice->GetDeviceRemovedReason())) + { + // 发布对与旧设备相关的资源的引用。 + dxgiDevice = nullptr; + deviceAdapter = nullptr; + deviceFactory = nullptr; + previousDefaultAdapter = nullptr; + + // 创建新设备和交换链。 + HandleDeviceLost(); + } +} + +// 重新创建所有设备资源并将其设置回当前状态。 +void DX::DeviceResources::HandleDeviceLost() +{ + m_swapChain = nullptr; + + if (m_deviceNotify != nullptr) + { + m_deviceNotify->OnDeviceLost(); + } + + CreateDeviceResources(); + m_d2dContext->SetDpi(m_dpi, m_dpi); + CreateWindowSizeDependentResources(); + + if (m_deviceNotify != nullptr) + { + m_deviceNotify->OnDeviceRestored(); + } +} + +// 注册我们的 DeviceNotify 以便在设备丢失和创建时收到通知。 +void DX::DeviceResources::RegisterDeviceNotify(DX::IDeviceNotify* deviceNotify) +{ + m_deviceNotify = deviceNotify; +} + +// 在应用程序挂起时调用此方法。它可提示驱动程序该应用程序 +// 正在进入空闲状态,可以回收临时缓冲区以供其他应用程序使用。 +void DX::DeviceResources::Trim() +{ + ComPtr dxgiDevice; + m_d3dDevice.As(&dxgiDevice); + + dxgiDevice->Trim(); +} + +// 将交换链的内容显示到屏幕上。 +void DX::DeviceResources::Present() +{ + // 第一个参数指示 DXGI 进行阻止直到 VSync,这使应用程序 + // 在下一个 VSync 前进入休眠。这将确保我们不会浪费任何周期渲染 + // 从不会在屏幕上显示的帧。 + DXGI_PRESENT_PARAMETERS parameters = { 0 }; + HRESULT hr = m_swapChain->Present1(1, 0, ¶meters); + + // 放弃呈现目标的内容。 + // 这是仅在完全覆盖现有内容时 + // 有效的操作。如果使用已更新或滚动矩形,则应将本调用删除。 + m_d3dContext->DiscardView1(m_d3dRenderTargetView.Get(), nullptr, 0); + + // 放弃深度模具的内容。 + m_d3dContext->DiscardView1(m_d3dDepthStencilView.Get(), nullptr, 0); + + // 如果通过断开连接或升级驱动程序移除了设备,则必须 + // 必须重新创建所有设备资源。 + if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) + { + HandleDeviceLost(); + } + else + { + DX::ThrowIfFailed(hr); + } +} + +// 此方法确定以下两个元素之间的旋转方式: 显示设备的本机方向和 +// 当前显示方向。 +DXGI_MODE_ROTATION DX::DeviceResources::ComputeDisplayRotation() +{ + DXGI_MODE_ROTATION rotation = DXGI_MODE_ROTATION_UNSPECIFIED; + + // 注意: NativeOrientation 只能为 "Landscape" 或 "Portrait",即使 + // DisplayOrientations 枚举具有其他值。 + switch (m_nativeOrientation) + { + case DisplayOrientations::Landscape: + switch (m_currentOrientation) + { + case DisplayOrientations::Landscape: + rotation = DXGI_MODE_ROTATION_IDENTITY; + break; + + case DisplayOrientations::Portrait: + rotation = DXGI_MODE_ROTATION_ROTATE270; + break; + + case DisplayOrientations::LandscapeFlipped: + rotation = DXGI_MODE_ROTATION_ROTATE180; + break; + + case DisplayOrientations::PortraitFlipped: + rotation = DXGI_MODE_ROTATION_ROTATE90; + break; + } + break; + + case DisplayOrientations::Portrait: + switch (m_currentOrientation) + { + case DisplayOrientations::Landscape: + rotation = DXGI_MODE_ROTATION_ROTATE90; + break; + + case DisplayOrientations::Portrait: + rotation = DXGI_MODE_ROTATION_IDENTITY; + break; + + case DisplayOrientations::LandscapeFlipped: + rotation = DXGI_MODE_ROTATION_ROTATE270; + break; + + case DisplayOrientations::PortraitFlipped: + rotation = DXGI_MODE_ROTATION_ROTATE180; + break; + } + break; + } + return rotation; +} \ No newline at end of file diff --git a/src/platform/windows/Common/DeviceResources.h b/src/platform/windows/Common/DeviceResources.h new file mode 100644 index 00000000..0e81d4b2 --- /dev/null +++ b/src/platform/windows/Common/DeviceResources.h @@ -0,0 +1,102 @@ +#pragma once + +namespace DX +{ + // 提供一个接口,以使拥有 DeviceResources 的应用程序在设备丢失或创建时收到通知。 + interface IDeviceNotify + { + virtual void OnDeviceLost() = 0; + virtual void OnDeviceRestored() = 0; + }; + + // 控制所有 DirectX 设备资源。 + class DeviceResources + { + public: + DeviceResources(); + void SetWindow(Windows::UI::Core::CoreWindow^ window); + void SetLogicalSize(Windows::Foundation::Size logicalSize); + void SetCurrentOrientation(Windows::Graphics::Display::DisplayOrientations currentOrientation); + void SetDpi(float dpi); + void ValidateDevice(); + void HandleDeviceLost(); + void RegisterDeviceNotify(IDeviceNotify* deviceNotify); + void Trim(); + void Present(); + + // 呈现器目标的大小,以像素为单位。 + Windows::Foundation::Size GetOutputSize() const { return m_outputSize; } + + // 呈现器目标的大小,以 dip 为单位。 + Windows::Foundation::Size GetLogicalSize() const { return m_logicalSize; } + float GetDpi() const { return m_effectiveDpi; } + + // D3D 访问器。 + ID3D11Device3* GetD3DDevice() const { return m_d3dDevice.Get(); } + ID3D11DeviceContext3* GetD3DDeviceContext() const { return m_d3dContext.Get(); } + IDXGISwapChain3* GetSwapChain() const { return m_swapChain.Get(); } + D3D_FEATURE_LEVEL GetDeviceFeatureLevel() const { return m_d3dFeatureLevel; } + ID3D11RenderTargetView1* GetBackBufferRenderTargetView() const { return m_d3dRenderTargetView.Get(); } + ID3D11DepthStencilView* GetDepthStencilView() const { return m_d3dDepthStencilView.Get(); } + D3D11_VIEWPORT GetScreenViewport() const { return m_screenViewport; } + DirectX::XMFLOAT4X4 GetOrientationTransform3D() const { return m_orientationTransform3D; } + + // D2D 访问器。 + ID2D1Factory3* GetD2DFactory() const { return m_d2dFactory.Get(); } + ID2D1Device2* GetD2DDevice() const { return m_d2dDevice.Get(); } + ID2D1DeviceContext2* GetD2DDeviceContext() const { return m_d2dContext.Get(); } + ID2D1Bitmap1* GetD2DTargetBitmap() const { return m_d2dTargetBitmap.Get(); } + IDWriteFactory3* GetDWriteFactory() const { return m_dwriteFactory.Get(); } + IWICImagingFactory2* GetWicImagingFactory() const { return m_wicFactory.Get(); } + D2D1::Matrix3x2F GetOrientationTransform2D() const { return m_orientationTransform2D; } + + private: + void CreateDeviceIndependentResources(); + void CreateDeviceResources(); + void CreateWindowSizeDependentResources(); + void UpdateRenderTargetSize(); + DXGI_MODE_ROTATION ComputeDisplayRotation(); + + // Direct3D 对象。 + Microsoft::WRL::ComPtr m_d3dDevice; + Microsoft::WRL::ComPtr m_d3dContext; + Microsoft::WRL::ComPtr m_swapChain; + + // Direct3D 渲染对象。3D 所必需的。 + Microsoft::WRL::ComPtr m_d3dRenderTargetView; + Microsoft::WRL::ComPtr m_d3dDepthStencilView; + D3D11_VIEWPORT m_screenViewport; + + // Direct2D 绘制组件。 + Microsoft::WRL::ComPtr m_d2dFactory; + Microsoft::WRL::ComPtr m_d2dDevice; + Microsoft::WRL::ComPtr m_d2dContext; + Microsoft::WRL::ComPtr m_d2dTargetBitmap; + + // DirectWrite 绘制组件。 + Microsoft::WRL::ComPtr m_dwriteFactory; + Microsoft::WRL::ComPtr m_wicFactory; + + // 对窗口的缓存引用。 + Platform::Agile m_window; + + // 缓存的设备属性。 + D3D_FEATURE_LEVEL m_d3dFeatureLevel; + Windows::Foundation::Size m_d3dRenderTargetSize; + Windows::Foundation::Size m_outputSize; + Windows::Foundation::Size m_logicalSize; + Windows::Graphics::Display::DisplayOrientations m_nativeOrientation; + Windows::Graphics::Display::DisplayOrientations m_currentOrientation; + float m_dpi; + + // 这是将向应用传回的 DPI。它考虑了应用是否支持高分辨率屏幕。 + float m_effectiveDpi; + + // 用于显示方向的转换。 + D2D1::Matrix3x2F m_orientationTransform2D; + DirectX::XMFLOAT4X4 m_orientationTransform3D; + + // IDeviceNotify 可直接保留,因为它拥有 DeviceResources。 + IDeviceNotify* m_deviceNotify; + }; +} \ No newline at end of file diff --git a/src/platform/windows/Common/DirectXHelper.h b/src/platform/windows/Common/DirectXHelper.h new file mode 100644 index 00000000..2b15451e --- /dev/null +++ b/src/platform/windows/Common/DirectXHelper.h @@ -0,0 +1,63 @@ +#pragma once + +#include // 对于 create_task + +namespace DX +{ + inline void ThrowIfFailed(HRESULT hr) + { + if (FAILED(hr)) + { + // 在此行中设置断点,以捕获 Win32 API 错误。 + throw Platform::Exception::CreateException(hr); + } + } + + // 从二进制文件中执行异步读取操作的函数。 + inline Concurrency::task> ReadDataAsync(const std::wstring& filename) + { + using namespace Windows::Storage; + using namespace Concurrency; + + auto folder = Windows::ApplicationModel::Package::Current->InstalledLocation; + + return create_task(folder->GetFileAsync(Platform::StringReference(filename.c_str()))).then([] (StorageFile^ file) + { + return FileIO::ReadBufferAsync(file); + }).then([] (Streams::IBuffer^ fileBuffer) -> std::vector + { + std::vector returnBuffer; + returnBuffer.resize(fileBuffer->Length); + Streams::DataReader::FromBuffer(fileBuffer)->ReadBytes(Platform::ArrayReference(returnBuffer.data(), fileBuffer->Length)); + return returnBuffer; + }); + } + + // 将使用与设备无关的像素(DIP)表示的长度转换为使用物理像素表示的长度。 + inline float ConvertDipsToPixels(float dips, float dpi) + { + static const float dipsPerInch = 96.0f; + return floorf(dips * dpi / dipsPerInch + 0.5f); // 舍入到最接近的整数。 + } + +#if defined(_DEBUG) + // 请检查 SDK 层支持。 + inline bool SdkLayersAvailable() + { + HRESULT hr = D3D11CreateDevice( + nullptr, + D3D_DRIVER_TYPE_NULL, // 无需创建实际硬件设备。 + 0, + D3D11_CREATE_DEVICE_DEBUG, // 请检查 SDK 层。 + nullptr, // 任何功能级别都会这样。 + 0, + D3D11_SDK_VERSION, // 对于 Windows 应用商店应用,始终将此值设置为 D3D11_SDK_VERSION。 + nullptr, // 无需保留 D3D 设备引用。 + nullptr, // 无需知道功能级别。 + nullptr // 无需保留 D3D 设备上下文引用。 + ); + + return SUCCEEDED(hr); + } +#endif +} diff --git a/src/platform/windows/Common/StepTimer.h b/src/platform/windows/Common/StepTimer.h new file mode 100644 index 00000000..408e753b --- /dev/null +++ b/src/platform/windows/Common/StepTimer.h @@ -0,0 +1,183 @@ +#pragma once + +#include + +namespace DX +{ + // 动画和模拟计时的帮助程序类。 + class StepTimer + { + public: + StepTimer() : + m_elapsedTicks(0), + m_totalTicks(0), + m_leftOverTicks(0), + m_frameCount(0), + m_framesPerSecond(0), + m_framesThisSecond(0), + m_qpcSecondCounter(0), + m_isFixedTimeStep(false), + m_targetElapsedTicks(TicksPerSecond / 60) + { + if (!QueryPerformanceFrequency(&m_qpcFrequency)) + { + throw ref new Platform::FailureException(); + } + + if (!QueryPerformanceCounter(&m_qpcLastTime)) + { + throw ref new Platform::FailureException(); + } + + // 将最大增量初始化为 1/10 秒。 + m_qpcMaxDelta = m_qpcFrequency.QuadPart / 10; + } + + // 获取上一次 Update 调用后的运行时间。 + uint64 GetElapsedTicks() const { return m_elapsedTicks; } + double GetElapsedSeconds() const { return TicksToSeconds(m_elapsedTicks); } + + // 获取程序启动之后的总时间。 + uint64 GetTotalTicks() const { return m_totalTicks; } + double GetTotalSeconds() const { return TicksToSeconds(m_totalTicks); } + + // 获取自程序启动之后的更新次数。 + uint32 GetFrameCount() const { return m_frameCount; } + + // 获取当前帧速率。 + uint32 GetFramesPerSecond() const { return m_framesPerSecond; } + + // 设置是使用固定的还是可变的时间步长模式。 + void SetFixedTimeStep(bool isFixedTimestep) { m_isFixedTimeStep = isFixedTimestep; } + + // 当使用固定时间步长模式时,设置调用 Update 的频率。 + void SetTargetElapsedTicks(uint64 targetElapsed) { m_targetElapsedTicks = targetElapsed; } + void SetTargetElapsedSeconds(double targetElapsed) { m_targetElapsedTicks = SecondsToTicks(targetElapsed); } + + // 整数格式使用每秒 10,000,000 次滴答来表示时间。 + static const uint64 TicksPerSecond = 10000000; + + static double TicksToSeconds(uint64 ticks) { return static_cast(ticks) / TicksPerSecond; } + static uint64 SecondsToTicks(double seconds) { return static_cast(seconds * TicksPerSecond); } + + // 在故意中断计时(例如,阻止性 IO 操作)之后 + // 调用此函数以避免固定时间步长逻辑尝试一系列弥补 + // Update 调用。 + + void ResetElapsedTime() + { + if (!QueryPerformanceCounter(&m_qpcLastTime)) + { + throw ref new Platform::FailureException(); + } + + m_leftOverTicks = 0; + m_framesPerSecond = 0; + m_framesThisSecond = 0; + m_qpcSecondCounter = 0; + } + + // 更新计时器状态,调用适当次数的指定 Update 函数。 + template + void Tick(const TUpdate& update) + { + // 查询当前时间。 + LARGE_INTEGER currentTime; + + if (!QueryPerformanceCounter(¤tTime)) + { + throw ref new Platform::FailureException(); + } + + uint64 timeDelta = currentTime.QuadPart - m_qpcLastTime.QuadPart; + + m_qpcLastTime = currentTime; + m_qpcSecondCounter += timeDelta; + + // 固定过大的时间增量(例如, 在调试器中暂停之后)。 + if (timeDelta > m_qpcMaxDelta) + { + timeDelta = m_qpcMaxDelta; + } + + // 将 QPC 单位转换为规范的计时格式。这会因为上一次固定而无法溢出。 + timeDelta *= TicksPerSecond; + timeDelta /= m_qpcFrequency.QuadPart; + + uint32 lastFrameCount = m_frameCount; + + if (m_isFixedTimeStep) + { + // 固定时间步长更新逻辑 + + // 如果应用程序的运行时间十分接近目标运行时间(1/4 毫秒内),可直接固定 + // 时钟以与目标值完全一致。这将防止微小和无关的错误 + // 随时间累积。在不使用此固定的情况下,请求 60 fps 固定更新的 + // 游戏如果在 59.94 NTSC 显示屏上运行时启用了 vsync,则最终会 + // 累积足够多的小错误而导致掉帧。 最好将 + // 将小偏差圆整到零,保持一切平稳运行。 + + if (abs(static_cast(timeDelta - m_targetElapsedTicks)) < TicksPerSecond / 4000) + { + timeDelta = m_targetElapsedTicks; + } + + m_leftOverTicks += timeDelta; + + while (m_leftOverTicks >= m_targetElapsedTicks) + { + m_elapsedTicks = m_targetElapsedTicks; + m_totalTicks += m_targetElapsedTicks; + m_leftOverTicks -= m_targetElapsedTicks; + m_frameCount++; + + update(); + } + } + else + { + // 可变时间步长更新逻辑。 + m_elapsedTicks = timeDelta; + m_totalTicks += timeDelta; + m_leftOverTicks = 0; + m_frameCount++; + + update(); + } + + // 跟踪当前帧速率。 + if (m_frameCount != lastFrameCount) + { + m_framesThisSecond++; + } + + if (m_qpcSecondCounter >= static_cast(m_qpcFrequency.QuadPart)) + { + m_framesPerSecond = m_framesThisSecond; + m_framesThisSecond = 0; + m_qpcSecondCounter %= m_qpcFrequency.QuadPart; + } + } + + private: + // 源计时数据使用 QPC 单位。 + LARGE_INTEGER m_qpcFrequency; + LARGE_INTEGER m_qpcLastTime; + uint64 m_qpcMaxDelta; + + // 派生的计时数据使用规范的计时格式。 + uint64 m_elapsedTicks; + uint64 m_totalTicks; + uint64 m_leftOverTicks; + + // 用于跟踪帧速率的成员。 + uint32 m_frameCount; + uint32 m_framesPerSecond; + uint32 m_framesThisSecond; + uint64 m_qpcSecondCounter; + + // 用于配置固定时间步长模式的成员。 + bool m_isFixedTimeStep; + uint64 m_targetElapsedTicks; + }; +} diff --git a/src/platform/windows/pch.cpp b/src/platform/windows/pch.cpp new file mode 100644 index 00000000..bcb5590b --- /dev/null +++ b/src/platform/windows/pch.cpp @@ -0,0 +1 @@ +#include "pch.h" diff --git a/src/platform/windows/pch.h b/src/platform/windows/pch.h new file mode 100644 index 00000000..797611f9 --- /dev/null +++ b/src/platform/windows/pch.h @@ -0,0 +1,17 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include diff --git a/src/platform/windows/uwp_app.cpp b/src/platform/windows/uwp_app.cpp new file mode 100644 index 00000000..23c46c66 --- /dev/null +++ b/src/platform/windows/uwp_app.cpp @@ -0,0 +1,384 @@ +/* *************************************************************************** + * uwp_app.cpp -- UWP app implementation, responsible for initializing the + * related drivers for LCUI. + * + * Copyright (C) 2017 by Liu Chao + * + * This file is part of the LCUI project, and may only be used, modified, + * and distributed under the terms of the GPLv2. + * + * By continuing to use, modify, or distribute this file you indicate that you + * have read the license and understand and accept it fully. + * + * The LCUI project is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GPL v2 for more details. + * + * You should have received a copy of the GPLv2 along with this file. It is + * usually in the LICENSE.TXT file, If not, see . + * ****************************************************************************/ + +/* **************************************************************************** + * uwp_app.cpp -- UWP 应用的实现,负责为 LCUI 初始化相关驱动程序 + * + * 版权所有 (C) 2017 归属于 刘超 + * + * 这个文件是 LCUI 项目的一部分,并且只可以根据GPLv2许可协议来使用、更改和 + * 发布。 + * + * 继续使用、修改或发布本文件,表明您已经阅读并完全理解和接受这个许可协议。 + * + * LCUI 项目是基于使用目的而加以散布的,但不负任何担保责任,甚至没有适销 + * 性或特定用途的隐含担保,详情请参照GPLv2许可协议。 + * + * 您应已收到附随于本文件的GPLv2许可协议的副本,它通常在 LICENSE 文件中,如果 + * 没有,请查看:. + * ****************************************************************************/ + +#include "pch.h" +#include "uwp_app.h" +#include +#include +#include +#include LCUI_APP_H + +using namespace LCUICore; + +using namespace concurrency; +using namespace Windows::ApplicationModel; +using namespace Windows::ApplicationModel::Core; +using namespace Windows::ApplicationModel::Activation; +using namespace Windows::UI::Core; +using namespace Windows::UI::Input; +using namespace Windows::System; +using namespace Windows::Foundation; +using namespace Windows::Graphics::Display; + +static struct UWPAppModule { + App^ core; + LCUI::Application *app; + Direct3DApplicationSource^ source; + void (*update)(LCUI_Surface); + void (*present)(LCUI_Surface); +} UWPApp; + +static void UWPApp_ProcessEvents( void ) +{ + UWPApp.core->ProcessEvents(); +} + +static int UWPApp_BindSysEvent( int type, LCUI_EventFunc func, + void *data, void( *destroy_data )(void*) ) +{ + return -1; +} + +static int UWPApp_UnbindSysEvent( int type, LCUI_EventFunc func ) +{ + return -1; +} + +static int UWPApp_UnbindSysEvent2( int handler_id ) +{ + return -1; +} + +static void *UWPApp_GetData( void ) +{ + return (void*)UWPApp.core; +} + +static LCUI_AppDriver LCUI_CreateUWPAppDriver( App^ app ) +{ + ASSIGN( driver, LCUI_AppDriver ); + driver->BindSysEvent = UWPApp_BindSysEvent; + driver->UnbindSysEvent = UWPApp_UnbindSysEvent; + driver->UnbindSysEvent2 = UWPApp_UnbindSysEvent2; + driver->ProcessEvents = UWPApp_ProcessEvents; + driver->GetData = UWPApp_GetData; + UWPApp.core = app; + return driver; +} + +static void UWPDisplay_Update( LCUI_Surface surface ) +{ + UWPApp.update( surface ); + UWPApp.core->Update(); +} + +static void UWPDisplay_Present( LCUI_Surface surface ) +{ + UWPApp.present( surface ); + UWPApp.core->Present(); +} + +IFrameworkView^ Direct3DApplicationSource::CreateView() +{ + return ref new App(); +} + +App::App() : + m_windowClosed(false), + m_windowVisible(true) +{ + +} + +// 创建 IFrameworkView 时调用的第一个方法。 +void App::Initialize(CoreApplicationView^ applicationView) +{ + // 注册应用程序生命周期的事件处理程序。此示例包括 Activated,因此我们 + // 可激活 CoreWindow 并开始在窗口上渲染。 + applicationView->Activated += + ref new TypedEventHandler(this, &App::OnActivated); + + CoreApplication::Suspending += + ref new EventHandler(this, &App::OnSuspending); + + CoreApplication::Resuming += + ref new EventHandler(this, &App::OnResuming); + + // 此时,我们具有访问设备的权限。 + // 我们可创建与设备相关的资源。 + m_deviceResources = std::make_shared(); +} + +// 创建(或重新创建) CoreWindow 对象时调用。 +void App::SetWindow( CoreWindow^ window ) +{ + window->SizeChanged += + ref new TypedEventHandler( this, &App::OnWindowSizeChanged ); + + window->VisibilityChanged += + ref new TypedEventHandler( this, &App::OnVisibilityChanged ); + + window->Closed += + ref new TypedEventHandler( this, &App::OnWindowClosed ); + + DisplayInformation^ currentDisplayInformation = DisplayInformation::GetForCurrentView(); + + currentDisplayInformation->DpiChanged += + ref new TypedEventHandler( this, &App::OnDpiChanged ); + + currentDisplayInformation->OrientationChanged += + ref new TypedEventHandler( this, &App::OnOrientationChanged ); + + DisplayInformation::DisplayContentsInvalidated += + ref new TypedEventHandler( this, &App::OnDisplayContentsInvalidated ); + + window->PointerPressed += + ref new TypedEventHandler( this, &App::OnPointerPressed ); + window->PointerMoved += + ref new TypedEventHandler( this, &App::OnPointerMoved ); + window->PointerReleased += + ref new TypedEventHandler( this, &App::OnPointerReleased ); + window->PointerWheelChanged += + ref new TypedEventHandler( this, &App::OnPointerWheelChanged ); + window->KeyUp += + ref new TypedEventHandler( this, &App::OnKeyUp ); + window->KeyDown += + ref new TypedEventHandler( this, &App::OnKeyDown ); + + m_deviceResources->SetWindow( window ); +} + +void App::OnPointerPressed(CoreWindow^ window, PointerEventArgs^ args) +{ + m_inputDriver->OnPointerPressed( window, args ); +} + +void App::OnPointerMoved(CoreWindow^ window, PointerEventArgs^ args) +{ + m_inputDriver->OnPointerMoved( window, args ); +} + +void App::OnPointerReleased(CoreWindow^ window, PointerEventArgs^ args) +{ + m_inputDriver->OnPointerReleased( window, args ); +} + +void App::OnPointerWheelChanged(CoreWindow^ window, PointerEventArgs^ args) +{ + m_inputDriver->OnPointerWheelChanged( window, args ); +} + +void App::OnKeyDown( Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args ) +{ + m_inputDriver->OnKeyDown( sender, args ); +} + +void App::OnKeyUp( Windows::UI::Core::CoreWindow^ sender,Windows::UI::Core:: KeyEventArgs^ args ) +{ + m_inputDriver->OnKeyUp( sender, args ); +} + +// 初始化场景资源或加载之前保存的应用程序状态。 +void App::Load( Platform::String^ entryPoint ) +{ + if( m_main ) { + return; + } + + m_displayDriver = LCUI_CreateUWPDisplay(); + m_inputDriver = std::unique_ptr( new InputDriver ); + m_main = std::unique_ptr
( new Main( m_deviceResources ) ); + m_appDriver = LCUI_CreateUWPAppDriver( this ); + UWPApp.update = m_displayDriver->update; + UWPApp.present = m_displayDriver->present; + m_displayDriver->update = UWPDisplay_Update; + m_displayDriver->present = UWPDisplay_Present; + + LCUI_InitBase(); + LCUI_InitApp( m_appDriver ); + LCUI_InitDisplay( m_displayDriver ); + LCUI_InitIME(); + LCUI_InitCursor(); + m_inputDriver->RegisterIME(); + m_inputDriver->SelectIME(); + UWPApp.app->Load( entryPoint ); +} + +void App::Present() +{ + if( m_windowVisible ) { + if( m_main->Render() ) { + m_deviceResources->Present(); + } + } +} + +void App::Update() +{ + if( m_windowVisible ) { + m_main->Update(); + } +} + +void App::ProcessEvents() +{ + if( m_windowClosed ) { + LCUI_Quit(); + return; + } + auto dispathcer = CoreWindow::GetForCurrentThread()->Dispatcher; + if( m_windowVisible ) { + dispathcer->ProcessEvents( CoreProcessEventsOption::ProcessAllIfPresent ); + } else { + dispathcer->ProcessEvents( CoreProcessEventsOption::ProcessOneAndAllPending ); + } +} + +// 将在窗口处于活动状态后调用此方法。 +void App::Run() +{ + UWPApp.app->Run(); +} + +// IFrameworkView 所必需的。 +// 终止事件不会导致调用 Uninitialize。如果在应用程序在前台运行时销毁 IFrameworkView +// 类,则将调用该方法。 +void App::Uninitialize() +{ +} + +// 应用程序生命周期事件处理程序。 + +void App::OnActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ args) +{ + // Run() 在 CoreWindow 激活前将不会开始。 + CoreWindow::GetForCurrentThread()->Activate(); +} + +void App::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args) +{ + // 在请求延期后异步保存应用程序状态。保留延期 + // 表示应用程序正忙于执行挂起操作。 + // 请注意,延期不是无限期的。在大约五秒后, + // 将强制应用程序退出。 + SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral(); + + create_task([this, deferral]() + { + m_deviceResources->Trim(); + + // 在此处插入代码。 + + deferral->Complete(); + }); +} + +void App::OnResuming(Platform::Object^ sender, Platform::Object^ args) +{ + // 还原在挂起时卸载的任何数据或状态。默认情况下, + // 在从挂起中恢复时,数据和状态会持续保留。请注意, + // 如果之前已终止应用程序,则不会发生此事件。 + + // 在此处插入代码。 +} + +// 窗口事件处理程序。 + +void App::OnWindowSizeChanged(CoreWindow^ sender, WindowSizeChangedEventArgs^ args) +{ + m_deviceResources->SetLogicalSize(Size(sender->Bounds.Width, sender->Bounds.Height)); + m_main->CreateWindowSizeDependentResources(); +} + +void App::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args) +{ + m_windowVisible = args->Visible; +} + +void App::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args) +{ + m_windowClosed = true; +} + +// DisplayInformation 事件处理程序。 + +void App::OnDpiChanged(DisplayInformation^ sender, Object^ args) +{ + // 注意: 在此处检索到的 LogicalDpi 值可能与应用的有效 DPI 不匹配 + // 如果正在针对高分辨率设备对它进行缩放。在 DeviceResources 上设置 DPI 后, + // 应始终使用 GetDpi 方法进行检索。 + // 有关详细信息,请参阅 DeviceResources.cpp。 + m_deviceResources->SetDpi(sender->LogicalDpi); + m_main->CreateWindowSizeDependentResources(); +} + +void App::OnOrientationChanged(DisplayInformation^ sender, Object^ args) +{ + m_deviceResources->SetCurrentOrientation(sender->CurrentOrientation); + m_main->CreateWindowSizeDependentResources(); +} + +void App::OnDisplayContentsInvalidated(DisplayInformation^ sender, Object^ args) +{ + m_deviceResources->ValidateDevice(); +} + +void LCUI::Initialize() +{ + UWPApp.source = ref new Direct3DApplicationSource(); +} + +LCUI::Application::Application() +{ + +} + +void LCUI::Application::Load( Platform::String^ entryPoint ) +{ + +} + +void LCUI::Application::Run() +{ + LCUI_Main(); +} + +void LCUI::Run( LCUI::Application &app ) +{ + UWPApp.app = &app; + CoreApplication::Run( UWPApp.source ); +} diff --git a/src/platform/windows/uwp_app.h b/src/platform/windows/uwp_app.h new file mode 100644 index 00000000..60f65b26 --- /dev/null +++ b/src/platform/windows/uwp_app.h @@ -0,0 +1,96 @@ +/* *************************************************************************** + * uwp_app.h -- UWP App class + * + * Copyright (C) 2017 by Liu Chao + * + * This file is part of the LCUI project, and may only be used, modified, + * and distributed under the terms of the GPLv2. + * + * By continuing to use, modify, or distribute this file you indicate that you + * have read the license and understand and accept it fully. + * + * The LCUI project is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GPL v2 for more details. + * + * You should have received a copy of the GPLv2 along with this file. It is + * usually in the LICENSE.TXT file, If not, see . + * ****************************************************************************/ + +/* **************************************************************************** + * uwp_app.h -- UWP App 类 + * + * 版权所有 (C) 2017 归属于 刘超 + * + * 这个文件是 LCUI 项目的一部分,并且只可以根据GPLv2许可协议来使用、更改和 + * 发布。 + * + * 继续使用、修改或发布本文件,表明您已经阅读并完全理解和接受这个许可协议。 + * + * LCUI 项目是基于使用目的而加以散布的,但不负任何担保责任,甚至没有适销 + * 性或特定用途的隐含担保,详情请参照GPLv2许可协议。 + * + * 您应已收到附随于本文件的GPLv2许可协议的副本,它通常在 LICENSE 文件中,如果 + * 没有,请查看:. + * ****************************************************************************/ + +#pragma once + +#include "Common/DeviceResources.h" +#include "uwp_main.h" + +namespace LCUICore +{ + // 我们的应用程序的主入口点。使用 Windows shell 连接应用程序并处理应用程序生命周期事件。 + ref class App sealed : public Windows::ApplicationModel::Core::IFrameworkView + { + public: + App(); + void ProcessEvents(); + void Update(); + void Present(); + + // IFrameworkView 方法。 + virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView); + virtual void SetWindow(Windows::UI::Core::CoreWindow^ window); + virtual void Load(Platform::String^ entryPoint); + virtual void Run(); + virtual void Uninitialize(); + protected: + // 应用程序生命周期事件处理程序。 + void OnActivated(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView, Windows::ApplicationModel::Activation::IActivatedEventArgs^ args); + void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args); + void OnResuming(Platform::Object^ sender, Platform::Object^ args); + + // 窗口事件处理程序。 + void OnWindowSizeChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ args); + void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args); + void OnWindowClosed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CoreWindowEventArgs^ args); + void OnPointerMoved(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args); + void OnPointerPressed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args); + void OnPointerReleased(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args); + void OnPointerWheelChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args); + void OnKeyDown( Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args ); + void OnKeyUp( Windows::UI::Core::CoreWindow^ sender,Windows::UI::Core:: KeyEventArgs^ args ); + + // DisplayInformation 事件处理程序。 + void OnDpiChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args); + void OnOrientationChanged(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args); + void OnDisplayContentsInvalidated(Windows::Graphics::Display::DisplayInformation^ sender, Platform::Object^ args); + + private: + LCUI_AppDriver m_appDriver; + LCUI_DisplayDriver m_displayDriver; + std::shared_ptr m_deviceResources; + std::unique_ptr m_inputDriver; + std::unique_ptr
m_main; + bool m_windowClosed; + bool m_windowVisible; + }; +} + +ref class Direct3DApplicationSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource +{ +public: + virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView(); +}; diff --git a/src/platform/windows/uwp_input.cpp b/src/platform/windows/uwp_input.cpp new file mode 100644 index 00000000..76ff8f27 --- /dev/null +++ b/src/platform/windows/uwp_input.cpp @@ -0,0 +1,310 @@ +/* *************************************************************************** + * uwp_input.cpp -- UWP input support for LCUI + * + * Copyright (C) 2017 by Liu Chao + * + * This file is part of the LCUI project, and may only be used, modified, + * and distributed under the terms of the GPLv2. + * + * By continuing to use, modify, or distribute this file you indicate that you + * have read the license and understand and accept it fully. + * + * The LCUI project is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GPL v2 for more details. + * + * You should have received a copy of the GPLv2 along with this file. It is + * usually in the LICENSE.TXT file, If not, see . + * ****************************************************************************/ + +/* **************************************************************************** + * uwp_input.cpp -- LCUI 的 UWP 版输入支持,包括鼠标、键盘、触屏等的输入处理 + * + * 版权所有 (C) 2017 归属于 刘超 + * + * 这个文件是 LCUI 项目的一部分,并且只可以根据GPLv2许可协议来使用、更改和 + * 发布。 + * + * 继续使用、修改或发布本文件,表明您已经阅读并完全理解和接受这个许可协议。 + * + * LCUI 项目是基于使用目的而加以散布的,但不负任何担保责任,甚至没有适销 + * 性或特定用途的隐含担保,详情请参照GPLv2许可协议。 + * + * 您应已收到附随于本文件的GPLv2许可协议的副本,它通常在 LICENSE 文件中,如果 + * 没有,请查看:. + * ****************************************************************************/ + +#include "pch.h" +#include "uwp_input.h" +#include +#include +#include + +using namespace LCUICore; +using namespace Windows::UI::Core; +using namespace Windows::UI::Input; +using namespace Windows::Devices::Input; +using namespace Windows::UI; +using namespace Windows::Foundation; +using namespace Windows::System; + +static LCUI_TouchPoint AddTouchPoint( LinkedList *points, + PointerPoint^ point, int state ) +{ + LinkedListNode *node; + LCUI_TouchPoint tp = NULL; + for( LinkedList_Each( node, points ) ) { + tp = (LCUI_TouchPoint)node->data; + if( tp->id == point->PointerId ) { + break; + } + tp = NULL; + } + if( !tp ) { + tp = NEW( LCUI_TouchPointRec, 1 ); + tp->id = point->PointerId; + /* 将第一个触点作为主触点 */ + tp->is_primary = points->length == 0; + LinkedList_Append( points, tp ); + } + tp->state = state; + tp->x = iround( point->Position.X ); + tp->y = iround( point->Position.Y ); + return tp; +} + +static void ClearInvalidTouchPoints( LinkedList *points ) +{ + LCUI_TouchPoint tp; + LinkedListNode *node, *next; + node = points->head.next; + while( node ) { + next = node->next; + tp = (LCUI_TouchPoint)node->data; + if( tp->state == LCUI_TOUCHUP ) { + LinkedList_DeleteNode( points, node ); + } + node = next; + } +} + +static int CreateTouchEvent( LCUI_SysEvent e, LinkedList *points ) +{ + int i = 0; + LinkedListNode *node; + LCUI_TouchPoint list; + list = NEW( LCUI_TouchPointRec, points->length ); + for( LinkedList_Each( node, points ) ) { + list[i++] = *(LCUI_TouchPoint)node->data; + } + return LCUI_CreateTouchEvent( e, list, points->length ); +} + +InputDriver::InputDriver() +{ + m_mouse.actived = false; + m_mouse.leftButtonPressed = false; + m_mouse.rightButtonPressed = false; + LinkedList_Init( &m_touch.points ); +} + +void InputDriver::OnPointerPressed( CoreWindow^ sender, + PointerEventArgs^ args ) +{ + LCUI_Pos pos; + LCUI_TouchPoint tp; + LCUI_SysEventRec ev; + PointerPoint^ point = args->CurrentPoint; + PointerPointProperties^ pointProps = point->Properties; + Point position = point->Position; + switch( point->PointerDevice->PointerDeviceType ) { + case PointerDeviceType::Mouse: + if( pointProps->IsLeftButtonPressed ) { + ev.button.button = LCUIKEY_LEFTBUTTON; + m_mouse.leftButtonPressed = true; + } else if( pointProps->IsRightButtonPressed ) { + ev.button.button = LCUIKEY_RIGHTBUTTON; + m_mouse.rightButtonPressed = true; + } + break; + case PointerDeviceType::Touch: + ev.type = LCUI_TOUCH; + tp = AddTouchPoint( &m_touch.points, point, LCUI_TOUCHDOWN ); + CreateTouchEvent( &ev, &m_touch.points ); + LCUI_TriggerEvent( &ev, NULL ); + LCUI_DestroyEvent( &ev ); + ClearInvalidTouchPoints( &m_touch.points ); + /* 如果该触点是主触点,则顺便触发鼠标事件 */ + if( tp->is_primary ) { + ev.button.button = LCUIKEY_LEFTBUTTON; + m_mouse.leftButtonPressed = true; + break; + } + default:return; + } + if( !m_mouse.actived ) { + m_mouse.actived = true; + m_mouse.position = position; + } + ev.type = LCUI_MOUSEDOWN; + pos.x = iround( position.X ); + pos.y = iround( position.Y ); + ev.button.x = pos.x; + ev.button.y = pos.y; + LCUICursor_SetPos( pos ); + LCUI_TriggerEvent( &ev, NULL ); +} + +void InputDriver::OnPointerMoved( CoreWindow^ sender, PointerEventArgs^ args ) +{ + Point position; + LCUI_Pos pos; + LCUI_TouchPoint tp; + LCUI_SysEventRec ev; + PointerPoint^ point = args->CurrentPoint; + position = args->CurrentPoint->Position; + switch( point->PointerDevice->PointerDeviceType ) { + case PointerDeviceType::Mouse: + break; + case PointerDeviceType::Touch: + ev.type = LCUI_TOUCH; + tp = AddTouchPoint( &m_touch.points, point, LCUI_TOUCHMOVE ); + CreateTouchEvent( &ev, &m_touch.points ); + ClearInvalidTouchPoints( &m_touch.points ); + LCUI_TriggerEvent( &ev, NULL ); + LCUI_DestroyEvent( &ev ); + if( tp->is_primary ) { + break; + } + default:return; + } + if( !m_mouse.actived ) { + m_mouse.actived = true; + m_mouse.position = position; + } + pos.x = iround( position.X ); + pos.y = iround( position.Y ); + ev.type = LCUI_MOUSEMOVE; + ev.motion.x = pos.x; + ev.motion.y = pos.y; + ev.motion.xrel = iround( position.X - m_mouse.position.Y ); + ev.motion.yrel = iround( position.Y - m_mouse.position.Y ); + m_mouse.position = position; + LCUI_TriggerEvent( &ev, NULL ); + LCUI_DestroyEvent( &ev ); + LCUICursor_SetPos( pos ); +} + +void InputDriver::OnPointerReleased( CoreWindow^ sender, PointerEventArgs^ args ) +{ + LCUI_Pos pos; + LCUI_TouchPoint tp; + LCUI_SysEventRec ev; + PointerPoint^ point = args->CurrentPoint; + PointerPointProperties^ pointProps = point->Properties; + Point position = point->Position; + switch( point->PointerDevice->PointerDeviceType ) { + case PointerDeviceType::Mouse: + if( !pointProps->IsLeftButtonPressed && + m_mouse.leftButtonPressed ) { + m_mouse.leftButtonPressed = false; + ev.button.button = LCUIKEY_LEFTBUTTON; + } + if( pointProps->IsRightButtonPressed && + m_mouse.rightButtonPressed ) { + m_mouse.rightButtonPressed = false; + ev.button.button = LCUIKEY_RIGHTBUTTON; + } + break; + case PointerDeviceType::Touch: + ev.type = LCUI_TOUCH; + tp = AddTouchPoint( &m_touch.points, point, LCUI_TOUCHUP ); + CreateTouchEvent( &ev, &m_touch.points ); + ClearInvalidTouchPoints( &m_touch.points ); + LCUI_TriggerEvent( &ev, NULL ); + LCUI_DestroyEvent( &ev ); + if( tp->is_primary ) { + m_mouse.leftButtonPressed = false; + ev.button.button = LCUIKEY_LEFTBUTTON; + } + break; + default:return; + } + ev.type = LCUI_MOUSEUP; + pos.x = iround( position.X ); + pos.y = iround( position.Y ); + ev.button.x = pos.x; + ev.button.y = pos.y; + LCUI_TriggerEvent( &ev, NULL ); + LCUI_DestroyEvent( &ev ); + LCUICursor_SetPos( pos ); +} + +void InputDriver::OnPointerWheelChanged( CoreWindow^ sender, PointerEventArgs^ args ) +{ + LCUI_SysEventRec ev; + PointerPoint^ point = args->CurrentPoint; + PointerPointProperties^ pointProps = point->Properties; + Point position = point->Position; + + ev.type = LCUI_MOUSEWHEEL; + ev.wheel.x = (int)(position.X + 0.5); + ev.wheel.y = (int)(position.Y + 0.5); + ev.wheel.delta = pointProps->MouseWheelDelta;; + LCUI_TriggerEvent( &ev, NULL ); + LCUI_DestroyEvent( &ev ); +} + +void InputDriver::OnKeyDown( CoreWindow^ sender, KeyEventArgs^ args ) +{ + LCUI_SysEventRec ev; + ev.type = LCUI_KEYDOWN; + ev.key.code = static_cast(args->VirtualKey); + LCUI_TriggerEvent( &ev, NULL ); + LCUI_DestroyEvent( &ev ); +} + +void InputDriver::OnKeyUp( CoreWindow^ sender, KeyEventArgs^ args ) +{ + LCUI_SysEventRec ev; + ev.type = LCUI_KEYUP; + ev.key.code = static_cast(args->VirtualKey); + LCUI_TriggerEvent( &ev, NULL ); + LCUI_DestroyEvent( &ev ); +} + +static LCUI_BOOL IME_ProcessKey( int key, int key_state ) +{ + return LCUIIME_CheckCharKey( key ); +} + +static void IME_ToText( int ch ) +{ + wchar_t text[2] = { (wchar_t)ch, 0 }; + LCUIIME_Commit( text, 2 ); +} + +static LCUI_BOOL IME_Open( void ) +{ + return TRUE; +} + +static LCUI_BOOL IME_Close( void ) +{ + return TRUE; +} + +void InputDriver::RegisterIME( void ) +{ + LCUI_IMEHandlerRec handler; + handler.prockey = IME_ProcessKey; + handler.totext = IME_ToText; + handler.close = IME_Close; + handler.open = IME_Open; + m_ime = LCUIIME_Register( "UWP Input Method", &handler ); +} + +void InputDriver::SelectIME( void ) +{ + LCUIIME_Select( m_ime ); +} diff --git a/src/platform/windows/uwp_input.h b/src/platform/windows/uwp_input.h new file mode 100644 index 00000000..bf8c8012 --- /dev/null +++ b/src/platform/windows/uwp_input.h @@ -0,0 +1,68 @@ +/* *************************************************************************** + * uwp_input.h -- UWP input support for LCUI + * + * Copyright (C) 2016-2017 by Liu Chao + * + * This file is part of the LCUI project, and may only be used, modified, + * and distributed under the terms of the GPLv2. + * + * By continuing to use, modify, or distribute this file you indicate that you + * have read the license and understand and accept it fully. + * + * The LCUI project is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GPL v2 for more details. + * + * You should have received a copy of the GPLv2 along with this file. It is + * usually in the LICENSE.TXT file, If not, see . + * ****************************************************************************/ + +/* **************************************************************************** + * uwp_input.h -- LCUI 的 UWP 版输入支持,包括鼠标、键盘、触屏等的输入处理 + * + * 版权所有 (C) 2016-2017 归属于 刘超 + * + * 这个文件是 LCUI 项目的一部分,并且只可以根据GPLv2许可协议来使用、更改和 + * 发布。 + * + * 继续使用、修改或发布本文件,表明您已经阅读并完全理解和接受这个许可协议。 + * + * LCUI 项目是基于使用目的而加以散布的,但不负任何担保责任,甚至没有适销 + * 性或特定用途的隐含担保,详情请参照GPLv2许可协议。 + * + * 您应已收到附随于本文件的GPLv2许可协议的副本,它通常在 LICENSE 文件中,如果 + * 没有,请查看:. + * ****************************************************************************/ + +#pragma once + +#include +#include + +namespace LCUICore { + +class InputDriver { +public: + InputDriver(); + void OnPointerPressed( Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args ); + void OnPointerMoved( Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args ); + void OnPointerReleased( Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args ); + void OnPointerWheelChanged( Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args ); + void OnKeyDown( Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args ); + void OnKeyUp( Windows::UI::Core::CoreWindow^ sender,Windows::UI::Core:: KeyEventArgs^ args ); + void RegisterIME( void ); + void SelectIME( void ); +private: + int m_ime; + struct { + bool actived; + bool leftButtonPressed; + bool rightButtonPressed; + Windows::Foundation::Point position; + } m_mouse; + struct { + LinkedList points; + } m_touch; +}; + +} diff --git a/src/platform/windows/uwp_main.cpp b/src/platform/windows/uwp_main.cpp new file mode 100644 index 00000000..b1a1dee7 --- /dev/null +++ b/src/platform/windows/uwp_main.cpp @@ -0,0 +1,124 @@ +/* *************************************************************************** + * uwp_main.h -- UWP application main implementation + * + * Copyright (C) 2017 by Liu Chao + * + * This file is part of the LCUI project, and may only be used, modified, + * and distributed under the terms of the GPLv2. + * + * By continuing to use, modify, or distribute this file you indicate that you + * have read the license and understand and accept it fully. + * + * The LCUI project is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GPL v2 for more details. + * + * You should have received a copy of the GPLv2 along with this file. It is + * usually in the LICENSE.TXT file, If not, see . + * ****************************************************************************/ + +/* **************************************************************************** + * uwp_renderer.h -- UWP 应用的主要功能实现 + * + * 版权所有 (C) 2017 归属于 刘超 + * + * 这个文件是 LCUI 项目的一部分,并且只可以根据GPLv2许可协议来使用、更改和 + * 发布。 + * + * 继续使用、修改或发布本文件,表明您已经阅读并完全理解和接受这个许可协议。 + * + * LCUI 项目是基于使用目的而加以散布的,但不负任何担保责任,甚至没有适销 + * 性或特定用途的隐含担保,详情请参照GPLv2许可协议。 + * + * 您应已收到附随于本文件的GPLv2许可协议的副本,它通常在 LICENSE 文件中,如果 + * 没有,请查看:. + * ****************************************************************************/ + +#include "pch.h" +#include "uwp_main.h" +#include "Common/DirectXHelper.h" + +using namespace LCUICore; +using namespace Windows::Foundation; +using namespace Windows::System::Threading; +using namespace Concurrency; + +// 加载应用程序时加载并初始化应用程序资产。 +Main::Main(const std::shared_ptr& deviceResources) : + m_deviceResources(deviceResources) +{ + // 注册以在设备丢失或重新创建时收到通知 + m_deviceResources->RegisterDeviceNotify(this); + + m_renderer = std::unique_ptr(new Renderer(m_deviceResources)); + + // TODO: 如果需要默认的可变时间步长模式之外的其他模式,请更改计时器设置。 + // 例如,对于 60 FPS 固定时间步长更新逻辑,请调用: + /* + m_timer.SetFixedTimeStep(true); + m_timer.SetTargetElapsedSeconds(1.0 / 60); + */ +} + +Main::~Main() +{ + // 取消注册设备通知 + m_deviceResources->RegisterDeviceNotify(nullptr); +} + +// 在窗口大小更改(例如,设备方向更改)时更新应用程序状态 +void Main::CreateWindowSizeDependentResources() +{ + m_renderer->CreateWindowSizeDependentResources(); +} + +// 每帧更新一次应用程序状态。 +void Main::Update() +{ + // 更新场景对象。 + m_timer.Tick( [&]() { + m_renderer->Update( m_timer ); + } ); +} + +// 根据当前应用程序状态呈现当前帧。 +// 如果帧已呈现并且已准备好显示,则返回 true。 +bool Main::Render() +{ + // 在首次更新前,请勿尝试呈现任何内容。 + if (m_timer.GetFrameCount() == 0) + { + return false; + } + + auto context = m_deviceResources->GetD3DDeviceContext(); + + // 将视区重置为针对整个屏幕。 + auto viewport = m_deviceResources->GetScreenViewport(); + context->RSSetViewports(1, &viewport); + + // 将呈现目标重置为屏幕。 + ID3D11RenderTargetView *const targets[1] = { m_deviceResources->GetBackBufferRenderTargetView() }; + context->OMSetRenderTargets(1, targets, m_deviceResources->GetDepthStencilView()); + + // 清除后台缓冲区和深度模具视图。 + context->ClearRenderTargetView(m_deviceResources->GetBackBufferRenderTargetView(), DirectX::Colors::CornflowerBlue); + context->ClearDepthStencilView(m_deviceResources->GetDepthStencilView(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); + + // 呈现场景对象。 + m_renderer->Render(); + return true; +} + +// 通知呈现器,需要释放设备资源。 +void Main::OnDeviceLost() +{ + m_renderer->ReleaseDeviceDependentResources(); +} + +// 通知呈现器,现在可重新创建设备资源。 +void Main::OnDeviceRestored() +{ + m_renderer->CreateDeviceDependentResources(); + CreateWindowSizeDependentResources(); +} diff --git a/src/platform/windows/uwp_main.h b/src/platform/windows/uwp_main.h new file mode 100644 index 00000000..a4b3f939 --- /dev/null +++ b/src/platform/windows/uwp_main.h @@ -0,0 +1,67 @@ +/* *************************************************************************** + * uwp_main.h -- + * + * Copyright (C) 2017 by Liu Chao + * + * This file is part of the LCUI project, and may only be used, modified, + * and distributed under the terms of the GPLv2. + * + * By continuing to use, modify, or distribute this file you indicate that you + * have read the license and understand and accept it fully. + * + * The LCUI project is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GPL v2 for more details. + * + * You should have received a copy of the GPLv2 along with this file. It is + * usually in the LICENSE.TXT file, If not, see . + * ****************************************************************************/ + +/* **************************************************************************** + * uwp_main.h -- + * + * 版权所有 (C) 2017 归属于 刘超 + * + * 这个文件是 LCUI 项目的一部分,并且只可以根据GPLv2许可协议来使用、更改和 + * 发布。 + * + * 继续使用、修改或发布本文件,表明您已经阅读并完全理解和接受这个许可协议。 + * + * LCUI 项目是基于使用目的而加以散布的,但不负任何担保责任,甚至没有适销 + * 性或特定用途的隐含担保,详情请参照GPLv2许可协议。 + * + * 您应已收到附随于本文件的GPLv2许可协议的副本,它通常在 LICENSE 文件中,如果 + * 没有,请查看:. + * ****************************************************************************/ + +#pragma once + +#include "Common/StepTimer.h" +#include "Common/DeviceResources.h" +#include "uwp_input.h" +#include "uwp_renderer.h" + +// 在屏幕上呈现 Direct2D 和 3D 内容。 +namespace LCUICore +{ + class Main : public DX::IDeviceNotify + { + public: + Main(const std::shared_ptr& deviceResources); + ~Main(); + void CreateWindowSizeDependentResources(); + void Update(); + bool Render(); + + // IDeviceNotify + virtual void OnDeviceLost(); + virtual void OnDeviceRestored(); + + private: + // 缓存的设备资源指针。 + std::shared_ptr m_deviceResources; + std::unique_ptr m_renderer; + // 渲染循环计时器。 + DX::StepTimer m_timer; + }; +} diff --git a/src/platform/windows/uwp_renderer.cpp b/src/platform/windows/uwp_renderer.cpp new file mode 100644 index 00000000..14bafc24 --- /dev/null +++ b/src/platform/windows/uwp_renderer.cpp @@ -0,0 +1,297 @@ +/* *************************************************************************** + * uwp_renderer.cpp -- UWP display support for LCUI + * + * Copyright (C) 2017 by Liu Chao + * + * This file is part of the LCUI project, and may only be used, modified, + * and distributed under the terms of the GPLv2. + * + * By continuing to use, modify, or distribute this file you indicate that you + * have read the license and understand and accept it fully. + * + * The LCUI project is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GPL v2 for more details. + * + * You should have received a copy of the GPLv2 along with this file. It is + * usually in the LICENSE.TXT file, If not, see . + * ****************************************************************************/ + +/* **************************************************************************** + * uwp_renderer.cpp -- LCUI 的 UWP 版图形输出支持 + * + * 版权所有 (C) 2017 归属于 刘超 + * + * 这个文件是 LCUI 项目的一部分,并且只可以根据GPLv2许可协议来使用、更改和 + * 发布。 + * + * 继续使用、修改或发布本文件,表明您已经阅读并完全理解和接受这个许可协议。 + * + * LCUI 项目是基于使用目的而加以散布的,但不负任何担保责任,甚至没有适销 + * 性或特定用途的隐含担保,详情请参照GPLv2许可协议。 + * + * 您应已收到附随于本文件的GPLv2许可协议的副本,它通常在 LICENSE 文件中,如果 + * 没有,请查看:. + * ****************************************************************************/ + +#include "pch.h" +#define LCUI_SURFACE_C +#include "uwp_renderer.h" +#include "Common/DirectXHelper.h" +#include + +using namespace LCUICore; +using namespace Microsoft::WRL; +using namespace Windows::Foundation; + +static struct UWPDisplay { + LCUI_BOOL is_inited; + Renderer *renderer; + LCUI_EventTrigger trigger; + LCUI_Surface surface; + LCUI_Graph frame; + LCUI_Rect rect; +} display = { 0 }; + +typedef struct LCUI_SurfaceRec_ { + UWPDisplay *display; + LCUI_BOOL is_updated; +} LCUI_SurfaceRec; + +void UpdateSurfaceSize( void ); + +Renderer::Renderer( const std::shared_ptr& deviceResources ) : + m_deviceResources( deviceResources ) +{ + m_bmp = nullptr; + m_backBmp = nullptr; + m_frameSwapable = false; + m_deviceResources->GetD2DFactory()->CreateDrawingStateBlock( &m_stateBlock ); + display.renderer = this; + CreateDeviceDependentResources(); + CreateWindowSizeDependentResources(); +} + +void Renderer::Update( DX::StepTimer const& timer ) +{ + +} + +void Renderer::Render() +{ + D2D1_RECT_F rect; + Size logicalSize = m_deviceResources->GetLogicalSize(); + ID2D1DeviceContext* context = m_deviceResources->GetD2DDeviceContext(); + context->SaveDrawingState( m_stateBlock.Get() ); + context->BeginDraw(); + SwapFrames(); + rect.left = rect.top = 0; + rect.right = (FLOAT)m_frameSize.width; + rect.bottom = (FLOAT)m_frameSize.height; + context->DrawBitmap( m_bmp.Get(), &rect, 1.0f, + D2D1_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR ); + + // 此处忽略 D2DERR_RECREATE_TARGET。此错误指示该设备 + // 丢失。将在下一次调用 Present 时对其进行处理。 + HRESULT hr = context->EndDraw(); + if( hr != D2DERR_RECREATE_TARGET ) { + DX::ThrowIfFailed( hr ); + } + + context->RestoreDrawingState( m_stateBlock.Get() ); +} + +void Renderer::SwapFrames() +{ + D2D1_RECT_F rect; + if( !m_frameSwapable ) { + return; + } + m_frameSwapable = false; + rect.left = (FLOAT)display.rect.x; + rect.top = (FLOAT)display.rect.y; + rect.right = rect.left + (FLOAT)display.rect.width; + rect.bottom = rect.top + (FLOAT)display.rect.height; + auto pos = D2D1::Point2U( (UINT)rect.left, (UINT)rect.top ); + auto readRect = D2D1::RectU( + (UINT)rect.left, (UINT)rect.top, + (UINT)rect.right, (UINT)rect.bottom + ); + m_backBmp->CopyFromMemory( &readRect, display.frame.bytes, + display.frame.bytes_per_row ); + m_bmp->CopyFromBitmap( &pos, m_backBmp.Get(), &readRect ); +} + +void Renderer::CreateDeviceDependentResources() +{ + +} + +void Renderer::CreateWindowSizeDependentResources() +{ + float dpi = m_deviceResources->GetDpi(); + Size outputSize = m_deviceResources->GetOutputSize(); + auto context = m_deviceResources->GetD2DDeviceContext(); + D2D1_BITMAP_PROPERTIES1 props = { + { + DXGI_FORMAT_B8G8R8A8_UNORM, + D2D1_ALPHA_MODE_IGNORE + }, + dpi, dpi, D2D1_BITMAP_OPTIONS_NONE, 0 + }; + m_frameSwapable = true; + m_frameSize = { (UINT32)outputSize.Width, (UINT32)outputSize.Height }; + Graph_Create( &display.frame, (int)m_frameSize.width, (int)m_frameSize.height ); + Graph_FillRect( &display.frame, RGB( 255, 255, 255 ), NULL, TRUE ); + context->CreateBitmap( m_frameSize, nullptr, 0, &props, &m_bmp ); + context->CreateBitmap( m_frameSize, nullptr, 0, &props, &m_backBmp ); + UpdateSurfaceSize(); +} + +void Renderer::ReleaseDeviceDependentResources() +{ + +} + +static void UpdateSurfaceSize( void ) +{ + LCUI_DisplayEventRec dpy_ev; + if( !display.surface || !display.renderer ) { + return; + } + dpy_ev.type = DET_RESIZE; + dpy_ev.surface = display.surface; + dpy_ev.resize.width = (int)display.renderer->m_frameSize.width; + dpy_ev.resize.height = (int)display.renderer->m_frameSize.height; + LCUIDisplay_SetSize( dpy_ev.resize.width, dpy_ev.resize.height ); + EventTrigger_Trigger( display.trigger, DET_RESIZE, &dpy_ev ); + LCUIDisplay_InvalidateArea( NULL ); +} + +static int UWPDisplay_GetWidth( void ) +{ + return (int)display.renderer->m_frameSize.width; +} + +static int UWPDisplay_GetHeight( void ) +{ + return (int)display.renderer->m_frameSize.height; +} + +static int UWPDisplay_BindEvent( int event_id, LCUI_EventFunc func, + void *data, void( *destroy_data )(void*) ) +{ + return EventTrigger_Bind( display.trigger, event_id, func, + data, destroy_data ); +} + +static LCUI_Surface UWPSurface_Create( void ) +{ + LCUI_Surface surface = NEW( LCUI_SurfaceRec, 1 ); + surface->is_updated = FALSE; + surface->display = &display; + display.surface = surface; + return surface; +} + +static void UWPSurface_Delete( LCUI_Surface surface ) +{ + free( surface ); +} + +static LCUI_BOOL UWPSurface_IsReady( LCUI_Surface surface ) +{ + return TRUE; +} + +static void UWPSurface_Show( LCUI_Surface surface ) +{ + +} + +static void UWPSurface_Hide( LCUI_Surface surface ) +{ + +} + +static void UWPSurface_Move( LCUI_Surface surface, int x, int y ) +{ + +} + +static void UWPSurface_Resize( LCUI_Surface surface, int width, int height ) +{ + +} + +static void UWPSurface_Update( LCUI_Surface surface ) +{ + if( !surface->is_updated ) { + UpdateSurfaceSize(); + surface->is_updated = TRUE; + } +} + +static void UWPSurface_Present( LCUI_Surface surface ) +{ + display.renderer->m_frameSwapable = true; +} + +static void UWPSurface_SetCaptionW( LCUI_Surface surface, const wchar_t *title ) +{ + +} + +static void UWPSurface_SetRenderMode( LCUI_Surface surface, int mode ) +{ + +} + +static LCUI_PaintContext UWPSurface_BeginPaint( LCUI_Surface surface, LCUI_Rect *rect ) +{ + ASSIGN( paint, LCUI_PaintContext ); + paint->rect = *rect; + paint->with_alpha = FALSE; + Graph_Init( &paint->canvas ); + LCUIRect_MergeRect( &display.rect, &display.rect, rect ); + LCUIRect_ValidateArea( &paint->rect, UWPDisplay_GetWidth(), + UWPDisplay_GetHeight() ); + Graph_Quote( &paint->canvas, &display.frame, &paint->rect ); + Graph_FillRect( &paint->canvas, RGB( 255, 255, 255 ), NULL, TRUE ); + return paint; +} + +static void UWPSurface_EndPaint( LCUI_Surface surface, LCUI_PaintContext paint ) +{ + free( paint ); +} + +LCUI_DisplayDriver LCUI_CreateUWPDisplay( void ) +{ + ASSIGN( driver, LCUI_DisplayDriver ); + strcpy( driver->name, "UWP Display" ); + driver->getWidth = UWPDisplay_GetWidth; + driver->getHeight = UWPDisplay_GetHeight; + driver->create = UWPSurface_Create; + driver->destroy = UWPSurface_Delete; + driver->isReady = UWPSurface_IsReady; + driver->show = UWPSurface_Show; + driver->hide = UWPSurface_Hide; + driver->move = UWPSurface_Move; + driver->resize = UWPSurface_Resize; + driver->update = UWPSurface_Update; + driver->present = UWPSurface_Present; + driver->setCaptionW = UWPSurface_SetCaptionW; + driver->setRenderMode = UWPSurface_SetRenderMode; + driver->setOpacity = NULL; + driver->getHandle = NULL; + driver->beginPaint = UWPSurface_BeginPaint; + driver->endPaint = UWPSurface_EndPaint; + driver->bindEvent = UWPDisplay_BindEvent; + Graph_Init( &display.frame ); + display.frame.color_type = COLOR_TYPE_ARGB; + display.surface = NULL; + display.trigger = EventTrigger(); + display.is_inited = TRUE; + return driver; +} diff --git a/src/platform/windows/uwp_renderer.h b/src/platform/windows/uwp_renderer.h new file mode 100644 index 00000000..07ad07e4 --- /dev/null +++ b/src/platform/windows/uwp_renderer.h @@ -0,0 +1,70 @@ +/* *************************************************************************** + * uwp_renderer.h -- UWP display support for LCUI + * + * Copyright (C) 2017 by Liu Chao + * + * This file is part of the LCUI project, and may only be used, modified, + * and distributed under the terms of the GPLv2. + * + * By continuing to use, modify, or distribute this file you indicate that you + * have read the license and understand and accept it fully. + * + * The LCUI project is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GPL v2 for more details. + * + * You should have received a copy of the GPLv2 along with this file. It is + * usually in the LICENSE.TXT file, If not, see . + * ****************************************************************************/ + +/* **************************************************************************** + * uwp_renderer.h -- LCUI 的 UWP 版图形输出支持 + * + * 版权所有 (C) 2017 归属于 刘超 + * + * 这个文件是 LCUI 项目的一部分,并且只可以根据GPLv2许可协议来使用、更改和 + * 发布。 + * + * 继续使用、修改或发布本文件,表明您已经阅读并完全理解和接受这个许可协议。 + * + * LCUI 项目是基于使用目的而加以散布的,但不负任何担保责任,甚至没有适销 + * 性或特定用途的隐含担保,详情请参照GPLv2许可协议。 + * + * 您应已收到附随于本文件的GPLv2许可协议的副本,它通常在 LICENSE 文件中,如果 + * 没有,请查看:. + * ****************************************************************************/ + +#pragma once + +#include +#include +#include + +#include +#include "Common/DeviceResources.h" +#include "Common/StepTimer.h" + +namespace LCUICore { + +class Renderer { +public: + Renderer( const std::shared_ptr& deviceResources ); + void CreateDeviceDependentResources(); + void CreateWindowSizeDependentResources(); + void ReleaseDeviceDependentResources(); + void Update( DX::StepTimer const& timer ); + void Render(); + void SwapFrames(); + bool m_frameSwapable; + D2D1_SIZE_U m_frameSize; + +private: + std::shared_ptr m_deviceResources; + Microsoft::WRL::ComPtr m_stateBlock; + Microsoft::WRL::ComPtr m_bmp; + Microsoft::WRL::ComPtr m_backBmp; +}; + +} + +LCUI_DisplayDriver LCUI_CreateUWPDisplay( void );