using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading; using ComputeSharp.Interop; #if WINDOWS_UWP using ComputeSharp.Uwp.Extensions; #else using ComputeSharp.WinUI.Extensions; #endif #if WINDOWS_UWP namespace ComputeSharp.Uwp.Helpers; #else namespace ComputeSharp.WinUI.Helpers; #endif #pragma warning disable CS0420 /// partial class SwapChainManager { /// /// Starts the current render loop. /// /// The instance to use, if available. /// The instance to use to render frames. public async void StartRenderLoop(IFrameRequestQueue? frameRequestQueue, IShaderRunner shaderRunner) { default(ArgumentNullException).ThrowIfNull(shaderRunner); using (await this.setupSemaphore.LockAsync()) { // Here and in the calls below, only get a reference tracking lease when starting a render thread. // This avoids crashes when the panel has been disposed but some code (eg. event handlers) still // ends up calling into any of the APIs in this file, which is not intended but should not crash. using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); this.renderCancellationTokenSource?.Cancel(); await this.renderSemaphore.WaitAsync(); Thread newRenderThread = new(static args => ((SwapChainManager)args!).SwitchAndStartRenderLoop()); this.frameRequestQueue = frameRequestQueue; this.shaderRunner = shaderRunner; this.renderCancellationTokenSource = new CancellationTokenSource(); this.renderThread = newRenderThread; this.renderSemaphore = new SemaphoreSlim(0, 1); this.isResizePending = true; newRenderThread.Start(this); } } /// /// Stops the current render loop, if one is running. /// public async void StopRenderLoop() { // Stopping the render loop doesn't use a reference tracking lease on purpose. // This is to allow callers to stop the render loop even after disposing without // the method throwing an exception. Stopping a loop doesn't actually access any // native objects anyway, as it's just cancelling the cancellation token source. using (await this.setupSemaphore.LockAsync()) { this.renderCancellationTokenSource?.Cancel(); } } /// /// Queues a change in the dynamic resolution mode. /// /// Whether or not to use dynamic resolution. public async void QueueDynamicResolutionModeChange(bool isDynamicResolutionEnabled) { using (await this.setupSemaphore.LockAsync()) { // If there is a render thread currently running, stop it and restart it if (this.renderCancellationTokenSource?.IsCancellationRequested == false) { using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); this.renderCancellationTokenSource?.Cancel(); await this.renderSemaphore.WaitAsync(); Thread newRenderThread = new(static args => ((SwapChainManager)args!).SwitchAndStartRenderLoop()); this.renderCancellationTokenSource = new CancellationTokenSource(); this.renderThread = newRenderThread; this.renderSemaphore = new SemaphoreSlim(0, 1); this.isDynamicResolutionEnabled = isDynamicResolutionEnabled; this.isResizePending = true; newRenderThread.Start(this); } else { this.isDynamicResolutionEnabled = isDynamicResolutionEnabled; } } } /// /// Queues a change in the vertical sync mode. /// /// Whether or not to use vertical sync. public async void QueueVerticalSyncModeChange(bool isVerticalSyncEnabled) { using (await this.setupSemaphore.LockAsync()) { // The v-sync option can be toggled on the fly when not using dynamic resolution if (this.renderCancellationTokenSource?.IsCancellationRequested == false && this.isDynamicResolutionEnabled) { using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); this.renderCancellationTokenSource?.Cancel(); await this.renderSemaphore.WaitAsync(); Thread newRenderThread = new(static args => ((SwapChainManager)args!).SwitchAndStartRenderLoop()); this.renderCancellationTokenSource = new CancellationTokenSource(); this.renderThread = newRenderThread; this.renderSemaphore = new SemaphoreSlim(0, 1); this.syncInterval = isVerticalSyncEnabled ? 1u : 0u; newRenderThread.Start(this); } else { this.syncInterval = isVerticalSyncEnabled ? 1u : 0u; } } } /// /// Queues a resize operation. /// /// The width of the render resolution. /// The height of the render resolution. public void QueueResize(double width, double height) { this.width = (float)width; this.height = (float)height; this.isResizePending = true; } /// /// Queues a change in the composition scale factors. /// /// The composition scale on the X axis. /// The composition scale on the Y axis public void QueueCompositionScaleChange(double compositionScaleX, double compositionScaleY) { this.compositionScaleX = (float)compositionScaleX; this.compositionScaleY = (float)compositionScaleY; this.isResizePending = true; } /// /// Queues a change in the resolution scale factor. /// /// The resolution scale factor to use. public void QueueResolutionScaleChange(double resolutionScale) { this.resolutionScale = (float)resolutionScale; this.isResizePending = true; } /// /// Selects the right render loop to start. /// private void SwitchAndStartRenderLoop() { try { OnRenderingStarted(); if (this.isDynamicResolutionEnabled) { this.dynamicResolutionScale = this.resolutionScale; // These two leases are needed to ensure the manager isn't disposed while rendering is running using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); RenderLoopWithDynamicResolution(); } else { using ReferenceTracker.Lease _0 = GetReferenceTracker().GetLease(); RenderLoop(); } this.renderStopwatch?.Stop(); OnRenderingStopped(); } catch (Exception e) { this.renderStopwatch?.Stop(); OnRenderingFailed(e); } finally { _ = this.renderSemaphore.Release(); } } /// /// The core render loop. /// [MethodImpl(MethodImplOptions.NoInlining)] private void RenderLoop() { Stopwatch renderStopwatch = this.renderStopwatch ??= new(); CancellationToken cancellationToken = this.renderCancellationTokenSource!.Token; if (!OnFrameRequest(out object? parameter, cancellationToken)) { return; } OnResize(); // Start the initial frame separately, before the timer starts. This ensures that // resuming after a pause correctly renders the first frame at the right time. if (OnUpdate(renderStopwatch.Elapsed, parameter)) { OnWaitForPresent(); OnPresent(); } renderStopwatch.Start(); // Main render loop, until cancellation is requested while (!cancellationToken.IsCancellationRequested) { if (!OnFrameRequest(out parameter, cancellationToken)) { return; } OnResize(); if (OnUpdate(renderStopwatch.Elapsed, parameter)) { OnWaitForPresent(); OnPresent(); } } } /// /// Gets the instance to use in . /// /// The instance to use. private unsafe partial void OnGetDynamicResolutionManager(out DynamicResolutionManager resolutionManager); /// /// The core render loop with dynamic resolution. /// [MethodImpl(MethodImplOptions.NoInlining)] private unsafe void RenderLoopWithDynamicResolution() { Stopwatch renderStopwatch = this.renderStopwatch ??= new(); Stopwatch frameStopwatch = new(); CancellationToken cancellationToken = this.renderCancellationTokenSource!.Token; OnGetDynamicResolutionManager(out DynamicResolutionManager resolutionManager); if (!OnFrameRequest(out object? parameter, cancellationToken)) { return; } OnResize(); if (OnUpdate(renderStopwatch.Elapsed, parameter)) { OnWaitForPresent(); OnPresent(); } renderStopwatch.Start(); while (!cancellationToken.IsCancellationRequested) { if (!OnFrameRequest(out parameter, cancellationToken)) { return; } OnResize(); frameStopwatch.Restart(); if (OnUpdate(renderStopwatch.Elapsed, parameter)) { frameStopwatch.Stop(); // The time spent waiting for present isn't included in the frame time, as when v-sync is // enabled it corresponds to the time spent waiting for the v-blank. If it was included, // then the actual framerate would never exceed the target one, meaning that if dynamic // resolution is enabled, the resolution scale could only keep decreasing without ever // being able to be increased again, as the framerate would never exceed the target. // Simply not counting the time spent waiting for that works around the issue. OnWaitForPresent(); frameStopwatch.Start(); OnPresent(); // Evaluate the dynamic resolution frame time step if (resolutionManager.Advance(frameStopwatch.ElapsedTicks, ref this.dynamicResolutionScale)) { this.isResizePending = true; } } } } /// /// Waits for a new frame request and retrieves its parameter. /// /// The input parameter for the frame to render. /// A token to cancel waiting for a new frame. /// Whether the operation was canceled. private bool OnFrameRequest(out object? parameter, CancellationToken token) { if (this.frameRequestQueue is IFrameRequestQueue frameRequestQueue) { [MethodImpl(MethodImplOptions.NoInlining)] static bool WaitForFrameRequest(IFrameRequestQueue frameRequestQueue, out object? parameter, CancellationToken token) { try { // Wait for a new frame request frameRequestQueue.Dequeue(out parameter, token); return true; } catch (OperationCanceledException) { parameter = null; return false; } } return WaitForFrameRequest(frameRequestQueue, out parameter, token); } parameter = null; return true; } /// /// Resizes the current application, if needed. /// private void OnResize() { if (this.isResizePending) { ApplyResize(); this.isResizePending = false; } } /// /// Updates the render resolution, if needed, and renders a new frame. /// /// The current time since the start of the application. /// The input parameter for the frame being rendered. /// Whether or not to present the resulting frame. private bool OnUpdate(TimeSpan time, object? parameter) { return this.shaderRunner!.TryExecute(this.texture!, time, parameter); } /// /// Waits for the panel to be ready to present a new frame for the current application. /// private unsafe partial void OnWaitForPresent(); /// /// Presents the last rendered frame for the current application. /// private unsafe partial void OnPresent(); /// /// Raises . /// private void OnRenderingStarted() { _ = this.dispatcherQueue.TryEnqueue(() => RenderingStarted?.Invoke(this.owner, EventArgs.Empty)); } /// /// Raises . /// private void OnRenderingStopped() { _ = this.dispatcherQueue.TryEnqueue(() => RenderingStopped?.Invoke(this.owner, EventArgs.Empty)); } /// /// Raises . /// /// The being thrown that caused rendering to stop. private void OnRenderingFailed(Exception e) { _ = this.dispatcherQueue.TryEnqueue(() => RenderingFailed?.Invoke(this.owner, new RenderingFailedEventArgs(e))); } /// /// Raises . /// private void OnDisposed() { _ = this.dispatcherQueue.TryEnqueue(() => Disposed?.Invoke(this.owner, EventArgs.Empty)); } /// /// Stops the current render loop, if one is running, and waits for it. /// /// This method doesn't check for disposal. private void UnsafeStopRenderLoopAndWait() { this.setupSemaphore.Wait(); this.renderCancellationTokenSource?.Cancel(); this.renderSemaphore.Wait(); } }