Add builtin frame time measurement.

GLArea automatically synchronizes to GDK's refresh rate, which may lead
to incorrect frame time measurements if it's not correctly measured.

This property is guaranteed to always contain the actual live frame
delta of the previous frame in render functions.
This commit is contained in:
Jarl Gullberg 2017-10-01 20:06:50 +02:00
parent 29863f13da
commit b1f90c380e
No known key found for this signature in database
GPG key ID: FBB69BD7CAE095A0

View file

@ -1,6 +1,7 @@
using System; using System;
using System.Threading; using System.Threading;
using System.ComponentModel; using System.ComponentModel;
using Gdk;
using OpenTK.Graphics; using OpenTK.Graphics;
using Gtk; using Gtk;
@ -20,6 +21,16 @@ namespace OpenTK
private IGraphicsContext _GraphicsContext; private IGraphicsContext _GraphicsContext;
private bool _Initialized = false; private bool _Initialized = false;
/// <summary>
/// The previous frame time reported by GTK.
/// </summary>
private double? PreviousFrameTime;
/// <summary>
/// Gets the time taken to render the last frame (in seconds).
/// </summary>
public double DeltaTime { get; private set; }
/// <summary> /// <summary>
/// The set <see cref="GraphicsContextFlags"/> for this widget. /// The set <see cref="GraphicsContextFlags"/> for this widget.
/// </summary> /// </summary>
@ -54,6 +65,7 @@ namespace OpenTK
GraphicsContextFlags = graphicsContextFlags; GraphicsContextFlags = graphicsContextFlags;
AddTickCallback(UpdateFrameTime);
SetRequiredVersion(glVersionMajor, glVersionMinor); SetRequiredVersion(glVersionMajor, glVersionMinor);
if (graphicsMode.Depth > 0) if (graphicsMode.Depth > 0)
@ -72,6 +84,31 @@ namespace OpenTK
} }
} }
/// <summary>
/// Updates the time delta with a new value from the last frame.
/// </summary>
/// <param name="widget">The sending widget.</param>
/// <param name="frameClock">The relevant frame clock.</param>
/// <returns>true if the callback should be called again; otherwise, false.</returns>
private bool UpdateFrameTime(Widget widget, FrameClock frameClock)
{
var frameTimeµSeconds = frameClock.FrameTime;
if (!PreviousFrameTime.HasValue)
{
PreviousFrameTime = frameTimeµSeconds;
return true;
}
var frameTimeSeconds = (frameTimeµSeconds - PreviousFrameTime) / 10e6;
DeltaTime = (float)frameTimeSeconds;
PreviousFrameTime = frameTimeµSeconds;
return true;
}
/// <summary> /// <summary>
/// Destructs this object. /// Destructs this object.
/// </summary> /// </summary>