summaryrefslogtreecommitdiff
path: root/platform/default/headless_display.cpp
blob: a4517327cb2548e6cd9f7a9bb2d4420f659d7297 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <mbgl/platform/default/headless_display.hpp>

#if MBGL_USE_EGL
#include <mbgl/util/string.hpp>
#include <EGL/egl.h>
#include <fcntl.h>
#include <gbm.h>
#include <unistd.h>
#endif

#include <cstring>
#include <stdexcept>
#include <string>

namespace mbgl {

HeadlessDisplay::HeadlessDisplay() {
#if MBGL_USE_CGL
    // TODO: test if OpenGL 4.1 with GL_ARB_ES2_compatibility is supported
    // If it is, use kCGLOGLPVersion_3_2_Core and enable that extension.
    CGLPixelFormatAttribute attributes[] = {
        kCGLPFAOpenGLProfile,
        static_cast<CGLPixelFormatAttribute>(kCGLOGLPVersion_Legacy),
        static_cast<CGLPixelFormatAttribute>(0)
    };

    GLint num;
    CGLError error = CGLChoosePixelFormat(attributes, &pixelFormat, &num);
    if (error != kCGLNoError) {
        throw std::runtime_error(std::string("Error choosing pixel format:") + CGLErrorString(error) + "\n");
    }
    if (num <= 0) {
        throw std::runtime_error("No pixel formats found.");
    }
#endif
#if MBGL_USE_EGL
    for (int i = 128; i < (128 + 16); i++) {
        auto device_name = std::string{ "/dev/dri/renderD" } + mbgl::util::toString(i);
        fd = open(device_name.c_str(), O_RDWR);
        if (fd > 0)
            break;
    }
    if (fd < 0) {
        throw std::runtime_error("Couldn't open drm device.");
    }

    gbm = gbm_create_device(fd);
    if (gbm == NULL) {
        throw std::runtime_error("Couldn't create gbm device.");
    }

    dpy = eglGetDisplay(reinterpret_cast<EGLNativeDisplayType>(gbm));
    if (dpy == EGL_NO_DISPLAY) {
        throw std::runtime_error("eglGetDisplay() failed.");
    }

    EGLint major, minor, n;
    if (!eglInitialize(dpy, &major, &minor)) {
        throw std::runtime_error("eglInitialize() failed.");
    }

    const EGLint attribs[] = {
        EGL_SURFACE_TYPE, EGL_DONT_CARE,
        EGL_RED_SIZE, 1,
        EGL_GREEN_SIZE, 1,
        EGL_BLUE_SIZE, 1,
        EGL_ALPHA_SIZE, 0,
        EGL_DEPTH_SIZE, 1,
        EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
        EGL_NONE
    };
    if (!eglChooseConfig(dpy, attribs, &config, 1, &n) || n != 1) {
        throw std::runtime_error("Failed to choose argb config.");
    }
#endif
}

HeadlessDisplay::~HeadlessDisplay() {
#if MBGL_USE_CGL
    CGLDestroyPixelFormat(pixelFormat);
#endif

#if MBGL_USE_EGL
    eglTerminate(dpy);
    gbm_device_destroy(gbm);
    close(fd);
#endif
}

} // namespace mbgl