Kanzi  3.9.4
Kanzi Engine API
kanzi::MainLoopScheduler Class Referencefinal

MainLoopScheduler implements the Kanzi application main loop in form of a customizable sequence of stages, each consisting of a sequence of tasks, where a task is any callable, including functions, function objects, and lambdas. More...

#include <kanzi/core.ui/main_loop/main_loop_scheduler.hpp>

Classes

struct  TaskInfo
 TaskInfo is a structure containing information related to a task. More...
 

Public Types

Enumerations.
enum  TaskRecurrence { TaskRecurrence::Recurring, TaskRecurrence::OneTime }
 Enumeration for task recurrence options. More...
 
enum  TimerRecurrence { TimerRecurrence::Recurring, TimerRecurrence::OneTime }
 Enumeration for timer recurrence options. More...
 
Public types and aliases.
using Task = function< void(chrono::nanoseconds)>
 Type alias for stage tasks. More...
 
using TimerTask = function< void(chrono::nanoseconds, unsigned int)>
 Type alias for timer tasks. More...
 
using Precondition = function< bool(void)>
 Type alias for stage precondition callbacks. More...
 
using Callback = function< void(void)>
 Type alias for general callbacks. More...
 
using OnSuspendCallback = function< optional< chrono::nanoseconds >(chrono::nanoseconds)>
 Type alias for on-suspension callbacks. More...
 
using StageSequenceContainer = stable_vector< Stage * >
 Type alias for container of the execution sequence of the stages. More...
 
using TaskInfoContainer = vector< TaskInfo >
 Alias for the vector of TaskInfo instances. More...
 

Public Member Functions

MainLoopTimerToken appendTimer (const Stage &stage, FixedString name, TimerRecurrence recurrence, chrono::nanoseconds interval, TimerTask task)
 Adds a timer task to be executed after a stage in the main loop. More...
 
MainLoopTimerToken appendTimer (const Stage &stage, MetadataGeneratedName name, TimerRecurrence recurrence, chrono::nanoseconds interval, TimerTask task)
 Adds a timer task to be executed after a stage in the main loop. More...
 
MainLoopTimerToken prependTimer (const Stage &stage, FixedString name, TimerRecurrence recurrence, chrono::nanoseconds interval, TimerTask task)
 /name Timer. More...
 
MainLoopTimerToken prependTimer (const Stage &stage, MetadataGeneratedName name, TimerRecurrence recurrence, chrono::nanoseconds interval, TimerTask task)
 Adds a timer task to be executed before a stage in the main loop. More...
 
bool removeTimer (const MainLoopTimerToken &token)
 Removes a timer task from the main loop. More...
 
Constructors and destructor.
 MainLoopScheduler ()
 Constructor. More...
 
 ~MainLoopScheduler ()
 Destructor. More...
 
 MainLoopScheduler (const MainLoopScheduler &)=delete
 
MainLoopScheduleroperator= (const MainLoopScheduler &)=delete
 
 MainLoopScheduler (MainLoopScheduler &&)=delete
 
MainLoopScheduleroperator= (MainLoopScheduler &&)=delete
 
Main loop entry points.
void loopMain ()
 Executes the whole application main loop, along with automatic suspension and frame rate control. More...
 
void loopRunning ()
 Executes the Running part of the main loop, along with automatic suspension and frame rate control. More...
 
bool run ()
 Executes a single iteration of the main loop in the Running state, with elapsed duration observed using the internal clock. More...
 
bool run (chrono::nanoseconds lastFrameDuration)
 Executes a single iteration of the main loop in the Running state with provided elapsed duration. More...
 
void loopPaused ()
 Executes the Paused part of the main loop. More...
 
void suspend ()
 Puts the application thread into revocable suspension for the duration determined by the frame limit and callback set with setOnSuspendCallback(). More...
 
void yield ()
 Puts the application thread into irrevocable suspension till the next frame border. More...
 
void executeStage (const Stage &stage)
 Executes all tasks mapped to a stage of the main loop. More...
 
State control.
void pause ()
 Pauses the main loop and changes its state to Paused. More...
 
void resume ()
 Resumes the main loop and changes its state back to Running. More...
 
void quit ()
 Quits the main loop and changes its state to Quitting. More...
 
MainLoopState getState () const
 Gets the main loop scheduler state. More...
 
void setCurrentFrameRendered ()
 Sets whether rendering was performed in the current frame. More...
 
bool isCurrentFrameRendered () const
 Returns whether rendering was performed in the current frame. More...
 
Stage control.
void setStageSequence (StageSequenceContainer stageSequence)
 Sets the sequence of execution of the main loop stages. More...
 
Task control.
MainLoopTaskToken prependTask (const Stage &stage, FixedString name, TaskRecurrence recurrence, Task task)
 Adds a task to the front of a stage. More...
 
MainLoopTaskToken prependTask (const Stage &stage, MetadataGeneratedName name, TaskRecurrence recurrence, Task task)
 Adds a task to the front of a stage. More...
 
MainLoopTaskToken appendTask (const Stage &stage, FixedString name, TaskRecurrence recurrence, Task task)
 Adds a task to the back of a stage. More...
 
MainLoopTaskToken appendTask (const Stage &stage, MetadataGeneratedName name, TaskRecurrence recurrence, Task task)
 Adds a task to the back of a stage. More...
 
bool removeTask (const Stage &stage, const MainLoopTaskToken &token)
 Removes a task from a stage. More...
 
bool replaceTask (const Stage &stage, const MainLoopTaskToken &token, Task task)
 Replaces a task in a stage with another one. More...
 
void clearTasks (const Stage &stage)
 Removes all tasks in a stage. More...
 
TaskInfoContainer getTaskInfo (const Stage &stage) const
 Returns a container with information about all tasks in a stage. More...
 
Task getTask (const Stage &stage, const MainLoopTaskToken &token) const
 Return a task in a stage with given token. More...
 
Callbacks.

/}

void setPrecondition (const Stage &stage, Precondition precondition)
 Sets a precondition for a stage. More...
 
void setOnSuspendCallback (OnSuspendCallback callback)
 Sets the OnSuspend callback. More...
 
void setOnPauseCallback (Callback callback)
 Sets the OnPause callback. More...
 
void setResumeCheckCallback (Callback callback)
 Sets the ResumeCheck callback. More...
 
void setOnResumeCallback (Callback callback)
 Sets the OnResume callback. More...
 
Event handle setters.
void setTaskDispatcherEventHandle (NativeEventHandle nativeHandle)
 Sets the native event handle that is used in waiting for the task dispatcher. More...
 
void setInputEventHandle (NativeEventHandle nativeHandle)
 Sets the native event handle that is used in waiting for user input. More...
 
Configurations.
void setFrameRateLimit (optional< unsigned int > frameRate)
 Sets the frame rate limit of the application. More...
 
void enableSuspendWhenIdle (bool suspendEnabled)
 Sets whether an application allows suspension. More...
 
bool isSuspendWhenIdleEnabled () const
 Returns whether an application allows suspension. More...
 
bool needsPolling () const
 Returns whether an event source needs polling. More...
 
Timing.
void resetClock ()
 Resets the internal clock of MainLoopScheduler. More...
 
void advanceFrame ()
 Advances the frame counter, and records last frame duration based on internal clock. More...
 
void advanceFrame (chrono::nanoseconds lastFrameDuration)
 Advances the frame counter, and records the given duration as last frame duration. More...
 
chrono::nanoseconds getLastFrameDuration () const
 Returns the duration of the last frame: the amount of time that passed between the start of the previous frame and the start of the current frame. More...
 
optional< chrono::nanoseconds > getSuspendDuration () const
 Suggests the duration of suspension based on configured frame limit, callback set with setOnSuspendCallback(), and the time elapsed since the start of frame based on the internal clock. More...
 
chrono::nanoseconds getYieldDuration () const
 Suggests the yield duration, which is the remaining frame allotment, based on the frame limit and time elapsed since the start of frame as per the internal clock. More...
 
optional< chrono::nanoseconds > getDurationUntilNextTimer () const
 Returns the time until the next timer task executes, based on internal clock. More...
 
optional< chrono::nanoseconds > getDurationUntilNextTimer (chrono::nanoseconds elapsedDuration) const
 Returns the time until the next timer task executes, based on provided elapsed time. More...
 
Profiling.
void initializeProfilerSampleBuffer (optional< size_t > sampleBufferSize)
 Initializes the sample buffer of main loop profiler. More...
 
MainLoopProfilerSharedPtr getProfiler ()
 Gets the main loop profiler. More...
 
uint64_t getFrameNumber ()
 Gets the current frame number in the main loop. More...
 

Detailed Description

MainLoopScheduler implements the Kanzi application main loop in form of a customizable sequence of stages, each consisting of a sequence of tasks, where a task is any callable, including functions, function objects, and lambdas.

It also provides the default Kanzi stages, along with platform specific mechanisms for automatic suspension, and frame rate control.

Application class owns an instance of MainLoopScheduler, and fills it with stage sequence and tasks. For more details, see the implementation of Application::initializeMainLoopTasks().

You can customize the application main loop by extending its stages with additional tasks, replacing existing tasks with your own implementations, or adding timer tasks to execute some functionality at regular intervals.

Examples

To modify contents of a stage:

// You can add a task to the back of a stage, so that it is last in the sequence.
// When you use this interface in the context of a task, and you add a task ahead
// in the sequence of the executing stage, Kanzi executes that task in the same main loop iteration.
// When you add a task, you must set the recurrence for that task.
// For example, when you set the task to be a one-time task, Kanzi executes it once and then discards it.
scheduler.appendTask(RenderStage,
kzMakeFixedString("PostRender"),
[](chrono::nanoseconds lastFrameDuration) {
doSomething(lastFrameDuration);
});
// You can add a task to the front of a stage, so that it is the first in the sequence.
// All interfaces that add tasks to a stage return tokens. You can use these tokens to access
// and modify the existing tasks in a stage.
// When you set a task to Recurring, Kanzi executes it on every iteration of respective stage,
// until you explicitly remove that task.
MainLoopTaskToken tokenPreRender = scheduler.prependTask(RenderStage,
kzMakeFixedString("PreRender"),
[](chrono::nanoseconds lastFrameDuration) {
doSomething(lastFrameDuration);
});
// You can replace a task using its token.
scheduler.replaceTask(RenderStage,
tokenPreRender,
[](chrono::nanoseconds lastFrameDuration) {
doSomething(lastFrameDuration);
});
// You can remove a task from its stage using its token.
scheduler.removeTask(RenderStage,
tokenPreRender);
// Clear an entire stage. For example, clear the stage when you want to implement
// the entire stage in your own way.
scheduler.clearTasks(RenderStage);

To observe contents of a stage:

// You can observe the contents of a stage, including task names, recurrence, and tokens.
// You can use this for debugging purposes.
// You can also use the tokens retrieved in this way to remove or replace specific tasks.
auto tasks = scheduler.getTaskInfo(RenderStage);
for (const auto& task : tasks)
{
doSomething(task.name, task.recurrence, task.token);
}

To add and remove a timer task:

// When you want Kanzi to execute a task at regular time intervals, you can add that task as a timer before or after a stage of the main loop.
// Use timer recurrence options to execute a timer only once or repeatedly.
// When a recurring timer elapses multiple times in a single iteration of the main loop, Kanzi executes that timer only once.
// Timer callback receives as arguments elapsed duration rounded down to a multiple of the interval of the timer and number of elapsed intervals.
MainLoopTimerToken timerToken = scheduler.appendTimer(UserStage,
kzMakeFixedString("MyTimer"),
chrono::seconds(1),
[](chrono::nanoseconds elapsedDuration, unsigned int repeatCount) {
doSomethingRepeatedly(elapsedDuration, repeatCount);
});
// You can remove existing timers by using their token.
scheduler.removeTimer(timerToken);

Member Typedef Documentation

◆ Task

using kanzi::MainLoopScheduler::Task = function<void(chrono::nanoseconds)>

Type alias for stage tasks.

Parameters
lastFrameDurationTime elapsed between start of last and current main loop iteration.

◆ TimerTask

using kanzi::MainLoopScheduler::TimerTask = function<void(chrono::nanoseconds, unsigned int)>

Type alias for timer tasks.

Parameters
elapsedDurationThe time since the last invocation or creation, rounded down to a multiple of the interval of the timer.
repeatCountThe number of elapsed intervals since the last invocation.

◆ Precondition

using kanzi::MainLoopScheduler::Precondition = function<bool(void)>

Type alias for stage precondition callbacks.

Returns
A boolean value that Kanzi uses to control the execution of the respective stage. Kanzi executes a Stage only if the return from its precondition is true, or no precondition is attached.

◆ Callback

using kanzi::MainLoopScheduler::Callback = function<void(void)>

Type alias for general callbacks.

◆ OnSuspendCallback

using kanzi::MainLoopScheduler::OnSuspendCallback = function<optional<chrono::nanoseconds>(chrono::nanoseconds)>

Type alias for on-suspension callbacks.

Parameters
remainingFrameAllotmentThe time remaining in the frame based on the configured frame rate limit and elapsed time as per internal clock.
Returns
Duration of suspension. Nullopt implies indefinite suspension.

◆ StageSequenceContainer

Type alias for container of the execution sequence of the stages.

◆ TaskInfoContainer

Alias for the vector of TaskInfo instances.

Member Enumeration Documentation

◆ TaskRecurrence

Enumeration for task recurrence options.

Enumerator
Recurring 

Kanzi executes the task every time it executes the stage that owns this task, until you remove this task.

OneTime 

Kanzi executes the task once and then discards it.

◆ TimerRecurrence

Enumeration for timer recurrence options.

Enumerator
Recurring 

Kanzi executes the timer tasks periodically at specified intervals.

When a recurring timer elapses multiple times in a single iteration of the Kanzi main loop, Kanzi executes that timer only once, but provides the number of elapsed intervals through its callback interface.

OneTime 

Kanzi executes the timer once in a main loop iteration where the specified time since their addition has elapsed.

Constructor & Destructor Documentation

◆ MainLoopScheduler() [1/3]

kanzi::MainLoopScheduler::MainLoopScheduler ( )
explicit

Constructor.

◆ ~MainLoopScheduler()

kanzi::MainLoopScheduler::~MainLoopScheduler ( )

Destructor.

◆ MainLoopScheduler() [2/3]

kanzi::MainLoopScheduler::MainLoopScheduler ( const MainLoopScheduler )
delete

◆ MainLoopScheduler() [3/3]

kanzi::MainLoopScheduler::MainLoopScheduler ( MainLoopScheduler &&  )
delete

Member Function Documentation

◆ operator=() [1/2]

MainLoopScheduler& kanzi::MainLoopScheduler::operator= ( const MainLoopScheduler )
delete

◆ operator=() [2/2]

MainLoopScheduler& kanzi::MainLoopScheduler::operator= ( MainLoopScheduler &&  )
delete

◆ loopMain()

void kanzi::MainLoopScheduler::loopMain ( )

Executes the whole application main loop, along with automatic suspension and frame rate control.

◆ loopRunning()

void kanzi::MainLoopScheduler::loopRunning ( )

Executes the Running part of the main loop, along with automatic suspension and frame rate control.

An application exits this function only when it is no longer in the Running state.

◆ run() [1/2]

bool kanzi::MainLoopScheduler::run ( )

Executes a single iteration of the main loop in the Running state, with elapsed duration observed using the internal clock.

Returns
A boolean value that marks whether rendering was performed in the current frame. The main loop uses this to determine whether to perform suspension or yielding. You can set this with the MainLoopScheduler::setCurrentFrameRendered().

◆ run() [2/2]

bool kanzi::MainLoopScheduler::run ( chrono::nanoseconds  lastFrameDuration)

Executes a single iteration of the main loop in the Running state with provided elapsed duration.

Parameters
lastFrameDurationThe time elapsed between the start of the last and the current main loop iteration.
Returns
A boolean value that marks whether rendering was performed in the current frame. The main loop uses this to determine whether to perform suspension or yielding. You can set this with the MainLoopScheduler::setCurrentFrameRendered().

◆ loopPaused()

void kanzi::MainLoopScheduler::loopPaused ( )

Executes the Paused part of the main loop.

An application exits this function only when it is no longer in the Paused state.

◆ suspend()

void kanzi::MainLoopScheduler::suspend ( )

Puts the application thread into revocable suspension for the duration determined by the frame limit and callback set with setOnSuspendCallback().

Input events and task dispatcher signals can revoke this suspension before the duration expires.

◆ yield()

void kanzi::MainLoopScheduler::yield ( )

Puts the application thread into irrevocable suspension till the next frame border.

◆ executeStage()

void kanzi::MainLoopScheduler::executeStage ( const Stage stage)

Executes all tasks mapped to a stage of the main loop.

Passes the duration of the last frame to each task.

Parameters
stageStage to execute.

◆ pause()

void kanzi::MainLoopScheduler::pause ( )

Pauses the main loop and changes its state to Paused.

◆ resume()

void kanzi::MainLoopScheduler::resume ( )

Resumes the main loop and changes its state back to Running.

◆ quit()

void kanzi::MainLoopScheduler::quit ( )

Quits the main loop and changes its state to Quitting.

◆ getState()

MainLoopState kanzi::MainLoopScheduler::getState ( ) const

Gets the main loop scheduler state.

Returns
Current state of the main loop scheduler.

◆ setCurrentFrameRendered()

void kanzi::MainLoopScheduler::setCurrentFrameRendered ( )

Sets whether rendering was performed in the current frame.

Call this function from a task in the Render stage to inform the main loop that the task performed rendering. The main loop uses this as a precondition for executing the Present stage for a frame.

See also
MainLoopScheduler::setCurrentFrameRendered(), MainLoopScheduler::run().

◆ isCurrentFrameRendered()

bool kanzi::MainLoopScheduler::isCurrentFrameRendered ( ) const

Returns whether rendering was performed in the current frame.

The main loop uses this as a precondition for executing the Present stage for a frame.

See also
MainLoopScheduler::setCurrentFrameRendered(), MainLoopScheduler::run().
Returns
If rendering was performed in the current frame, true, otherwise false.

◆ setStageSequence()

void kanzi::MainLoopScheduler::setStageSequence ( StageSequenceContainer  stageSequence)

Sets the sequence of execution of the main loop stages.

Parameters
stageSequenceContainer of stage sequence.

◆ prependTask() [1/2]

MainLoopTaskToken kanzi::MainLoopScheduler::prependTask ( const Stage stage,
FixedString  name,
TaskRecurrence  recurrence,
Task  task 
)

Adds a task to the front of a stage.

Use this overload when you have the task name available at compile time.

Parameters
stageReference to the stage.
nameName for the task. Must be a string literal.
recurrenceRecurrence choice for the task that you want to insert.
taskThe task that you want to insert.
Returns
Token of the added task. You can use that token to remove or replace the task.

◆ prependTask() [2/2]

MainLoopTaskToken kanzi::MainLoopScheduler::prependTask ( const Stage stage,
MetadataGeneratedName  name,
TaskRecurrence  recurrence,
Task  task 
)

Adds a task to the front of a stage.

Use this overload when you do not have the task name available at compile time.

Parameters
stageReference to the stage.
nameName for the task.
recurrenceRecurrence choice for the task that you want to insert.
taskThe task that you want to insert.
Returns
Token of the added task. You can use that token to remove or replace the task.

◆ appendTask() [1/2]

MainLoopTaskToken kanzi::MainLoopScheduler::appendTask ( const Stage stage,
FixedString  name,
TaskRecurrence  recurrence,
Task  task 
)

Adds a task to the back of a stage.

Use this overload when you have the task name available at compile time.

Parameters
stageReference to the stage.
nameName for the task. Must be a string literal.
recurrenceRecurrence choice for the task that you want to insert.
taskThe task that you want to insert.
Returns
Token of the added task. You can use that token to remove or replace the task.

◆ appendTask() [2/2]

MainLoopTaskToken kanzi::MainLoopScheduler::appendTask ( const Stage stage,
MetadataGeneratedName  name,
TaskRecurrence  recurrence,
Task  task 
)

Adds a task to the back of a stage.

Use this overload when you do not have the task name available at compile time.

Parameters
stageReference to the stage.
nameName for the task.
recurrenceRecurrence choice for the task that you want to insert.
taskThe task that you want to insert.
Returns
Token of the added task. You can use that token to remove or replace the task.

◆ removeTask()

bool kanzi::MainLoopScheduler::removeTask ( const Stage stage,
const MainLoopTaskToken token 
)

Removes a task from a stage.

Parameters
stageReference to the stage.
tokenToken of the task.
Returns
If removal is successful, returns true. If the function cannot find the matching token, returns false.

◆ replaceTask()

bool kanzi::MainLoopScheduler::replaceTask ( const Stage stage,
const MainLoopTaskToken token,
Task  task 
)

Replaces a task in a stage with another one.

Parameters
stageReference to the stage.
tokenToken of the task.
taskThe task with which to replace the current task.
Returns
If replacement is successful, returns true. If the function cannot find the matching token, returns false.

◆ clearTasks()

void kanzi::MainLoopScheduler::clearTasks ( const Stage stage)

Removes all tasks in a stage.

Parameters
stageReference to the stage.

◆ getTaskInfo()

TaskInfoContainer kanzi::MainLoopScheduler::getTaskInfo ( const Stage stage) const

Returns a container with information about all tasks in a stage.

Parameters
stageReference to the stage.
Returns
Vector that contains the task information.

◆ getTask()

Task kanzi::MainLoopScheduler::getTask ( const Stage stage,
const MainLoopTaskToken token 
) const

Return a task in a stage with given token.

Parameters
stageReference to the stage.
tokenToken of the task.
Returns
If token is found, returns a copy of the task. If not found, returns invalid (default constructed) task.

◆ prependTimer() [1/2]

MainLoopTimerToken kanzi::MainLoopScheduler::prependTimer ( const Stage stage,
FixedString  name,
TimerRecurrence  recurrence,
chrono::nanoseconds  interval,
TimerTask  task 
)

/name Timer.

/{ Adds a timer task to be executed before a stage in the main loop. Use this overload when you have the task name available at compile time.

Parameters
stageReference to the stage.
nameName for the task. Must be a string literal.
recurrenceRecurrence type of the task.
intervalThe amount of time after which to execute the task.
taskThe task.
Returns
Token of the added task. You can use this token to remove the task.

◆ prependTimer() [2/2]

MainLoopTimerToken kanzi::MainLoopScheduler::prependTimer ( const Stage stage,
MetadataGeneratedName  name,
TimerRecurrence  recurrence,
chrono::nanoseconds  interval,
TimerTask  task 
)

Adds a timer task to be executed before a stage in the main loop.

Use this overload when you do not have the task name available at compile time.

Parameters
stageReference to the stage.
nameName for the task.
recurrenceRecurrence type of the task.
intervalThe amount of time after which to execute the task.
taskThe task.
Returns
Token of the added task. You can use this token to remove the task.

◆ appendTimer() [1/2]

MainLoopTimerToken kanzi::MainLoopScheduler::appendTimer ( const Stage stage,
FixedString  name,
TimerRecurrence  recurrence,
chrono::nanoseconds  interval,
TimerTask  task 
)

Adds a timer task to be executed after a stage in the main loop.

Use this overload when you have the task name available at compile time.

Parameters
stageReference to the stage.
nameName for the task. Must be a string literal.
recurrenceRecurrence type of the task.
intervalThe amount of time after which to execute the task.
taskThe task.
Returns
Token of the added task. You can use this token to remove the task.

◆ appendTimer() [2/2]

MainLoopTimerToken kanzi::MainLoopScheduler::appendTimer ( const Stage stage,
MetadataGeneratedName  name,
TimerRecurrence  recurrence,
chrono::nanoseconds  interval,
TimerTask  task 
)

Adds a timer task to be executed after a stage in the main loop.

Use this overload when you do not have the task name available at compile time.

Parameters
stageReference to the stage.
nameName for the task.
recurrenceRecurrence type of the task.
intervalThe amount of time after which to execute the task.
taskThe task.
Returns
Token of the added task. You can use this token to remove the task.

◆ removeTimer()

bool kanzi::MainLoopScheduler::removeTimer ( const MainLoopTimerToken token)

Removes a timer task from the main loop.

Parameters
tokenToken of the task.
Returns
If removal is successful, returns true. If the function cannot find the matching token, returns false.

◆ setPrecondition()

void kanzi::MainLoopScheduler::setPrecondition ( const Stage stage,
Precondition  precondition 
)

Sets a precondition for a stage.

Kanzi executes a Stage only if the return from its precondition is true, or no precondition is attached.

Parameters
stageReference to a stage.
preconditionPrecondition for the stage.

◆ setOnSuspendCallback()

void kanzi::MainLoopScheduler::setOnSuspendCallback ( OnSuspendCallback  callback)

Sets the OnSuspend callback.

Kanzi executes this callback every time the main loop enters suspension, passing as argument the time remaining in frame, based on configured frame rate limit and elapsed time as per internal clock. The callback should return of the following:

  • Desired suspension duration in nanoseconds.
  • Nullopt for an indefinite suspend.
  • 0 to cancel the suspend.
    Parameters
    callbackThe callback to use.

◆ setOnPauseCallback()

void kanzi::MainLoopScheduler::setOnPauseCallback ( Callback  callback)

Sets the OnPause callback.

Kanzi executes this callback every time when the main loop enters the Paused state.

Parameters
callbackThe callback to use.

◆ setResumeCheckCallback()

void kanzi::MainLoopScheduler::setResumeCheckCallback ( Callback  callback)

Sets the ResumeCheck callback.

Kanzi executes this callback in every iteration of the Paused loop.

Parameters
callbackThe callback to use.

◆ setOnResumeCallback()

void kanzi::MainLoopScheduler::setOnResumeCallback ( Callback  callback)

Sets the OnResume callback.

Kanzi executes this callback every time when the main loop exits the Paused state.

Parameters
callbackThe callback to use.

◆ setTaskDispatcherEventHandle()

void kanzi::MainLoopScheduler::setTaskDispatcherEventHandle ( NativeEventHandle  nativeHandle)

Sets the native event handle that is used in waiting for the task dispatcher.

Parameters
nativeHandleNative event handle bound to the task dispatcher.

◆ setInputEventHandle()

void kanzi::MainLoopScheduler::setInputEventHandle ( NativeEventHandle  nativeHandle)

Sets the native event handle that is used in waiting for user input.

Parameters
nativeHandleNative event handle bound to input.

◆ setFrameRateLimit()

void kanzi::MainLoopScheduler::setFrameRateLimit ( optional< unsigned int >  frameRate)

Sets the frame rate limit of the application.

This sets an upper limit on the number of frames rendered by Kanzi every second.

Parameters
frameRateThe number of frames to render every second. To disable frame rate limit, use nullopt or 0.

◆ enableSuspendWhenIdle()

void kanzi::MainLoopScheduler::enableSuspendWhenIdle ( bool  suspendEnabled)

Sets whether an application allows suspension.

Parameters
suspendEnabledIf the application allows suspension, use true, otherwise false.

◆ isSuspendWhenIdleEnabled()

bool kanzi::MainLoopScheduler::isSuspendWhenIdleEnabled ( ) const

Returns whether an application allows suspension.

Returns
If the application allows suspension, true, otherwise false.

◆ needsPolling()

bool kanzi::MainLoopScheduler::needsPolling ( ) const

Returns whether an event source needs polling.

Polling is needed when an event source does not have the capability to abort suspension.

Returns
When at least one event source needs polling, true.

◆ resetClock()

void kanzi::MainLoopScheduler::resetClock ( )

Resets the internal clock of MainLoopScheduler.

A platform back-end typically calls this interface whenever switching the application from another state to Running state.

◆ advanceFrame() [1/2]

void kanzi::MainLoopScheduler::advanceFrame ( )

Advances the frame counter, and records last frame duration based on internal clock.

Additionally, records difference between the observed last frame duration and frame allotment based on set frame rate limit, which is used to compensate the allotment of subsequent frames.

◆ advanceFrame() [2/2]

void kanzi::MainLoopScheduler::advanceFrame ( chrono::nanoseconds  lastFrameDuration)

Advances the frame counter, and records the given duration as last frame duration.

Parameters
lastFrameDurationTime elapsed since the start of the previous frame.

◆ getLastFrameDuration()

chrono::nanoseconds kanzi::MainLoopScheduler::getLastFrameDuration ( ) const

Returns the duration of the last frame: the amount of time that passed between the start of the previous frame and the start of the current frame.

Returns
The duration of the last frame in nanoseconds.

◆ getSuspendDuration()

optional<chrono::nanoseconds> kanzi::MainLoopScheduler::getSuspendDuration ( ) const

Suggests the duration of suspension based on configured frame limit, callback set with setOnSuspendCallback(), and the time elapsed since the start of frame based on the internal clock.

Returns
The duration of suspension in nanoseconds. When the application is suspended indefinitely, returns nullopt.

◆ getYieldDuration()

chrono::nanoseconds kanzi::MainLoopScheduler::getYieldDuration ( ) const

Suggests the yield duration, which is the remaining frame allotment, based on the frame limit and time elapsed since the start of frame as per the internal clock.

Additionally, adjusts the result based on the differences between the observed frame durations and the desired frame allotment based on set frame rate limit.

Returns
The duration of yield in nanoseconds.

◆ getDurationUntilNextTimer() [1/2]

optional<chrono::nanoseconds> kanzi::MainLoopScheduler::getDurationUntilNextTimer ( ) const

Returns the time until the next timer task executes, based on internal clock.

Returns
optional<chrono::nanoseconds> Time until the next timer task executes. If no timers are active, returns nullopt.

◆ getDurationUntilNextTimer() [2/2]

optional<chrono::nanoseconds> kanzi::MainLoopScheduler::getDurationUntilNextTimer ( chrono::nanoseconds  elapsedDuration) const

Returns the time until the next timer task executes, based on provided elapsed time.

Parameters
elapsedDurationTime elapsed since the start of current frame.
Returns
optional<chrono::nanoseconds> Time until the next timer task executes. If no timers are active, returns nullopt.

◆ initializeProfilerSampleBuffer()

void kanzi::MainLoopScheduler::initializeProfilerSampleBuffer ( optional< size_t >  sampleBufferSize)

Initializes the sample buffer of main loop profiler.

Only effective in profiling builds.

Parameters
sampleBufferSizeOptional size of sample buffer. If nullopt, Kanzi uses KZ_PROFILING_MAIN_LOOP.

◆ getProfiler()

MainLoopProfilerSharedPtr kanzi::MainLoopScheduler::getProfiler ( )

Gets the main loop profiler.

Returns
The pointer to the main loop profiler.

◆ getFrameNumber()

uint64_t kanzi::MainLoopScheduler::getFrameNumber ( )

Gets the current frame number in the main loop.

Returns
Frame number.

The documentation for this class was generated from the following file: