Last active
January 22, 2023 23:57
-
-
Save DrSpeedy/4fc6497e4af095d60b993ee9cfa54faa to your computer and use it in GitHub Desktop.
FTXUI Render Thread Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This code is from the Datarazer project. You may find more info here: https://wiltech.org/datarazer | |
// This code also to be used as an example for threaded rendering with FXTUI: https://github.com/ArthurSonzogni/FTXUI | |
int main() { | |
// ... | |
Element current_render = text("Loading application..."); | |
// Initialize renderer | |
std::mutex render_mtx; | |
std::mutex event_mtx; | |
auto component = Renderer([&] { | |
std::lock_guard<std::mutex> lock(render_mtx); | |
return current_render; | |
}); | |
// Setup event handling buffer to be executed on 2nd thread | |
std::vector<Event> event_buffer; | |
component |= CatchEvent([&](Event event) { | |
if (event.is_cursor_reporting()) { | |
return false; | |
} | |
{ | |
std::lock_guard<std::mutex> lock(event_mtx); | |
event_buffer.push_back(event); | |
} | |
return true; | |
}); | |
application_thread_running = true; | |
std::thread application_thread([&] { | |
// Initialize main classes | |
auto vc = new ViewWindowController(); | |
auto dc = new DiskController(); | |
auto mwin = std::shared_ptr<MainWindow>(new MainWindow(vc, dc)); | |
vc->AddWindow(mwin); | |
vc->SetActiveWindow(0); | |
// View Components | |
while (application_thread_running) { | |
// Build render buffer | |
auto new_frame = vc->Render(); | |
{ | |
std::lock_guard<std::mutex> lock(render_mtx); | |
current_render = new_frame; | |
} | |
// Handle events this frame | |
{ | |
std::lock_guard<std::mutex> lock(event_mtx); | |
while (event_buffer.size() != 0) { | |
auto event = *(event_buffer.begin()); | |
vc->OnUserInput(event); | |
event_buffer.erase(event_buffer.begin()); | |
} | |
} | |
// Force FTXUI to refresh the frame | |
screen.Post(Event::Custom); | |
std::this_thread::sleep_for(0.001s); | |
} | |
// stop application | |
delete vc; | |
delete dc; | |
} | |
// Start FTXUI on the main thread | |
screen.Loop(component); | |
exit(EXIT_SUCCESS); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment