use libuv event loop in the glfw view

Integrates libuv's default loop with GLFW's glfwWaitEvents() call. See https://github.com/joyent/libuv/issues/1246 for more details on integrating event loops.

fixes #149
This commit is contained in:
Konstantin Käfer
2014-04-22 16:54:55 +02:00
parent 9ff9d0edb5
commit 1ecff57829
9 changed files with 108 additions and 281 deletions

View File

@@ -1,7 +1,40 @@
#include "glfw_view.hpp"
#ifndef HAVE_KQUEUE
# if defined(__APPLE__) || \
defined(__DragonFly__) || \
defined(__FreeBSD__) || \
defined(__OpenBSD__) || \
defined(__NetBSD__)
# define HAVE_KQUEUE 1
# endif
#endif
#ifndef HAVE_EPOLL
# if defined(__linux__)
# define HAVE_EPOLL 1
# endif
#endif
#if defined(HAVE_KQUEUE) || defined(HAVE_EPOLL)
#if defined(HAVE_KQUEUE)
# include <sys/types.h>
# include <sys/event.h>
# include <sys/time.h>
#endif
#if defined(HAVE_EPOLL)
# include <sys/epoll.h>
#endif
#endif
MapView::MapView(llmr::Settings &settings, bool fullscreen)
: fullscreen(fullscreen), settings(settings), map(settings) {}
: fullscreen(fullscreen), settings(settings), map(settings),
stop_event_listener(false) {}
MapView::~MapView() { glfwTerminate(); }
@@ -163,28 +196,70 @@ void MapView::mousemove(GLFWwindow *window, double x, double y) {
mapView->last_y = y;
}
int MapView::run() {
while (!glfwWindowShouldClose(window)) {
llmr::platform::cleanup();
void MapView::eventloop(void *arg) {
MapView *view = static_cast<MapView *>(arg);
int r = 0;
int fd = 0;
int timeout;
if (dirty) {
try {
dirty = map.render();
while (!view->stop_event_listener) {
fd = uv_backend_fd(uv_default_loop());
timeout = uv_backend_timeout(uv_default_loop());
do {
#if defined(HAVE_KQUEUE)
struct timespec ts;
ts.tv_sec = timeout / 1000;
ts.tv_nsec = (timeout % 1000) * 1000000;
r = kevent(fd, NULL, 0, NULL, 0, &ts);
#elif defined(HAVE_EPOLL)
{
struct epoll_event ev;
r = epoll_wait(fd, &ev, 1, timeout);
}
catch (std::exception &ex) {
fprintf(stderr, "exception: %s\n", ex.what());
}
glfwSwapBuffers(window);
fps();
#endif
} while (r == -1 && errno == EINTR);
glfwPostEmptyEvent();
uv_sem_wait(&view->event_listener);
}
}
int MapView::run() {
uv_thread_t embed_thread;
uv_run(uv_default_loop(), UV_RUN_NOWAIT);
/* Start worker that will interrupt external loop */
stop_event_listener = false;
uv_sem_init(&event_listener, 0);
uv_thread_create(&embed_thread, eventloop, this);
while (!glfwWindowShouldClose(window)) {
bool dirty = false;
try {
dirty = map.render();
}
catch (std::exception &ex) {
fprintf(stderr, "exception: %s\n", ex.what());
}
glfwSwapBuffers(window);
fps();
if (dirty) {
glfwPollEvents();
} else {
glfwWaitEvents();
}
uv_run(uv_default_loop(), UV_RUN_NOWAIT);
uv_sem_post(&event_listener);
}
stop_event_listener = true;
uv_thread_join(&embed_thread);
return 0;
}
@@ -234,5 +309,10 @@ void show_debug_image(std::string name, const char *data, size_t width, size_t h
glfwMakeContextCurrent(current_window);
}
void restart() {
glfwPostEmptyEvent();
}
}
}