Rise
The Vieneo Province
Loading...
Searching...
No Matches
Window11.cpp
Go to the documentation of this file.
1#include "Window11.h"
3#include "FrameProfiler11.h"
4#include <windowsx.h>
5#include <algorithm>
6#include <exception>
7#include <d3d11sdklayers.h>
8#include <set>
9
10namespace Rendering
11{
12 namespace {constexpr wchar_t ClassName[]=L"Rise.Native11.Window";}
13 HRESULT Window11::Failure(const char* operation,HRESULT result)
14 {
15 char detail[64]{};sprintf_s(detail," HRESULT=0x%08lx",static_cast<unsigned long>(result));
16 status=std::string(operation)+detail;
17 if(callbacks.report)callbacks.report(status,result);return result;
18 }
19 double Window11::Time() const
20 {
21 LARGE_INTEGER now{};QueryPerformanceCounter(&now);
22 return frequency.QuadPart ? double(now.QuadPart-started.QuadPart)/frequency.QuadPart : 0;
23 }
25 {
26 Destroy();options=requested;callbacks=std::move(handlers);
27 if(!options.width || !options.height || options.samples<1)return E_INVALIDARG;
28 if(!options.instance)options.instance=GetModuleHandleW(nullptr);
29 if(!QueryPerformanceFrequency(&frequency) || !QueryPerformanceCounter(&started))return E_FAIL;
31 // Dialog default actions depend on Windows delivering WM_LBUTTONDBLCLK.
32 WNDCLASSEXW type{sizeof(type)};type.style=CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS;type.lpfnWndProc=Procedure;
33 type.hInstance=options.instance;type.hCursor=LoadCursorW(nullptr,IDC_ARROW);type.lpszClassName=ClassName;
34 type.hIcon=LoadIconW(options.instance,MAKEINTRESOURCEW(101));type.hIconSm=type.hIcon;
35 if(!RegisterClassExW(&type) && GetLastError()!=ERROR_CLASS_ALREADY_EXISTS)return Failure("register native window",HRESULT_FROM_WIN32(GetLastError()));
36 const DWORD style=options.borderless ? WS_POPUP : WS_OVERLAPPEDWINDOW;
37 RECT bounds{0,0,LONG(options.width),LONG(options.height)};
38 if(!AdjustWindowRectEx(&bounds,style,FALSE,0))return Failure("size native window",HRESULT_FROM_WIN32(GetLastError()));
39 int x=CW_USEDEFAULT,y=CW_USEDEFAULT;
41 {
42 // Use one monitor's work area, including its origin and taskbar,
43 // rather than the virtual desktop or Windows' cascading position.
44 MONITORINFO monitor{sizeof(monitor)};
45 if(!GetMonitorInfoW(MonitorFromPoint(POINT{0,0},MONITOR_DEFAULTTOPRIMARY),&monitor))
46 return Failure("locate startup monitor",HRESULT_FROM_WIN32(GetLastError()));
47 x=monitor.rcWork.left+(monitor.rcWork.right-monitor.rcWork.left-(bounds.right-bounds.left))/2;
48 y=monitor.rcWork.top+(monitor.rcWork.bottom-monitor.rcWork.top-(bounds.bottom-bounds.top))/2;
49 }
50 creating=true;
51 window=CreateWindowExW(0,ClassName,options.title.c_str(),style,x,y,
52 bounds.right-bounds.left,bounds.bottom-bounds.top,nullptr,nullptr,options.instance,this);
53 creating=false;
54 if(!window)return Failure("create native window",HRESULT_FROM_WIN32(GetLastError()));
55 RECT client{};GetClientRect(window,&client);width=UINT(client.right);height=UINT(client.bottom);
56 HRESULT hr=CreateDevice();if(FAILED(hr)){Destroy();return hr;}
58 if(options.visible){ShowWindow(window,SW_SHOW);UpdateWindow(window);}
60 }
62 {
63 HRESULT hr=device.Create({options.warp ? D3D_DRIVER_TYPE_WARP : D3D_DRIVER_TYPE_HARDWARE,options.debugLayer});
64 if(FAILED(hr))return Failure(device.Status().c_str(),hr);
65 // Capture this before resource creation, and again on device recovery.
67 if(FAILED(hr=device.AttachWindow(window,width,height,options.samples)))return Failure(device.Status().c_str(),hr);
68 if(FAILED(hr=draws.Initialize(device)))return Failure(draws.Status().c_str(),hr);
69 callbacksLive=true;
70 if(callbacks.create && FAILED(hr=callbacks.create()))return Failure("create game GPU resources",hr);
71 if(callbacks.resize && FAILED(hr=callbacks.resize(width,height)))return Failure("resize game GPU resources",hr);
72 return S_OK;
73 }
74 HRESULT Window11::Resize(UINT nextWidth,UINT nextHeight)
75 {
76 if(!initialized || creating)return S_FALSE;
77 if(!nextWidth || !nextHeight){minimized=true;device.Resize(0,0,options.samples);return S_FALSE;}
78 minimized=false;
79 if(width==nextWidth && height==nextHeight && !device.Suspended() &&
80 device.Depth().Description().SampleDesc.Count==device.SelectSamples(options.samples))return S_OK;
82 // Drop every application reference before DXGI recreates its targets.
83 draws.ReleaseTargets();width=nextWidth;height=nextHeight;
85 if(FAILED(hr))return Failure(device.Status().c_str(),hr);
87 if(callbacks.resize && FAILED(hr=callbacks.resize(width,height)))return Failure("resize game GPU resources",hr);
88 return S_OK;
89 }
91 {
92 if(!initialized || creating || Suspended())return E_UNEXPECTED;
93 if((samples!=1 && samples!=2 && samples!=4 && samples!=8) || !device.SupportsSamples(samples))return E_INVALIDARG;
94 const UINT previousSamples=options.samples;
95 options.samples=samples;
96 const HRESULT hr=Resize(width,height);
97 if(FAILED(hr))
98 {
99 // Keep a failed quality change from leaving the scene unusable.
100 options.samples=previousSamples;
101 if(FAILED(Resize(width,height)))Close(1);
102 }
103 return hr;
104 }
106 {
107 if(!window || creating)return E_UNEXPECTED;
108 struct RecoveryGuard {bool& value;RecoveryGuard(bool& v):value(v){value=true;}~RecoveryGuard(){value=false;}} recovery(recovering);
109 creating=true;
110 if(callbacks.report)callbacks.report("Before device recovery: "+MemoryDiagnostics11(device.Device()),S_OK);
113 callbacksLive=false;
115 if(callbacks.report)callbacks.report("After device cleanup: "+MemoryDiagnostics11(nullptr),S_OK);
116 const HRESULT hr=CreateDevice();creating=false;
117 if(SUCCEEDED(hr) && fullscreen)return device.SetFullscreen(true);
118 return hr;
119 }
121 {
122 if(!initialized)return E_UNEXPECTED;
123 if(fullscreen==value)return S_OK;
124 creating=true;const HRESULT hr=device.SetFullscreen(value);creating=false;
125 if(FAILED(hr))return Failure("fullscreen",hr);
126 fullscreen=value;RECT client{};GetClientRect(window,&client);
127 return Resize(UINT(client.right),UINT(client.bottom));
128 }
130 {
131 if(!initialized || inFrame)return E_UNEXPECTED;
132 if(Suspended())return S_FALSE;
133 LARGE_INTEGER now{};QueryPerformanceCounter(&now);
134 const double time=double(now.QuadPart-started.QuadPart)/frequency.QuadPart;
135 // Preserve the client's elapsed-time contract; clipping long frames
136 // here would slow game timers and animations relative to wall time.
137 const float elapsed=float((std::max)(0.,double(now.QuadPart-previous.QuadPart)/frequency.QuadPart));previous=now;
138 struct FrameGuard {bool& active;FrameGuard(bool& value):active(value){active=true;}~FrameGuard(){active=false;}} guard(inFrame);
139 auto& profiler=FrameProfiler11::Get();
140 profiler.BeginFrame(device.Device(),device.Context(),width,height,device.Depth().Description().SampleDesc.Count,options.vsync,elapsed);
141 // Login can reset the game clock inside move; stall timings need an
142 // absolute counter that stays monotonic across that transition.
143 const auto sample=[&]{LARGE_INTEGER value{};QueryPerformanceCounter(&value);return double(value.QuadPart)/frequency.QuadPart;};
144 const double updateStarted=sample();
145 {ProfileScope11 timing("CPU update",false);if(callbacks.move)callbacks.move(time,elapsed);}
146 const double updateFinished=sample();
147 // FrameMove can close or resize the window, so recheck its lifetime.
148 if(!running || !window || Suspended()){profiler.EndFrame();return S_FALSE;}
149 profiler.BeginGpu();
150 draws.BindScene();HRESULT hr=S_OK;
151 {ProfileScope11 timing("Render submission",false);if(callbacks.draw)hr=callbacks.draw(time,elapsed);}
152 const double drawFinished=sample();
153 if(SUCCEEDED(hr))hr=device.Present(options.vsync ? 1 : 0);
154 const double presentFinished=sample();
155 if(callbacks.report && presentFinished-updateStarted>.25)
156 {
157 char delay[256]{};
158 sprintf_s(delay,"Frame delay: update=%.1f ms, render submission=%.1f ms, Present=%.1f ms; %ux%u MSAA=%u",
159 (updateFinished-updateStarted)*1000,(drawFinished-updateFinished)*1000,
160 (presentFinished-drawFinished)*1000,width,height,device.Depth().Description().SampleDesc.Count);
161 callbacks.report(delay,hr);
162 }
163 profiler.EndFrame();
165 {
166 Microsoft::WRL::ComPtr<ID3D11InfoQueue> queue;
167 if(SUCCEEDED(device.Device()->QueryInterface(IID_PPV_ARGS(&queue))))
168 {
169 static std::set<std::string> reported;
170 for(UINT64 i=0;i<queue->GetNumStoredMessagesAllowedByRetrievalFilter();++i)
171 {
172 SIZE_T bytes=0;queue->GetMessage(i,nullptr,&bytes);std::vector<uint8_t> storage(bytes);
173 auto* message=reinterpret_cast<D3D11_MESSAGE*>(storage.data());
174 if(SUCCEEDED(queue->GetMessage(i,message,&bytes)) && message->Severity<=D3D11_MESSAGE_SEVERITY_WARNING
175 && reported.size()<100 && reported.insert(message->pDescription).second)
176 callbacks.report(std::string("D3D11 validation: ")+message->pDescription,message->Severity<=D3D11_MESSAGE_SEVERITY_ERROR ? E_FAIL : S_FALSE);
177 }
178 queue->ClearStoredMessages();
179 }
180 }
182 {
183 Failure("native device removed; recreating resources",device.RemovalReason());
184 return RecreateDevice();
185 }
186 if(FAILED(hr))return Failure("native frame",hr);
187 if(hr==S_OK && callbacks.presented)
188 {
189 const HRESULT shown=callbacks.presented();
190 if(FAILED(shown))return Failure("present game window",shown);
191 }
192 occluded=hr==DXGI_STATUS_OCCLUDED;++frames;
193 // Login can reset the game clock inside either callback. Sample its
194 // current epoch so the pre-login timestamp cannot delay FPS updates.
195 const double fpsTime=Time();
196 if(fpsTime-fpsStart>=.5){fps=float(frames/(fpsTime-fpsStart));frames=0;fpsStart=fpsTime;}
197 return hr;
198 }
200 {
201 MSG message{};
202 while(running)
203 {
204 while(PeekMessageW(&message,nullptr,0,0,PM_REMOVE))
205 {
206 if(message.message==WM_QUIT){running=false;exitCode=int(message.wParam);break;}
207 TranslateMessage(&message);DispatchMessageW(&message);
208 }
209 if(!running)break;
210 if(Suspended()){MsgWaitForMultipleObjectsEx(0,nullptr,100,QS_ALLINPUT,MWMO_INPUTAVAILABLE);continue;}
211 if(occluded)MsgWaitForMultipleObjectsEx(0,nullptr,50,QS_ALLINPUT,MWMO_INPUTAVAILABLE);
212 if(FAILED(Frame())){exitCode=1;break;}
213 }
214 return exitCode;
215 }
216 void Window11::Close(int result)
217 {
218 exitCode=result;running=false;if(window)PostMessageW(window,WM_CLOSE,0,0);
219 }
221 {
222 running=false;
223 if(callbacksLive)
224 {
227 }
229 // Leave exclusive fullscreen while the swap chain/window are valid.
231 if(window)DestroyWindow(window);
233 }
238 LRESULT CALLBACK Window11::Procedure(HWND handle,UINT message,WPARAM wParam,LPARAM lParam)
239 {
240 auto* host=reinterpret_cast<Window11*>(GetWindowLongPtrW(handle,GWLP_USERDATA));
241 if(message==WM_NCCREATE)
242 {
243 host=static_cast<Window11*>(reinterpret_cast<CREATESTRUCTW*>(lParam)->lpCreateParams);
244 SetWindowLongPtrW(handle,GWLP_USERDATA,reinterpret_cast<LONG_PTR>(host));host->window=handle;
245 }
246 if(!host)return DefWindowProcW(handle,message,wParam,lParam);
247 // C++ exceptions must not escape a Windows callback and be swallowed by
248 // user32. The game's outer native-exception diagnostics remain in charge.
249 try {return host->Message(handle,message,wParam,lParam);}
250 catch(const std::exception& error){host->Failure(error.what(),E_FAIL);host->Close(1);return 0;}
251 catch(...){host->Failure("unhandled native window callback",E_FAIL);host->Close(1);return 0;}
252 }
253 LRESULT Window11::Message(HWND handle,UINT message,WPARAM wParam,LPARAM lParam)
254 {
255 bool handled=false;
256 if(message==WM_NCDESTROY)
257 {
258 SetWindowLongPtrW(handle,GWLP_USERDATA,0);window=nullptr;running=false;
259 return DefWindowProcW(handle,message,wParam,lParam);
260 }
261 // Window lifetime callbacks do not depend on GPU initialization. In
262 // particular WM_CREATE registers the game's device notifications;
263 // suppressing it leaves no handle to release at shutdown. Continue to
264 // suppress resize/activation messages while creating GPU resources.
265 if(callbacks.message && (!creating || message==WM_CREATE || message==WM_DESTROY))
266 {
267 const LRESULT result=callbacks.message(handle,message,wParam,lParam,handled);if(handled)return result;
268 }
269 switch(message)
270 {
271 case WM_SIZE:
272 if(initialized && !creating && FAILED(Resize(LOWORD(lParam),HIWORD(lParam))))Close(1);
273 return 0;
274 case WM_KEYDOWN:case WM_KEYUP:case WM_SYSKEYDOWN:case WM_SYSKEYUP:
275 if(callbacks.keyboard)callbacks.keyboard(UINT(wParam),message==WM_KEYDOWN || message==WM_SYSKEYDOWN,(lParam&(1LL<<29))!=0);
276 // DXUT reserved F10 for game bindings when no menu bar existed.
277 // DefWindowProc otherwise enters Windows' modal menu loop on key
278 // release, stopping frames (and DirectInput polling) until input.
279 if(wParam==VK_F10 && !GetMenu(handle))return 0;
280 break;
281 case WM_ERASEBKGND:return 1;
282 case WM_PAINT:{PAINTSTRUCT paint{};BeginPaint(window,&paint);EndPaint(window,&paint);return 0;}
283 case WM_CLOSE:running=false;DestroyWindow(window);return 0;
284 case WM_DESTROY:running=false;return 0;
285 }
286 return DefWindowProcW(handle,message,wParam,lParam);
287 }
288}
SCRIPT_CONTROL SCRIPT_STATE const void int
HRESULT(WINAPI *CUniBuffer::_ScriptApplyDigitSubstitution)(const SCRIPT_DIGITSUBSTITUTE *
SCRIPT_CONTROL SCRIPT_STATE const void DWORD
UINT SelectSamples(UINT requested) const
Definition Device11.cpp:124
HRESULT AttachWindow(HWND window, UINT width, UINT height, UINT requestedSamples)
Definition Device11.cpp:142
bool SupportsSamples(UINT count) const
Definition Device11.cpp:112
ID3D11DeviceContext * Context() const
Definition Device11.h:66
bool Suspended() const
Definition Device11.h:73
IDXGISwapChain1 * SwapChain() const
Definition Device11.h:67
ID3D11Device * Device() const
Definition Device11.h:65
HRESULT Present(UINT syncInterval=1)
Definition Device11.cpp:243
const std::string & Status() const
Definition Device11.h:75
HRESULT SetFullscreen(bool fullscreen)
Definition Device11.cpp:261
HRESULT Resize(UINT width, UINT height, UINT requestedSamples)
Definition Device11.cpp:210
HRESULT Create(const DeviceOptions11 &options={})
Definition Device11.cpp:84
HRESULT RemovalReason() const
Definition Device11.cpp:268
const SceneDepth11 & Depth() const
Definition Device11.h:70
const std::string & Status() const
HRESULT Initialize(Device11 &device, const std::filesystem::path &shaderDirectory={})
static FrameProfiler11 & Get()
const D3D11_TEXTURE2D_DESC & Description() const
Definition Device11.h:22
double Time() const
Definition Window11.cpp:19
LARGE_INTEGER started
Definition Window11.h:71
LRESULT Message(HWND, UINT, WPARAM, LPARAM)
Definition Window11.cpp:253
HRESULT Failure(const char *operation, HRESULT result)
Definition Window11.cpp:13
void StopCallbacksAndWindow()
Definition Window11.cpp:220
HRESULT Create(const WindowOptions11 &options, Callbacks callbacks)
Definition Window11.cpp:24
DrawContext11 draws
Definition Window11.h:70
HRESULT SetSamples(UINT samples)
Definition Window11.cpp:90
WindowOptions11 options
Definition Window11.h:66
HRESULT Resize(UINT width, UINT height)
Definition Window11.cpp:74
static LRESULT CALLBACK Procedure(HWND, UINT, WPARAM, LPARAM)
Definition Window11.cpp:238
std::string status
Definition Window11.h:79
bool Suspended() const
Definition Window11.h:55
LARGE_INTEGER previous
Definition Window11.h:71
Callbacks callbacks
Definition Window11.h:67
LARGE_INTEGER frequency
Definition Window11.h:71
HRESULT SetFullscreen(bool value)
Definition Window11.cpp:120
HRESULT CreateDevice()
Definition Window11.cpp:61
HRESULT RecreateDevice()
Definition Window11.cpp:105
void Close(int result=0)
Definition Window11.cpp:216
bool IsDeviceRemovalError11(HRESULT result)
std::string MemoryDiagnostics11(ID3D11Device *device)
std::string DriverDiagnostics11(ID3D11Device *device)
std::function< HRESULT(UINT, UINT)> resize
Definition Window11.h:24
std::function< void()> destroy
Definition Window11.h:26
std::function< void(double, float)> move
Definition Window11.h:29
std::function< LRESULT(HWND, UINT, WPARAM, LPARAM, bool &)> message
Definition Window11.h:31
std::function< HRESULT()> presented
Definition Window11.h:28
std::function< void(const std::string &, HRESULT)> report
Definition Window11.h:33
std::function< HRESULT()> create
Definition Window11.h:23
std::function< void(UINT, bool, bool)> keyboard
Definition Window11.h:32
std::function< void()> releaseSizeDependent
Definition Window11.h:25
std::function< HRESULT(double, float)> draw
Definition Window11.h:30