kmscube.c: init_drm(): select the current CRTC display mode is valid
[glsdk/kmscube.git] / kmscube.c
1 /*
2  * Copyright (c) 2012 Arvin Schnell <arvin.schnell@gmail.com>
3  * Copyright (c) 2012 Rob Clark <rob@ti.com>
4  * Copyright (c) 2013 Anand Balagopalakrishnan <anandb@ti.com>
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sub license,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice (including the
14  * next paragraph) shall be included in all copies or substantial portions
15  * of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
20  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23  * DEALINGS IN THE SOFTWARE.
24  */
26 /* Based on a egl cube test app originally written by Arvin Schnell */
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <fcntl.h>
31 #include <string.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <unistd.h>
35 #include <errno.h>
36 #include <signal.h>
38 #include <xf86drm.h>
39 #include <xf86drmMode.h>
40 #include <gbm.h>
42 #include "esUtil.h"
44 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
46 #define MAX_DISPLAYS    (4)
47 uint8_t DISP_ID = 0;
48 uint8_t all_display = 0;
49 int8_t connector_id = -1;
51 static struct {
52         EGLDisplay display;
53         EGLConfig config;
54         EGLContext context;
55         EGLSurface surface;
56         GLuint program;
57         GLint modelviewmatrix, modelviewprojectionmatrix, normalmatrix;
58         GLuint vbo;
59         GLuint positionsoffset, colorsoffset, normalsoffset;
60         GLuint vertex_shader, fragment_shader;
61 } gl;
63 static struct {
64         struct gbm_device *dev;
65         struct gbm_surface *surface;
66 } gbm;
68 static struct {
69         int fd;
70         uint32_t ndisp;
71         uint32_t crtc_id[MAX_DISPLAYS];
72         uint32_t connector_id[MAX_DISPLAYS];
73         uint32_t resource_id;
74         uint32_t encoder[MAX_DISPLAYS];
75         drmModeModeInfo *mode[MAX_DISPLAYS];
76         drmModeConnector *connectors[MAX_DISPLAYS];
77 } drm;
79 struct drm_fb {
80         struct gbm_bo *bo;
81         uint32_t fb_id;
82 };
84 static int init_drm(void)
85 {
86         static const char *modules[] = {
87                         "omapdrm", "tilcdc", "i915", "radeon", "nouveau", "vmwgfx", "exynos"
88         };
89         drmModeRes *resources;
90         drmModeConnector *connector = NULL;
91         drmModeEncoder *encoder = NULL;
92         drmModeCrtc *crtc = NULL;
94         int i, j;
95         uint32_t maxRes, curRes;
97         for (i = 0; i < ARRAY_SIZE(modules); i++) {
98                 printf("trying to load module %s...", modules[i]);
99                 drm.fd = drmOpen(modules[i], NULL);
100                 if (drm.fd < 0) {
101                         printf("failed.\n");
102                 } else {
103                         printf("success.\n");
104                         break;
105                 }
106         }
108         if (drm.fd < 0) {
109                 printf("could not open drm device\n");
110                 return -1;
111         }
113         resources = drmModeGetResources(drm.fd);
114         if (!resources) {
115                 printf("drmModeGetResources failed: %s\n", strerror(errno));
116                 return -1;
117         }
118         drm.resource_id = (uint32_t) resources;
120         /* find a connected connector: */
121         for (i = 0; i < resources->count_connectors; i++) {
122                 connector = drmModeGetConnector(drm.fd, resources->connectors[i]);
123                 if (connector->connection == DRM_MODE_CONNECTED) {
125                         /* find the matched encoders */
126                         for (j=0; j<resources->count_encoders; j++) {
127                                 encoder = drmModeGetEncoder(drm.fd, resources->encoders[j]);
128                                 if (encoder->encoder_id == connector->encoder_id)
129                                         break;
131                                 drmModeFreeEncoder(encoder);
132                                 encoder = NULL;
133                         }
135                         if (!encoder) {
136                                 printf("no encoder!\n");
137                                 return -1;
138                         }
140                         /* choose the current or first supported mode */
141                         crtc = drmModeGetCrtc(drm.fd, encoder->crtc_id);
142                         for (j = 0; j < connector->count_modes; j++)
143                         {
144                                 if (crtc->mode_valid)
145                                 {
146                                         if ((connector->modes[j].hdisplay == crtc->width) &&
147                                         (connector->modes[j].vdisplay == crtc->height))
148                                         {
149                                                 drm.mode[drm.ndisp] = &connector->modes[j];
150                                                 break;
151                                         }
152                                 }
153                                 else
154                                 {
155                                         if ((connector->modes[j].hdisplay == crtc->x) &&
156                                            (connector->modes[j].vdisplay == crtc->y))
157                                         {
158                                                 drm.mode[drm.ndisp] = &connector->modes[j];
159                                                 break;
160                                         }
161                                 }
162                         }
164                         if(j >= connector->count_modes)
165                                 drm.mode[drm.ndisp] = &connector->modes[0];
167                         drm.connector_id[drm.ndisp] = connector->connector_id;
169                         drm.encoder[drm.ndisp]  = (uint32_t) encoder;
170                         drm.crtc_id[drm.ndisp] = encoder->crtc_id;
171                         drm.connectors[drm.ndisp] = connector;
173                         printf("### Display [%d]: CRTC = %d, Connector = %d\n", drm.ndisp, drm.crtc_id[drm.ndisp], drm.connector_id[drm.ndisp]);
174                         printf("\tMode chosen [%s] : Clock => %d, Vertical refresh => %d, Type => %d\n", drm.mode[drm.ndisp]->name, drm.mode[drm.ndisp]->clock, drm.mode[drm.ndisp]->vrefresh, drm.mode[drm.ndisp]->type);
175                         printf("\tHorizontal => %d, %d, %d, %d, %d\n", drm.mode[drm.ndisp]->hdisplay, drm.mode[drm.ndisp]->hsync_start, drm.mode[drm.ndisp]->hsync_end, drm.mode[drm.ndisp]->htotal, drm.mode[drm.ndisp]->hskew);
176                         printf("\tVertical => %d, %d, %d, %d, %d\n", drm.mode[drm.ndisp]->vdisplay, drm.mode[drm.ndisp]->vsync_start, drm.mode[drm.ndisp]->vsync_end, drm.mode[drm.ndisp]->vtotal, drm.mode[drm.ndisp]->vscan);
178                         /* If a connector_id is specified, use the corresponding display */
179                         if ((connector_id != -1) && (connector_id == drm.connector_id[drm.ndisp]))
180                                 DISP_ID = drm.ndisp;
182                         /* If all displays are enabled, choose the connector with maximum
183                         * resolution as the primary display */
184                         if (all_display) {
185                                 maxRes = drm.mode[DISP_ID]->vdisplay * drm.mode[DISP_ID]->hdisplay;
186                                 curRes = drm.mode[drm.ndisp]->vdisplay * drm.mode[drm.ndisp]->hdisplay;
188                                 if (curRes > maxRes)
189                                         DISP_ID = drm.ndisp;
190                         }
192                         drm.ndisp++;
193                 } else {
194                         drmModeFreeConnector(connector);
195                 }
196         }
198         if (drm.ndisp == 0) {
199                 /* we could be fancy and listen for hotplug events and wait for
200                  * a connector..
201                  */
202                 printf("no connected connector!\n");
203                 return -1;
204         }
206         return 0;
209 static int init_gbm(void)
211         gbm.dev = gbm_create_device(drm.fd);
213         gbm.surface = gbm_surface_create(gbm.dev,
214                         drm.mode[DISP_ID]->hdisplay, drm.mode[DISP_ID]->vdisplay,
215                         GBM_FORMAT_XRGB8888,
216                         GBM_BO_USE_SCANOUT | GBM_BO_USE_RENDERING);
217         if (!gbm.surface) {
218                 printf("failed to create gbm surface\n");
219                 return -1;
220         }
222         return 0;
225 static int init_gl(void)
227         EGLint major, minor, n;
228         GLint ret;
230         static const GLfloat vVertices[] = {
231                         // front
232                         -1.0f, -1.0f, +1.0f, // point blue
233                         +1.0f, -1.0f, +1.0f, // point magenta
234                         -1.0f, +1.0f, +1.0f, // point cyan
235                         +1.0f, +1.0f, +1.0f, // point white
236                         // back
237                         +1.0f, -1.0f, -1.0f, // point red
238                         -1.0f, -1.0f, -1.0f, // point black
239                         +1.0f, +1.0f, -1.0f, // point yellow
240                         -1.0f, +1.0f, -1.0f, // point green
241                         // right
242                         +1.0f, -1.0f, +1.0f, // point magenta
243                         +1.0f, -1.0f, -1.0f, // point red
244                         +1.0f, +1.0f, +1.0f, // point white
245                         +1.0f, +1.0f, -1.0f, // point yellow
246                         // left
247                         -1.0f, -1.0f, -1.0f, // point black
248                         -1.0f, -1.0f, +1.0f, // point blue
249                         -1.0f, +1.0f, -1.0f, // point green
250                         -1.0f, +1.0f, +1.0f, // point cyan
251                         // top
252                         -1.0f, +1.0f, +1.0f, // point cyan
253                         +1.0f, +1.0f, +1.0f, // point white
254                         -1.0f, +1.0f, -1.0f, // point green
255                         +1.0f, +1.0f, -1.0f, // point yellow
256                         // bottom
257                         -1.0f, -1.0f, -1.0f, // point black
258                         +1.0f, -1.0f, -1.0f, // point red
259                         -1.0f, -1.0f, +1.0f, // point blue
260                         +1.0f, -1.0f, +1.0f  // point magenta
261         };
263         static const GLfloat vColors[] = {
264                         // front
265                         0.0f,  0.0f,  1.0f, // blue
266                         1.0f,  0.0f,  1.0f, // magenta
267                         0.0f,  1.0f,  1.0f, // cyan
268                         1.0f,  1.0f,  1.0f, // white
269                         // back
270                         1.0f,  0.0f,  0.0f, // red
271                         0.0f,  0.0f,  0.0f, // black
272                         1.0f,  1.0f,  0.0f, // yellow
273                         0.0f,  1.0f,  0.0f, // green
274                         // right
275                         1.0f,  0.0f,  1.0f, // magenta
276                         1.0f,  0.0f,  0.0f, // red
277                         1.0f,  1.0f,  1.0f, // white
278                         1.0f,  1.0f,  0.0f, // yellow
279                         // left
280                         0.0f,  0.0f,  0.0f, // black
281                         0.0f,  0.0f,  1.0f, // blue
282                         0.0f,  1.0f,  0.0f, // green
283                         0.0f,  1.0f,  1.0f, // cyan
284                         // top
285                         0.0f,  1.0f,  1.0f, // cyan
286                         1.0f,  1.0f,  1.0f, // white
287                         0.0f,  1.0f,  0.0f, // green
288                         1.0f,  1.0f,  0.0f, // yellow
289                         // bottom
290                         0.0f,  0.0f,  0.0f, // black
291                         1.0f,  0.0f,  0.0f, // red
292                         0.0f,  0.0f,  1.0f, // blue
293                         1.0f,  0.0f,  1.0f  // magenta
294         };
296         static const GLfloat vNormals[] = {
297                         // front
298                         +0.0f, +0.0f, +1.0f, // forward
299                         +0.0f, +0.0f, +1.0f, // forward
300                         +0.0f, +0.0f, +1.0f, // forward
301                         +0.0f, +0.0f, +1.0f, // forward
302                         // back
303                         +0.0f, +0.0f, -1.0f, // backbard
304                         +0.0f, +0.0f, -1.0f, // backbard
305                         +0.0f, +0.0f, -1.0f, // backbard
306                         +0.0f, +0.0f, -1.0f, // backbard
307                         // right
308                         +1.0f, +0.0f, +0.0f, // right
309                         +1.0f, +0.0f, +0.0f, // right
310                         +1.0f, +0.0f, +0.0f, // right
311                         +1.0f, +0.0f, +0.0f, // right
312                         // left
313                         -1.0f, +0.0f, +0.0f, // left
314                         -1.0f, +0.0f, +0.0f, // left
315                         -1.0f, +0.0f, +0.0f, // left
316                         -1.0f, +0.0f, +0.0f, // left
317                         // top
318                         +0.0f, +1.0f, +0.0f, // up
319                         +0.0f, +1.0f, +0.0f, // up
320                         +0.0f, +1.0f, +0.0f, // up
321                         +0.0f, +1.0f, +0.0f, // up
322                         // bottom
323                         +0.0f, -1.0f, +0.0f, // down
324                         +0.0f, -1.0f, +0.0f, // down
325                         +0.0f, -1.0f, +0.0f, // down
326                         +0.0f, -1.0f, +0.0f  // down
327         };
329         static const EGLint context_attribs[] = {
330                 EGL_CONTEXT_CLIENT_VERSION, 2,
331                 EGL_NONE
332         };
334         static const EGLint config_attribs[] = {
335                 EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
336                 EGL_RED_SIZE, 1,
337                 EGL_GREEN_SIZE, 1,
338                 EGL_BLUE_SIZE, 1,
339                 EGL_ALPHA_SIZE, 0,
340                 EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
341                 EGL_NONE
342         };
344         static const char *vertex_shader_source =
345                         "uniform mat4 modelviewMatrix;      \n"
346                         "uniform mat4 modelviewprojectionMatrix;\n"
347                         "uniform mat3 normalMatrix;         \n"
348                         "                                   \n"
349                         "attribute vec4 in_position;        \n"
350                         "attribute vec3 in_normal;          \n"
351                         "attribute vec4 in_color;           \n"
352                         "\n"
353                         "vec4 lightSource = vec4(2.0, 2.0, 20.0, 0.0);\n"
354                         "                                   \n"
355                         "varying vec4 vVaryingColor;        \n"
356                         "                                   \n"
357                         "void main()                        \n"
358                         "{                                  \n"
359                         "    gl_Position = modelviewprojectionMatrix * in_position;\n"
360                         "    vec3 vEyeNormal = normalMatrix * in_normal;\n"
361                         "    vec4 vPosition4 = modelviewMatrix * in_position;\n"
362                         "    vec3 vPosition3 = vPosition4.xyz / vPosition4.w;\n"
363                         "    vec3 vLightDir = normalize(lightSource.xyz - vPosition3);\n"
364                         "    float diff = max(0.0, dot(vEyeNormal, vLightDir));\n"
365                         "    vVaryingColor = vec4(diff * in_color.rgb, 1.0);\n"
366                         "}                                  \n";
368         static const char *fragment_shader_source =
369                         "precision mediump float;           \n"
370                         "                                   \n"
371                         "varying vec4 vVaryingColor;        \n"
372                         "                                   \n"
373                         "void main()                        \n"
374                         "{                                  \n"
375                         "    gl_FragColor = vVaryingColor;  \n"
376                         "}                                  \n";
378         gl.display = eglGetDisplay(gbm.dev);
380         if (!eglInitialize(gl.display, &major, &minor)) {
381                 printf("failed to initialize\n");
382                 return -1;
383         }
385         printf("Using display %p with EGL version %d.%d\n",
386                         gl.display, major, minor);
388         printf("EGL Version \"%s\"\n", eglQueryString(gl.display, EGL_VERSION));
389         printf("EGL Vendor \"%s\"\n", eglQueryString(gl.display, EGL_VENDOR));
390         printf("EGL Extensions \"%s\"\n", eglQueryString(gl.display, EGL_EXTENSIONS));
392         if (!eglBindAPI(EGL_OPENGL_ES_API)) {
393                 printf("failed to bind api EGL_OPENGL_ES_API\n");
394                 return -1;
395         }
397         if (!eglChooseConfig(gl.display, config_attribs, &gl.config, 1, &n) || n != 1) {
398                 printf("failed to choose config: %d\n", n);
399                 return -1;
400         }
402         gl.context = eglCreateContext(gl.display, gl.config,
403                         EGL_NO_CONTEXT, context_attribs);
404         if (gl.context == NULL) {
405                 printf("failed to create context\n");
406                 return -1;
407         }
409         gl.surface = eglCreateWindowSurface(gl.display, gl.config, gbm.surface, NULL);
410         if (gl.surface == EGL_NO_SURFACE) {
411                 printf("failed to create egl surface\n");
412                 return -1;
413         }
415         /* connect the context to the surface */
416         eglMakeCurrent(gl.display, gl.surface, gl.surface, gl.context);
419         gl.vertex_shader = glCreateShader(GL_VERTEX_SHADER);
421         glShaderSource(gl.vertex_shader, 1, &vertex_shader_source, NULL);
422         glCompileShader(gl.vertex_shader);
424         glGetShaderiv(gl.vertex_shader, GL_COMPILE_STATUS, &ret);
425         if (!ret) {
426                 char *log;
428                 printf("vertex shader compilation failed!:\n");
429                 glGetShaderiv(gl.vertex_shader, GL_INFO_LOG_LENGTH, &ret);
430                 if (ret > 1) {
431                         log = malloc(ret);
432                         glGetShaderInfoLog(gl.vertex_shader, ret, NULL, log);
433                         printf("%s", log);
434                 }
436                 return -1;
437         }
439         gl.fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
441         glShaderSource(gl.fragment_shader, 1, &fragment_shader_source, NULL);
442         glCompileShader(gl.fragment_shader);
444         glGetShaderiv(gl.fragment_shader, GL_COMPILE_STATUS, &ret);
445         if (!ret) {
446                 char *log;
448                 printf("fragment shader compilation failed!:\n");
449                 glGetShaderiv(gl.fragment_shader, GL_INFO_LOG_LENGTH, &ret);
451                 if (ret > 1) {
452                         log = malloc(ret);
453                         glGetShaderInfoLog(gl.fragment_shader, ret, NULL, log);
454                         printf("%s", log);
455                 }
457                 return -1;
458         }
460         gl.program = glCreateProgram();
462         glAttachShader(gl.program, gl.vertex_shader);
463         glAttachShader(gl.program, gl.fragment_shader);
465         glBindAttribLocation(gl.program, 0, "in_position");
466         glBindAttribLocation(gl.program, 1, "in_normal");
467         glBindAttribLocation(gl.program, 2, "in_color");
469         glLinkProgram(gl.program);
471         glGetProgramiv(gl.program, GL_LINK_STATUS, &ret);
472         if (!ret) {
473                 char *log;
475                 printf("program linking failed!:\n");
476                 glGetProgramiv(gl.program, GL_INFO_LOG_LENGTH, &ret);
478                 if (ret > 1) {
479                         log = malloc(ret);
480                         glGetProgramInfoLog(gl.program, ret, NULL, log);
481                         printf("%s", log);
482                 }
484                 return -1;
485         }
487         glUseProgram(gl.program);
489         gl.modelviewmatrix = glGetUniformLocation(gl.program, "modelviewMatrix");
490         gl.modelviewprojectionmatrix = glGetUniformLocation(gl.program, "modelviewprojectionMatrix");
491         gl.normalmatrix = glGetUniformLocation(gl.program, "normalMatrix");
493         glViewport(0, 0, drm.mode[DISP_ID]->hdisplay, drm.mode[DISP_ID]->vdisplay);
494         glEnable(GL_CULL_FACE);
496         gl.positionsoffset = 0;
497         gl.colorsoffset = sizeof(vVertices);
498         gl.normalsoffset = sizeof(vVertices) + sizeof(vColors);
499         glGenBuffers(1, &gl.vbo);
500         glBindBuffer(GL_ARRAY_BUFFER, gl.vbo);
501         glBufferData(GL_ARRAY_BUFFER, sizeof(vVertices) + sizeof(vColors) + sizeof(vNormals), 0, GL_STATIC_DRAW);
502         glBufferSubData(GL_ARRAY_BUFFER, gl.positionsoffset, sizeof(vVertices), &vVertices[0]);
503         glBufferSubData(GL_ARRAY_BUFFER, gl.colorsoffset, sizeof(vColors), &vColors[0]);
504         glBufferSubData(GL_ARRAY_BUFFER, gl.normalsoffset, sizeof(vNormals), &vNormals[0]);
505         glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*)gl.positionsoffset);
506         glEnableVertexAttribArray(0);
507         glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*)gl.normalsoffset);
508         glEnableVertexAttribArray(1);
509         glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*)gl.colorsoffset);
510         glEnableVertexAttribArray(2);
512         return 0;
515 static void exit_gbm(void)
517         gbm_surface_destroy(gbm.surface);
518         gbm_device_destroy(gbm.dev);
519         return;
522 static void exit_gl(void)
524         glDeleteProgram(gl.program);
525         glDeleteBuffers(1, &gl.vbo);
526         glDeleteShader(gl.fragment_shader);
527         glDeleteShader(gl.vertex_shader);
528         eglDestroySurface(gl.display, gl.surface);
529         eglDestroyContext(gl.display, gl.context);
530         eglTerminate(gl.display);
531         return;
534 static void exit_drm(void)
537         drmModeRes *resources;
538         int i;
540         resources = (drmModeRes *)drm.resource_id;
541         for (i = 0; i < resources->count_connectors; i++) {
542                 drmModeFreeEncoder(drm.encoder[i]);
543                 drmModeFreeConnector(drm.connectors[i]);
544         }
545         drmModeFreeResources(drm.resource_id);
546         drmClose(drm.fd);
547         return;
550 void cleanup_kmscube(void)
552         exit_gl();
553         exit_gbm();
554         exit_drm();
555         printf("Cleanup of GL, GBM and DRM completed\n");
556         return;
559 static void draw(uint32_t i)
561         ESMatrix modelview;
563         /* clear the color buffer */
564         glClearColor(0.5, 0.5, 0.5, 1.0);
565         glClear(GL_COLOR_BUFFER_BIT);
567         esMatrixLoadIdentity(&modelview);
568         esTranslate(&modelview, 0.0f, 0.0f, -8.0f);
569         esRotate(&modelview, 45.0f + (0.25f * i), 1.0f, 0.0f, 0.0f);
570         esRotate(&modelview, 45.0f - (0.5f * i), 0.0f, 1.0f, 0.0f);
571         esRotate(&modelview, 10.0f + (0.15f * i), 0.0f, 0.0f, 1.0f);
573         GLfloat aspect = (GLfloat)(drm.mode[DISP_ID]->vdisplay) / (GLfloat)(drm.mode[DISP_ID]->hdisplay);
575         ESMatrix projection;
576         esMatrixLoadIdentity(&projection);
577         esFrustum(&projection, -2.8f, +2.8f, -2.8f * aspect, +2.8f * aspect, 6.0f, 10.0f);
579         ESMatrix modelviewprojection;
580         esMatrixLoadIdentity(&modelviewprojection);
581         esMatrixMultiply(&modelviewprojection, &modelview, &projection);
583         float normal[9];
584         normal[0] = modelview.m[0][0];
585         normal[1] = modelview.m[0][1];
586         normal[2] = modelview.m[0][2];
587         normal[3] = modelview.m[1][0];
588         normal[4] = modelview.m[1][1];
589         normal[5] = modelview.m[1][2];
590         normal[6] = modelview.m[2][0];
591         normal[7] = modelview.m[2][1];
592         normal[8] = modelview.m[2][2];
594         glUniformMatrix4fv(gl.modelviewmatrix, 1, GL_FALSE, &modelview.m[0][0]);
595         glUniformMatrix4fv(gl.modelviewprojectionmatrix, 1, GL_FALSE, &modelviewprojection.m[0][0]);
596         glUniformMatrix3fv(gl.normalmatrix, 1, GL_FALSE, normal);
598         glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
599         glDrawArrays(GL_TRIANGLE_STRIP, 4, 4);
600         glDrawArrays(GL_TRIANGLE_STRIP, 8, 4);
601         glDrawArrays(GL_TRIANGLE_STRIP, 12, 4);
602         glDrawArrays(GL_TRIANGLE_STRIP, 16, 4);
603         glDrawArrays(GL_TRIANGLE_STRIP, 20, 4);
606 static void
607 drm_fb_destroy_callback(struct gbm_bo *bo, void *data)
609         struct drm_fb *fb = data;
610         struct gbm_device *gbm = gbm_bo_get_device(bo);
612         if (fb->fb_id)
613                 drmModeRmFB(drm.fd, fb->fb_id);
615         free(fb);
618 static struct drm_fb * drm_fb_get_from_bo(struct gbm_bo *bo)
620         struct drm_fb *fb = gbm_bo_get_user_data(bo);
621         uint32_t width, height, stride, handle;
622         int ret;
624         if (fb)
625                 return fb;
627         fb = calloc(1, sizeof *fb);
628         fb->bo = bo;
630         width = gbm_bo_get_width(bo);
631         height = gbm_bo_get_height(bo);
632         stride = gbm_bo_get_stride(bo);
633         handle = gbm_bo_get_handle(bo).u32;
635         ret = drmModeAddFB(drm.fd, width, height, 24, 32, stride, handle, &fb->fb_id);
636         if (ret) {
637                 printf("failed to create fb: %s\n", strerror(errno));
638                 free(fb);
639                 return NULL;
640         }
642         gbm_bo_set_user_data(bo, fb, drm_fb_destroy_callback);
644         return fb;
647 static void page_flip_handler(int fd, unsigned int frame,
648                   unsigned int sec, unsigned int usec, void *data)
650         int *waiting_for_flip = data;
651         *waiting_for_flip = 0;
654 void print_usage()
656         printf("Usage : kmscube <options>\n");
657         printf("\t-h : Help\n");
658         printf("\t-a : Enable all displays\n");
659         printf("\t-c <id> : Display using connector_id [if not specified, use the first connected connector]\n");
660         printf("\t-n <number> (optional): Number of frames to render\n");
663 int kms_signalhandler(int signum)
665         switch(signum) {
666         case SIGINT:
667         case SIGTERM:
668                 /* Allow the pending page flip requests to be completed before
669                  * the teardown sequence */
670                 sleep(1);
671                 printf("Handling signal number = %d\n", signum);
672                 cleanup_kmscube();
673                 break;
674         default:
675                 printf("Unknown signal\n");
676                 break;
677         }
678         exit(1);
681 int main(int argc, char *argv[])
683         fd_set fds;
684         drmEventContext evctx = {
685                         .version = DRM_EVENT_CONTEXT_VERSION,
686                         .page_flip_handler = page_flip_handler,
687         };
688         struct gbm_bo *bo;
689         struct drm_fb *fb;
690         uint32_t i = 0;
691         int ret;
692         int opt;
693         int frame_count = -1;
695         signal(SIGINT, kms_signalhandler);
696         signal(SIGTERM, kms_signalhandler);
698         while ((opt = getopt(argc, argv, "ahc:n:")) != -1) {
699                 switch(opt) {
700                 case 'a':
701                         all_display = 1;
702                         break;
704                 case 'h':
705                         print_usage();
706                         return 0;
708                 case 'c':
709                         connector_id = atoi(optarg);
710                         break;
711                 case 'n':
712                         frame_count = atoi(optarg);
713                         break;
716                 default:
717                         printf("Undefined option %s\n", argv[optind]);
718                         print_usage();
719                         return -1;
720                 }
721         }
723         if (all_display) {
724                 printf("### Enabling all displays\n");
725                 connector_id = -1;
726         }
728         ret = init_drm();
729         if (ret) {
730                 printf("failed to initialize DRM\n");
731                 return ret;
732         }
733         printf("### Primary display => ConnectorId = %d, Resolution = %dx%d\n",
734                         drm.connector_id[DISP_ID], drm.mode[DISP_ID]->hdisplay,
735                         drm.mode[DISP_ID]->vdisplay);
737         FD_ZERO(&fds);
738         FD_SET(drm.fd, &fds);
740         ret = init_gbm();
741         if (ret) {
742                 printf("failed to initialize GBM\n");
743                 return ret;
744         }
746         ret = init_gl();
747         if (ret) {
748                 printf("failed to initialize EGL\n");
749                 return ret;
750         }
752         /* clear the color buffer */
753         glClearColor(0.5, 0.5, 0.5, 1.0);
754         glClear(GL_COLOR_BUFFER_BIT);
755         eglSwapBuffers(gl.display, gl.surface);
756         bo = gbm_surface_lock_front_buffer(gbm.surface);
757         fb = drm_fb_get_from_bo(bo);
759         /* set mode: */
760         if (all_display) {
761                 for (i=0; i<drm.ndisp; i++) {
762                         ret = drmModeSetCrtc(drm.fd, drm.crtc_id[i], fb->fb_id, 0, 0,
763                                         &drm.connector_id[i], 1, drm.mode[i]);
764                         if (ret) {
765                                 printf("display %d failed to set mode: %s\n", i, strerror(errno));
766                                 return ret;
767                         }
768                 }
769         } else {
770                 ret = drmModeSetCrtc(drm.fd, drm.crtc_id[DISP_ID], fb->fb_id,
771                                 0, 0, &drm.connector_id[DISP_ID], 1, drm.mode[DISP_ID]);
772                 if (ret) {
773                         printf("display %d failed to set mode: %s\n", DISP_ID, strerror(errno));
774                         return ret;
775                 }
776         }
778         while (frame_count != 0) {
779                 struct gbm_bo *next_bo;
780                 int waiting_for_flip = 1;
782                 draw(i++);
784                 eglSwapBuffers(gl.display, gl.surface);
785                 next_bo = gbm_surface_lock_front_buffer(gbm.surface);
786                 fb = drm_fb_get_from_bo(next_bo);
788                 /*
789                  * Here you could also update drm plane layers if you want
790                  * hw composition
791                  */
793                 ret = drmModePageFlip(drm.fd, drm.crtc_id[DISP_ID], fb->fb_id,
794                                 DRM_MODE_PAGE_FLIP_EVENT, &waiting_for_flip);
795                 if (ret) {
796                         printf("failed to queue page flip: %s\n", strerror(errno));
797                         return -1;
798                 }
800                 while (waiting_for_flip) {
801                         ret = select(drm.fd + 1, &fds, NULL, NULL, NULL);
802                         if (ret < 0) {
803                                 printf("select err: %s\n", strerror(errno));
804                                 return ret;
805                         } else if (ret == 0) {
806                                 printf("select timeout!\n");
807                                 return -1;
808                         } else if (FD_ISSET(0, &fds)) {
809                                 continue;
810                         }
811                         drmHandleEvent(drm.fd, &evctx);
812                 }
814                 /* release last buffer to render on again: */
815                 gbm_surface_release_buffer(gbm.surface, bo);
816                 bo = next_bo;
818                 if(frame_count >= 0)
819                         frame_count--;
820         }
822         cleanup_kmscube();
823         printf("\n Exiting kmscube \n");
825         return ret;