using System; using System.Diagnostics; using System.Drawing; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using TerraFX.Interop; using FX = TerraFX.Interop.Windows; namespace ComputeSharp.Sample.SwapChain { internal abstract class Win32Application { public abstract string Title { get; } public abstract void OnInitialize(Size size, HWND hwnd); public abstract void OnResize(Size size); public abstract void OnUpdate(TimeSpan time); } /// /// A helper class to manage the creation and execution of Win32 applications. /// internal unsafe static class Win32ApplicationRunner { /// /// Whether or not a resize operation is in progress. /// private static bool isResizing = false; /// /// Whether or not the application is currently paused. /// private static bool isPaused = false; /// /// The for the application window. /// private static HWND hwnd; /// /// The current size of the application window. /// private static Size windowSize; /// /// A instance used to track the elapsed time for the application. /// private static Stopwatch stopwatch = null!; /// /// The application being run. /// private static Win32Application application = null!; /// /// The number of elapsed milliseconds since the window title was last updated. /// private static long elapsedMillisecondsForLastTitleUpdate; /// /// The number of elapsed frames since the window title was last updated. /// private static int elapsedFramesSinceLastTitleUpdate; /// /// Runs a specified application and starts the main loop to update its state. /// This is the entry point for a given application of type , and it should be /// called as soon as the process is launched, excluding any other additional initialization needed. /// To launch an application, simply add this line to the project being used: /// Win32ApplicationRunner.Run<MyApplication>(); /// /// The type of application being launched. /// The exit code for the application. public static int Run() where T : Win32Application, new() { application = new T(); IntPtr hInstance = FX.GetModuleHandleW(null); uint width = 1280; uint height = 720; fixed (char* name = Assembly.GetExecutingAssembly().FullName) fixed (char* windowTitle = application.Title) { // Initialize the window class WNDCLASSEXW windowClassEx = new() { cbSize = (uint)sizeof(WNDCLASSEXW), style = FX.CS_HREDRAW | FX.CS_VREDRAW, lpfnWndProc = &WindowProc, hInstance = hInstance, hCursor = FX.LoadCursorW(IntPtr.Zero, FX.MAKEINTRESOURCE(32512)), lpszClassName = (ushort*)name }; // Register the window class _ = FX.RegisterClassExW(&windowClassEx); Rectangle windowRect = new(0, 0, (int)width, (int)height); // Set the target window size _ = FX.AdjustWindowRect((RECT*)&windowRect, FX.WS_OVERLAPPEDWINDOW, FX.FALSE); height = (uint)(windowRect.Bottom - windowRect.Top); width = (uint)(windowRect.Right - windowRect.Left); // Create the window and store a handle to it hwnd = FX.CreateWindowExW( 0, windowClassEx.lpszClassName, (ushort*)windowTitle, FX.WS_OVERLAPPEDWINDOW, FX.CW_USEDEFAULT, FX.CW_USEDEFAULT, (int)width, (int)height, HWND.NULL, HMENU.NULL, hInstance, (void*)GCHandle.ToIntPtr(GCHandle.Alloc(application)) ); } windowSize = new Size((int)height, (int)width); // Initialize the application application.OnInitialize(windowSize, hwnd); // Display the window _ = FX.ShowWindow(hwnd, FX.SW_SHOWDEFAULT); // Start the timer stopwatch = Stopwatch.StartNew(); MSG msg = default; // Process any messages in the queue while (msg.message != FX.WM_QUIT) { if (FX.PeekMessageW(&msg, HWND.NULL, 0, 0, FX.PM_REMOVE) != 0) { _ = FX.TranslateMessage(&msg); _ = FX.DispatchMessageW(&msg); } else if (!isPaused || true) { RunApp(); } else { Thread.Sleep(100); } } // Return this part of the WM_QUIT message to Windows return (int)msg.wParam; } /// /// The application state update method that is invoked within the main application loop. /// private static void RunApp() { // Update window title approx every second if (stopwatch.ElapsedMilliseconds - elapsedMillisecondsForLastTitleUpdate >= 1000) { string title = isPaused switch { true => $"{application.Title} - Paused", false => $"{application.Title} - FPS: {elapsedFramesSinceLastTitleUpdate}" }; fixed (char* pTitle = title) { _ = FX.SetWindowTextW(hwnd, (ushort*)pTitle); } elapsedMillisecondsForLastTitleUpdate = stopwatch.ElapsedMilliseconds; elapsedFramesSinceLastTitleUpdate = 0; } // Update the application state application.OnUpdate(stopwatch.Elapsed); elapsedFramesSinceLastTitleUpdate++; } /// /// Processes incoming messages for a window. /// /// A handle to the window. /// The message. /// Additional message information (the contents depend on the value of ). /// Additional message information (the contents depend on the value of ). /// The result of the message processing for the input message. [UnmanagedCallersOnly] private static nint WindowProc(IntPtr hwnd, uint uMsg, nuint wParam, nint lParam) { switch (uMsg) { // Change the paused state on window activation case FX.WM_ACTIVATE: { if (FX.LOWORD(wParam) == FX.WA_INACTIVE) { isPaused = true; } else { isPaused = false; } return 0; } // Change the paused state when ESC is pressed case FX.WM_KEYDOWN: { if ((ConsoleKey)wParam == ConsoleKey.Escape) { if (isPaused) { FX.SetCapture(hwnd); } else { FX.ReleaseCapture(); } isPaused = !isPaused; } return 0; } // Window resize started case FX.WM_ENTERSIZEMOVE: { isResizing = true; return 0; } // Window resize completed case FX.WM_EXITSIZEMOVE: { isResizing = false; application.OnResize(windowSize); return 0; } case FX.WM_SIZE: { uint size = (uint)lParam; windowSize = new Size(FX.LOWORD(size), FX.HIWORD(size)); if (!isResizing && wParam != FX.SIZE_MINIMIZED) { application.OnResize(windowSize); } return 0; } // Shutdown case FX.WM_DESTROY: { FX.PostQuitMessage(0); return 0; } } return FX.DefWindowProcW(hwnd, uMsg, wParam, lParam); } } }