Skip to content

Latest commit

 

History

History
75 lines (64 loc) · 1.7 KB

File metadata and controls

75 lines (64 loc) · 1.7 KB

Event system

Events are used as a messaging mechanism between different parts of the program. Most game engines use an event system, not just for handling input, but other kinds of news as well.

ddge::app::create()
    .plug_in(ddge::plugins::Events{})
    .register_event<WindowClosedEvent>();

This event system was built with the mechanism of the game loop in mind. Events may happen once or multiple times in the time of a game loop iteration. After an event is recorded in one iteration, it will get published in the next one, then disappear. This makes it so that each event can be acted on for exactly one iteration of the game loop after it was recorded.

A system that records an event
auto close_window(const Recorder<WindowClosedEvent>& recorder) -> void
{
    std::println("Window closed");
    recorder.record();
}
A system that reacts on the event
auto say_goodbye(const Reader<WindowClosedEvent>& reader) -> void
{
    for (auto event : reader.read()) {
        std::println("Goodbye window!");
    }
}
Example for events inside the game loop
ddge::scheduler::loop_until(
    ddge::scheduler::start_as(process_events)
        .then(say_goodbye)
        .then(close_window),
    window_is_open
)
Window closed
Goodbye window!
Window closed

An event can have any type. For our example it was

struct WindowClosedEvent {};

Finally, we have seen how to record events and react to them. The only question left is how to clear and swap the event buffers as it was described above.

Swap event buffer
auto process_events(const Processor& processor) -> void
{
    processor.process_events();
}