Correct way to resize swapChain in DirectX12 - c++-winrt

I am attempting to port the DirectX12/XAML UWP template over to a C++-WinRT version... where EVERYTHING is done via C++-WinRT and I can turn off CX. I'm currently stuck on how to ResizeBuffers on the swapchain. Before resizing the buffers I have to release all the buffer references. In C++/CX ComPtr there is Reset() method to release reference of the renderTarget buffers, but in C++/winrt com_ptr no such Reset() method exists and if I set renderTarget to nullptr in order to release it, it throws an exception shown in the Screenshot below. And if I don't set the renderTarget to nullptr then exception is not thrown but the swapChain is also not resized.
Later I also tried it using the wrl::ComPtr and the Reset() method it is still throwing the same error. Does anyone know the correct way of resizing the swapChain in DirectX12?
Screenshot of the code and error

You can't use a "fail-fast" error handler like ThrowIfFailed for ResizeBuffers or Present. Both return meaningful failure codes at runtime you must handle.
Specifically both can return DXGI_ERROR_DEVICE_REMOVED or DXGI_ERROR_DEVICE_RESET and you need to handle it. In fact, in the UWP environment, you will see this happen at start up so you must handle it--some 'classic' Win32 desktop apps just ignore it and crash at weird times like when Windows Update updates a driver while the game is running.
For details on handling 'lost-device' (which is really 'device removed'), see DeviceResources .h / .cpp.
See also Microsoft Docs which is written for DirectX 11, but all the equivalent stuff has to happen for DirectX 12.

Related

How to call a method on the GUI thread in C++/winrt

When responding to an event in a textbox using C++/winrt I need to use ScrollViewer.ChangeView(). Trouble is, nothing happens when the call executes and I expect that is because at that moment the code is in the wrong thread; I have read this is the cause for lack of visible results from ChangeView(). It appears that the proper course is to use CoreDispatcher.RunAsync to update the scroller on the UI thread. The example code for this is provided only in C# and managed C++, however, and it is a tricky matter to figure out how this would look in normal C++. At any rate, I am not getting it. Does anyone have an example of the proper way to call a method on the UI thread in C++/winrt? Thanks.
[UPDATE:] I have found another method that seems to work, which I will show here, though I am still interested in an answer to the above. The other method is to create an IAsyncOperation that boils down to this:
IAsyncOperation<bool> ScrollIt(h,v, zoom){
co_await m_scroll_viewer.ChangeView(h,v,zoom);
}
The documentation entry Concurrency and asynchronous operations with C++/WinRT: Programming with thread affinity in mind explains, how to control, which thread runs certain code. This is particularly helpful in context of asynchronous functions.
C++/WinRT provides helpers winrt::resume_background() and winrt::resume_foreground(). co_await-ing either one switches to the respective thread (either a background thread, or the thread associated with the dispatcher of a control).
The following code illustrates the usage:
IAsyncOperation<bool> ScrollIt(h, v, zoom){
co_await winrt::resume_background();
// Do compute-bound work here.
// Switch to the foreground thread associated with m_scroll_viewer.
co_await winrt::resume_foreground(m_scroll_viewer.Dispatcher());
// Execute GUI-related code
m_scroll_viewer.ChangeView(h, v, zoom);
// Optionally switch back to a background thread.
// Return an appropriate value.
co_return {};
}

Qt5 "Attempt to set a screen on a child window" many runtime warning messages

In our Qt5-based application, many messages like this are displayed in the console:
0x1beccb0 void QWindowPrivate::setTopLevelScreen(QScreen*, bool) ( QScreen(0xd25b80) ): Attempt to set a screen on a child window.
It does not prevent the application from running, but I would like to fix them, since it tends to indicate that there is probably something wrong that we are doing. The code is quite large (cannot be included in the post, it is there: http://gforge.inria.fr/frs/?group_id=1465). I cannot ask you to take a look at it (too big), but maybe you will have an idea with the following additional information:
The messages appear only under Linux, and not under Windows
Our application is a 3D modeler, that has several QGLWidgets for
displaying 3D content. If I remove the QGLWidgets, then the messages
disappear.
In the debugger, if I put a breakpoint on
QWindowPrivate::setTopLevelScreen(), it is called by:
kernel/qwindow.cpp:368
368 q->connect(screen, SIGNAL(destroyed(QObject*)), q, SLOT(screenDestroyed(QObject*)));
Update1:
I put a breakpoint on QMessageLogger::warning (qDebug() is a macro that uses this function), now I can better see the stack that looks like:
#0 0x00007fffefa50600 in QMessageLogger::warning() const#plt () from /usr/lib/x86_64-linux-gnu/libQt5Gui.so.5
#1 0x00007fffefa851cb in QWindowPrivate::setTopLevelScreen (this=0xd330e0, newScreen=0x7201a0, recreate=<optimized out>)
at kernel/qwindow.cpp:371
#2 0x00007fffefa7f2f5 in QGuiApplicationPrivate::processWindowSystemEvent (e=e#entry=0x760600)
at kernel/qguiapplication.cpp:1608
#3 0x00007fffefa631f8 in QWindowSystemInterface::sendWindowSystemEvents (flags=...)
at kernel/qwindowsysteminterface.cpp:625
#4 0x00007fffeb7d4100 in userEventSourceDispatch (source=<optimized out>)
at eventdispatchers/qeventdispatcher_glib.cpp:70
(More stack frames follow...)
In QGuiApplicationPrivate::processWindowSystemEvent, it is handling a QWindowSystemInterfacePrivate::ThemeChange event:
1608 case QWindowSystemInterfacePrivate::ThemeChange:
1609 QGuiApplicationPrivate::processThemeChanged(
1610 static_cast<QWindowSystemInterfacePrivate::ThemeChangeEvent *>(e));
1611 break;
Update2:
Nearly there !! It is when I call setMinimumWidth() / setMinimumHeight() on a QGLWidget. Now I'd like to know why...
Update3:
More information: the messages are only displayed when I have two screens connected to my computer.
Finally, I understood what happens:
The warning messages occur whenever setMinimumWidth() / setMinimumHeight() are called on a QGLWidget under Linux with a dual screen display.
This is probably a bug in Qt. It will probably be not fixed, since it is recommended in the documentation to use the new QOpenGLWidget instead, that appeared in Qt 5.4 (note: "OpenGL" instead of "GL"), which I did and the warning messages disappeared.
Edit: I saw a message from someone that had problems with text not rendering properly with the new QOpenGLWidget which I answer here: When using the new QOpenGLWidget, one needs to take care that it no longer has an independent OpenGL context, it shares the OpenGL context with Qt (therefore, OpenGL states modified in the rendering function needs to be restored after exiting the rendering function, for instance blending mode).

What kind of crash produces an Application Error (aka Application Popup) on Windows XP?

First I will describe the crash types I know about. Scroll down for the actual question. Note that I am only interested in crashes that are handled by Windows. Specific applications and frameworks sometimes have their own crash handlers (eg. Cygwin, the VCL, Java or .NET), which I will not discuss.
Dr Watson
On Windows XP, most unhandled "Structured Exceptions" such as access violations produce a Microsoft Application Error Reporting dialog (it was later renamed "Windows Error Reporting" but the executable is dwwin.exe and I will call it Dr Watson):
It is easily reproduced with *(char*)0=0;
FatalAppExit
Calling FatalAppExit() produces a MessageBox and Event Log entry, but no Dr Watson:
Stack overflow
On Windows XP a stack overflow causes the process to unceremoniously exit with no notification at all. (I think this was fixed starting with Vista)
It can be reproduced with main(){main();}
My question is, what causes one of these:
This dialog is owned by csrss.exe, and by the time I see it, the AcroRd32.exe process has exited.
It also writes an entry in the System Event Log (which a Dr Watson crash doesn't do):
I can reproduce the dialog and Event Log entry (but obviously not an actual crash), with this call to MessageBox:
MessageBox(
0,
"The exception unknown software exception (0xc0000409) occurred in the application at location 0x00404def.",
"AcroRd32.exe - Application Error",
MB_ICONSTOP | MB_SERVICE_NOTIFICATION);
I've ruled out Adobe Reader running as a service. It is version 11.0.08. The crash seems to happen sporadically when a Windows Explorer window with a PDF file selected becomes the active window.
Of course I'm not asking you to troubleshoot Adobe Reader for me, just how to produce an "Application Error" / "Application Popup" type of crash, preferably programmatically so I can understand what's going on.
This looks like the work of kernel32.UnhandledExceptionFilter. You might be able to trigger this error message with:
EXCEPTION_RECORD Rec = {
ExceptionCode : 0xc0000409, /* STATUS_STACK_BUFFER_OVERRUN */
ExceptionAddress : cast(void*) 0x404def,
};
CONTEXT Ctx;
RtlCaptureContext(&Ctx);
EXCEPTION_POINTERS Xcep = {
ExceptionRecord : &Rec,
ContextRecord : &Ctx,
};
UnhandledExceptionFilter(&Xcep);
However on Windows 7 that didn't do it for me, it just went straight to Dr Watson.
What does seem to work on W7 is this:
size_t[2] Params = [
0xc0000409, /* STATUS_STACK_BUFFER_OVERRUN */
0x404def, /* exception address */
];
int Response;
NtRaiseHardError(
0xc0000144 /* STATUS_UNHANDLED_EXCEPTION */ |
0x10000000 /* HARDERROR_OVERRIDE_ERRORMODE */,
Params.length,
0, /* UnicodeStringParameterMask */
Params.ptr,
2 /* OptionOkCancel */,
&Response
);
I know UnhandledExceptionFilter has this code somewhere, I just don't know what conditions it needs to take that code path. But you can just call NtRaiseHardError like this yourself.
Here's the result:
I don't use XP any more so you'll have to experiment yourself to see how these methods behave on XP, but hopefully this will give you a starting point.
The error dialog owned by CSRSS (which can also be programmatically triggered by a manual call to NtRaiseHardError, see this answer), is displayed on Windows when you have an unhandled exception. For all Win32 applications, a default exception handler for unhandled exceptions is set up by kernel32.dll, and this is this handler that does the job of either showing the Windows Error Reporting dialog, or showing the error dialog.
For the details, the open-source ReactOS project (which aim is to "re-create" Windows in an open-source way using clean-room RE) has similar code, that should help you knowing precisely in which conditions the error dialog appears: see the UnhandledExceptionFilter() function in dll/win32/kernel32/client/except.c.

CreateFileAsync in SuspensionManager throws indecipherable exception

I created a new Windows Store app project using the Grid App (XAML) template. I ran the project (in debug mode) without changing a single line of code. While it was running, I switched back to Visual Studio and clicked the Suspend button in the toolbar.
At this point, the app threw a SuspensionManagerException. The exception’s details weren’t too helpful. The message is SuspensionManager failed. It has the (so far) unhelpful HResult -2146233088. It also has an InnerException that’s just as unhelpful. Its message is Error HRESULT E_FAIL has been returned from a call to a COM component. and its HResult, which is -2147467259, is even worse than the outer exception’s HResult.
The line of code that throws the exception is in the SuspensionManager, which, again, is part of the project template. Here’s the line:
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting);
The part that triggers the exception is LocalFolder.CreateFileAsync(…). The MSDN documentation for the CreateFileAsync method has a “Remarks” section that reads: If you try to create a file in a virtual folder like a library or a file group, this method may fail.
That’s it. There’s no explanation of why it may fail, or a description of the conditions under which it may fail, or what you can do about it.
As it happens, even when it fails, the file is actually created. The file in question is called _sessionState.xml and is located at C:\Users\<username>\AppData\Local\Packages\<package_id>\LocalState. If I delete the file and re-suspend the app, the exception is throw again and the file is recreated.
I've searched high and low and haven't found anything conclusive. The CreateFileAsync method is a projection, so I can't easily disassemble it or figure out why it "may fail".
Does anybody have any idea what could be causing this problem, or how to go about debugging or solving it?
The first thing to check is that Frame.Navigate should only take primitives as its parameter argument.
Also, make sure you are calling GetDeferral in your async event handler.

EXC_BAD_ACCESS on animationForKey:

I'm trying to use a recent feature of the Scintilla component, which provides OSX-like text-highlighting effect (the yellow animated bouncing box), and I'm stuck with an error that pops up intermittently :
EXC_BAD_ACCESS
pointing to this particular line :
if (layerFindIndicator!=nil)
if ([layerFindIndicator animationForKey:#"animateFound"])
[layerFindIndicator removeAnimationForKey:#"animateFound"];
(the ifs are mine; just in case I caught the object layerFindIndicator being nil, or deallocated or whatever... Unfortunately, it doesn't help...)
layerFindIndicator is seemingly a subclass of CAGradientLayer. (You may see the full code for layerFindIndicator, here).
Since, I'm an absolute newbie to Quartz Core, could please give me any hint as to HOW this could be debugged?
Since, I'm an absolute newbie to Quartz Core, could please give me any hint as to HOW this could be debugged?
This doesn't have anything to do with QuartzCore specifically (at least, I hope not)—it's general this-object-has-been-killed-before-its-time-how-do-I-find-the-killer stuff.
In Xcode:
Edit your current scheme.
For the Profile action, set it to use the Debug build configuration.
Dismiss that and then hit the Profile command.
Xcode will build for that action and then launch Instruments.
Instruments will prompt you to choose a template; you want the Zombies template. Once you've chosen it, Instruments will create a trace document and run your application. Switch to your application (if it isn't already frontmost), then do whatever causes the crash.
If the crash really is a dead-object crash, Zombies will reveal it. You'll get a flag in Instruments's timeline saying something like “message sent to zombie object 0xd3c2b1a0”, and your program will probably exit shortly thereafter.
In that flag is a tiny little button that looks like this: ➲ except it'll be gray. Click on it.
That takes you to the history of that object (actually of that address, including any previous objects or other allocations that have started at that address). Show your Extended Detail Pane (the one that appears on the right showing a stack trace), then scroll down to the end and then move backward (upward) step by step through time, looking at releases and autoreleases, looking for the one that isn't balancing out the object's allocation or a retain.
The solution will probably involve one or more of:
Changing a property to be strong or weak rather than assign/unsafe_unretained
Adding a property where you previously did not strongly own an object
Rearchitecting some things, if it's not clear which of the above you need to do or if either one of them seems like a filthy hack
Switching to ARC to get weak properties and __weak instance variables (both of which get set to nil automatically when the referenced object dies) and to get local variables being implicitly initialized to nil
But it'll depend on what you find in Instruments. And, of course, there's the chance that your problem—the bad access—isn't a dead object at all and all of the above will not help you.
Try this:
if (layerFindIndicator!=nil){
if ([layerFindIndicator animationForKey:#"animateFound"]){
[layerFindIndicator removeAnimationForKey:#"animateFound"];
}
}
Also check to see if it is released else were.
EDIT:
Another thing I found was you didn't have an white space in the if. Your code should now look like this:
if (layerFindIndicator != nil){
if ([layerFindIndicator animationForKey:#"animateFound"]){
[layerFindIndicator removeAnimationForKey:#"animateFound"];
}
}