oculus2

view src/main.c @ 9:9c36ae39ad95

merged
author John Tsiombikas <nuclear@member.fsf.org>
date Sat, 25 Oct 2014 20:07:55 +0300
parents 4d6733229e01 5b04743fd3d0
children 3d224ad45cac
line source
1 /* Very simple OculusSDK OpenGL usage example.
2 *
3 * Uses SDL2 (www.libsdl.org) for event handling and OpenGL context management.
4 * Uses GLEW (glew.sourceforge.net) for OpenGL extension wrangling.
5 *
6 * Author: John Tsiombikas <nuclear@member.fsf.org>
7 * This code is in the public domain. Do whatever you like with it.
8 */
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <assert.h>
12 #include <SDL2/SDL.h>
13 #include <GL/glew.h>
15 #ifdef WIN32
16 #define OVR_OS_WIN32
17 #endif
18 #ifdef __APPLE__
19 #define OVR_OS_MAC
20 #endif
22 #include <OVR_CAPI.h>
23 #include <OVR_CAPI_GL.h>
25 int init(void);
26 void cleanup(void);
27 void toggle_hmd_fullscreen(void);
28 void display(void);
29 void draw_scene(void);
30 void draw_box(float xsz, float ysz, float zsz, float norm_sign);
31 void update_rtarg(int width, int height);
32 int handle_event(SDL_Event *ev);
33 int key_event(int key, int state);
34 void reshape(int x, int y);
35 unsigned int next_pow2(unsigned int x);
36 void quat_to_matrix(const float *quat, float *mat);
37 unsigned int gen_chess_tex(float r0, float g0, float b0, float r1, float g1, float b1);
39 /* forward declaration to avoid including non-public headers of libovr */
40 OVR_EXPORT void ovrhmd_EnableHSWDisplaySDKRender(ovrHmd hmd, ovrBool enable);
42 static SDL_Window *win;
43 static SDL_GLContext ctx;
44 static int win_width, win_height;
46 static unsigned int fbo, fb_tex, fb_depth;
47 static int fb_width, fb_height;
48 static int fb_tex_width, fb_tex_height;
50 static ovrHmd hmd;
51 static ovrSizei eyeres[2];
52 static ovrEyeRenderDesc eye_rdesc[2];
53 static ovrGLTexture fb_ovr_tex[2];
55 static unsigned int chess_tex;
58 int main(int argc, char **argv)
59 {
60 if(init() == -1) {
61 return 1;
62 }
64 for(;;) {
65 SDL_Event ev;
66 while(SDL_PollEvent(&ev)) {
67 if(handle_event(&ev) == -1) {
68 goto done;
69 }
70 }
71 display();
72 }
74 done:
75 cleanup();
76 return 0;
77 }
80 int init(void)
81 {
82 int i, x, y;
83 unsigned int flags, dcaps;
84 union ovrGLConfig glcfg;
86 /* libovr must be initialized before we create the OpenGL context */
87 ovr_Initialize();
89 SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER);
91 x = y = SDL_WINDOWPOS_UNDEFINED;
92 flags = SDL_WINDOW_OPENGL;
93 if(!(win = SDL_CreateWindow("press 'f' to move to the HMD", x, y, 1280, 800, flags))) {
94 fprintf(stderr, "failed to create window\n");
95 return -1;
96 }
97 if(!(ctx = SDL_GL_CreateContext(win))) {
98 fprintf(stderr, "failed to create OpenGL context\n");
99 return -1;
100 }
102 glewInit();
104 if(!(hmd = ovrHmd_Create(0))) {
105 fprintf(stderr, "failed to open Oculus HMD, falling back to virtual debug HMD\n");
106 if(!(hmd = ovrHmd_CreateDebug(ovrHmd_DK2))) {
107 fprintf(stderr, "failed to create virtual debug HMD\n");
108 return -1;
109 }
110 }
111 printf("initialized HMD: %s - %s\n", hmd->Manufacturer, hmd->ProductName);
113 /* resize our window to match the HMD resolution */
114 SDL_SetWindowSize(win, hmd->Resolution.w, hmd->Resolution.h);
115 SDL_SetWindowPosition(win, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
116 win_width = hmd->Resolution.w;
117 win_height = hmd->Resolution.h;
119 /* enable position and rotation tracking (and anything else they might add in the future) */
120 ovrHmd_ConfigureTracking(hmd, 0xffffffff, 0);
121 /* retrieve the optimal render target resolution for each eye */
122 eyeres[0] = ovrHmd_GetFovTextureSize(hmd, ovrEye_Left, hmd->DefaultEyeFov[0], 1.0);
123 eyeres[1] = ovrHmd_GetFovTextureSize(hmd, ovrEye_Right, hmd->DefaultEyeFov[1], 1.0);
125 /* and create a single render target texture to encompass both eyes */
126 fb_width = eyeres[0].w + eyeres[1].w;
127 fb_height = eyeres[0].h > eyeres[1].h ? eyeres[0].h : eyeres[1].h;
128 update_rtarg(fb_width, fb_height);
130 /* fill in the ovrGLTexture structures that describe our render target texture */
131 for(i=0; i<2; i++) {
132 fb_ovr_tex[i].OGL.Header.API = ovrRenderAPI_OpenGL;
133 fb_ovr_tex[i].OGL.Header.TextureSize.w = fb_tex_width;
134 fb_ovr_tex[i].OGL.Header.TextureSize.h = fb_tex_height;
135 /* this next field is the only one that differs between the two eyes */
136 fb_ovr_tex[i].OGL.Header.RenderViewport.Pos.x = i == 0 ? 0 : fb_width / 2.0;
137 fb_ovr_tex[i].OGL.Header.RenderViewport.Pos.y = fb_tex_height - fb_height;
138 fb_ovr_tex[i].OGL.Header.RenderViewport.Size.w = fb_width / 2.0;
139 fb_ovr_tex[i].OGL.Header.RenderViewport.Size.h = fb_height;
140 fb_ovr_tex[i].OGL.TexId = fb_tex; /* both eyes will use the same texture id */
141 }
143 /* fill in the ovrGLConfig structure needed by the SDK to draw our stereo pair
144 * to the actual HMD display (SDK-distortion mode)
145 */
146 memset(&glcfg, 0, sizeof glcfg);
147 glcfg.OGL.Header.API = ovrRenderAPI_OpenGL;
148 glcfg.OGL.Header.RTSize = hmd->Resolution;
149 glcfg.OGL.Header.Multisample = 1;
151 if(hmd->HmdCaps & ovrHmdCap_ExtendDesktop) {
152 printf("running in \"extended desktop\" mode\n");
153 } else {
154 /* to sucessfully draw to the HMD display in "direct-hmd" mode, we have to
155 * call ovrHmd_AttachToWindow
156 * XXX: this doesn't work properly yet due to bugs in the oculus 0.4.1 sdk/driver
157 */
158 #ifdef WIN32
159 HWND sys_win = GetActiveWindow();
160 glcfg.OGL.Window = sys_win;
161 glcfg.OGL.DC = wglGetCurrentDC();
162 ovrHmd_AttachToWindow(hmd, sys_win, 0, 0);
163 #endif
164 printf("running in \"direct-hmd\" mode\n");
165 }
167 /* enable low-persistence display and dynamic prediction for lattency compensation */
168 ovrHmd_SetEnabledCaps(hmd, ovrHmdCap_LowPersistence | ovrHmdCap_DynamicPrediction);
170 /* configure SDK-rendering and enable chromatic abberation correction, vignetting, and
171 * timewrap, which shifts the image before drawing to counter any lattency between the call
172 * to ovrHmd_GetEyePose and ovrHmd_EndFrame.
173 */
174 dcaps = ovrDistortionCap_Chromatic | ovrDistortionCap_Vignette | ovrDistortionCap_TimeWarp |
175 ovrDistortionCap_Overdrive;
176 if(!ovrHmd_ConfigureRendering(hmd, &glcfg.Config, dcaps, hmd->DefaultEyeFov, eye_rdesc)) {
177 fprintf(stderr, "failed to configure distortion renderer\n");
178 }
180 /* disable the retarded "health and safety warning" */
181 ovrhmd_EnableHSWDisplaySDKRender(hmd, 0);
183 glEnable(GL_DEPTH_TEST);
184 glEnable(GL_CULL_FACE);
185 glEnable(GL_LIGHTING);
186 glEnable(GL_LIGHT0);
187 glEnable(GL_LIGHT1);
188 glEnable(GL_NORMALIZE);
190 glClearColor(0.1, 0.1, 0.1, 1);
192 chess_tex = gen_chess_tex(1.0, 0.7, 0.4, 0.4, 0.7, 1.0);
193 return 0;
194 }
196 void cleanup(void)
197 {
198 if(hmd) {
199 ovrHmd_Destroy(hmd);
200 }
201 ovr_Shutdown();
203 SDL_Quit();
204 }
206 void toggle_hmd_fullscreen(void)
207 {
208 static int fullscr, prev_x, prev_y;
209 fullscr = !fullscr;
211 if(fullscr) {
212 /* going fullscreen on the rift. save current window position, and move it
213 * to the rift's part of the desktop before going fullscreen
214 */
215 SDL_GetWindowPosition(win, &prev_x, &prev_y);
216 SDL_SetWindowPosition(win, hmd->WindowsPos.x, hmd->WindowsPos.y);
217 SDL_SetWindowFullscreen(win, SDL_WINDOW_FULLSCREEN_DESKTOP);
218 } else {
219 /* return to windowed mode and move the window back to its original position */
220 SDL_SetWindowFullscreen(win, 0);
221 SDL_SetWindowPosition(win, prev_x, prev_y);
222 }
223 }
225 void display(void)
226 {
227 int i;
228 ovrMatrix4f proj;
229 ovrPosef pose[2];
230 float rot_mat[16];
232 /* the drawing starts with a call to ovrHmd_BeginFrame */
233 ovrHmd_BeginFrame(hmd, 0);
235 /* start drawing onto our texture render target */
236 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
237 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
239 /* for each eye ... */
240 for(i=0; i<2; i++) {
241 ovrEyeType eye = hmd->EyeRenderOrder[i];
243 /* -- viewport transformation --
244 * setup the viewport to draw in the left half of the framebuffer when we're
245 * rendering the left eye's view (0, 0, width/2, height), and in the right half
246 * of the framebuffer for the right eye's view (width/2, 0, width/2, height)
247 */
248 glViewport(eye == ovrEye_Left ? 0 : fb_width / 2, 0, fb_width / 2, fb_height);
250 /* -- projection transformation --
251 * we'll just have to use the projection matrix supplied by the oculus SDK for this eye
252 * note that libovr matrices are the transpose of what OpenGL expects, so we have to
253 * use glLoadTransposeMatrixf instead of glLoadMatrixf to load it.
254 */
255 proj = ovrMatrix4f_Projection(hmd->DefaultEyeFov[eye], 0.5, 500.0, 1);
256 glMatrixMode(GL_PROJECTION);
257 glLoadTransposeMatrixf(proj.M[0]);
259 /* -- view/camera transformation --
260 * we need to construct a view matrix by combining all the information provided by the oculus
261 * SDK, about the position and orientation of the user's head in the world.
262 */
263 /* TODO: use ovrHmd_GetEyePoses out of the loop instead */
264 pose[eye] = ovrHmd_GetHmdPosePerEye(hmd, eye);
265 glMatrixMode(GL_MODELVIEW);
266 glLoadIdentity();
267 glTranslatef(eye_rdesc[eye].HmdToEyeViewOffset.x,
268 eye_rdesc[eye].HmdToEyeViewOffset.y,
269 eye_rdesc[eye].HmdToEyeViewOffset.z);
270 /* retrieve the orientation quaternion and convert it to a rotation matrix */
271 quat_to_matrix(&pose[eye].Orientation.x, rot_mat);
272 glMultMatrixf(rot_mat);
273 /* translate the view matrix with the positional tracking */
274 glTranslatef(-pose[eye].Position.x, -pose[eye].Position.y, -pose[eye].Position.z);
275 /* move the camera to the eye level of the user */
276 glTranslatef(0, -ovrHmd_GetFloat(hmd, OVR_KEY_EYE_HEIGHT, 1.65), 0);
278 /* finally draw the scene for this eye */
279 draw_scene();
280 }
282 /* after drawing both eyes into the texture render target, revert to drawing directly to the
283 * display, and we call ovrHmd_EndFrame, to let the Oculus SDK draw both images properly
284 * compensated for lens distortion and chromatic abberation onto the HMD screen.
285 */
286 glBindFramebuffer(GL_FRAMEBUFFER, 0);
287 glViewport(0, 0, win_width, win_height);
289 ovrHmd_EndFrame(hmd, pose, &fb_ovr_tex[0].Texture);
291 assert(glGetError() == GL_NO_ERROR);
292 }
294 void draw_scene(void)
295 {
296 int i;
297 float grey[] = {0.8, 0.8, 0.8, 1};
298 float col[] = {0, 0, 0, 1};
299 float lpos[][4] = {
300 {-8, 2, 10, 1},
301 {0, 15, 0, 1}
302 };
303 float lcol[][4] = {
304 {0.8, 0.8, 0.8, 1},
305 {0.4, 0.3, 0.3, 1}
306 };
308 for(i=0; i<2; i++) {
309 glLightfv(GL_LIGHT0 + i, GL_POSITION, lpos[i]);
310 glLightfv(GL_LIGHT0 + i, GL_DIFFUSE, lcol[i]);
311 }
313 glMatrixMode(GL_MODELVIEW);
315 glPushMatrix();
316 glTranslatef(0, 10, 0);
317 glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, grey);
318 glBindTexture(GL_TEXTURE_2D, chess_tex);
319 glEnable(GL_TEXTURE_2D);
320 draw_box(30, 20, 30, -1.0);
321 glDisable(GL_TEXTURE_2D);
322 glPopMatrix();
324 for(i=0; i<4; i++) {
325 glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, grey);
326 glPushMatrix();
327 glTranslatef(i & 1 ? 5 : -5, 1, i & 2 ? -5 : 5);
328 draw_box(0.5, 2, 0.5, 1.0);
329 glPopMatrix();
331 col[0] = i & 1 ? 1.0 : 0.3;
332 col[1] = i == 0 ? 1.0 : 0.3;
333 col[2] = i & 2 ? 1.0 : 0.3;
334 glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, col);
336 glPushMatrix();
337 if(i & 1) {
338 glTranslatef(0, 0.25, i & 2 ? 2 : -2);
339 } else {
340 glTranslatef(i & 2 ? 2 : -2, 0.25, 0);
341 }
342 draw_box(0.5, 0.5, 0.5, 1.0);
343 glPopMatrix();
344 }
345 }
347 void draw_box(float xsz, float ysz, float zsz, float norm_sign)
348 {
349 glMatrixMode(GL_MODELVIEW);
350 glScalef(xsz * 0.5, ysz * 0.5, zsz * 0.5);
352 if(norm_sign < 0.0) {
353 glFrontFace(GL_CW);
354 }
356 glBegin(GL_QUADS);
357 glNormal3f(0, 0, 1 * norm_sign);
358 glTexCoord2f(0, 0); glVertex3f(-1, -1, 1);
359 glTexCoord2f(1, 0); glVertex3f(1, -1, 1);
360 glTexCoord2f(1, 1); glVertex3f(1, 1, 1);
361 glTexCoord2f(0, 1); glVertex3f(-1, 1, 1);
362 glNormal3f(1 * norm_sign, 0, 0);
363 glTexCoord2f(0, 0); glVertex3f(1, -1, 1);
364 glTexCoord2f(1, 0); glVertex3f(1, -1, -1);
365 glTexCoord2f(1, 1); glVertex3f(1, 1, -1);
366 glTexCoord2f(0, 1); glVertex3f(1, 1, 1);
367 glNormal3f(0, 0, -1 * norm_sign);
368 glTexCoord2f(0, 0); glVertex3f(1, -1, -1);
369 glTexCoord2f(1, 0); glVertex3f(-1, -1, -1);
370 glTexCoord2f(1, 1); glVertex3f(-1, 1, -1);
371 glTexCoord2f(0, 1); glVertex3f(1, 1, -1);
372 glNormal3f(-1 * norm_sign, 0, 0);
373 glTexCoord2f(0, 0); glVertex3f(-1, -1, -1);
374 glTexCoord2f(1, 0); glVertex3f(-1, -1, 1);
375 glTexCoord2f(1, 1); glVertex3f(-1, 1, 1);
376 glTexCoord2f(0, 1); glVertex3f(-1, 1, -1);
377 glEnd();
378 glBegin(GL_TRIANGLE_FAN);
379 glNormal3f(0, 1 * norm_sign, 0);
380 glTexCoord2f(0.5, 0.5); glVertex3f(0, 1, 0);
381 glTexCoord2f(0, 0); glVertex3f(-1, 1, 1);
382 glTexCoord2f(1, 0); glVertex3f(1, 1, 1);
383 glTexCoord2f(1, 1); glVertex3f(1, 1, -1);
384 glTexCoord2f(0, 1); glVertex3f(-1, 1, -1);
385 glTexCoord2f(0, 0); glVertex3f(-1, 1, 1);
386 glEnd();
387 glBegin(GL_TRIANGLE_FAN);
388 glNormal3f(0, -1 * norm_sign, 0);
389 glTexCoord2f(0.5, 0.5); glVertex3f(0, -1, 0);
390 glTexCoord2f(0, 0); glVertex3f(-1, -1, -1);
391 glTexCoord2f(1, 0); glVertex3f(1, -1, -1);
392 glTexCoord2f(1, 1); glVertex3f(1, -1, 1);
393 glTexCoord2f(0, 1); glVertex3f(-1, -1, 1);
394 glTexCoord2f(0, 0); glVertex3f(-1, -1, -1);
395 glEnd();
397 glFrontFace(GL_CCW);
398 }
400 /* update_rtarg creates (and/or resizes) the render target used to draw the two stero views */
401 void update_rtarg(int width, int height)
402 {
403 if(!fbo) {
404 /* if fbo does not exist, then nothing does... create every opengl object */
405 glGenFramebuffers(1, &fbo);
406 glGenTextures(1, &fb_tex);
407 glGenRenderbuffers(1, &fb_depth);
409 glBindTexture(GL_TEXTURE_2D, fb_tex);
410 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
411 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
412 }
414 glBindFramebuffer(GL_FRAMEBUFFER, fbo);
416 /* calculate the next power of two in both dimensions and use that as a texture size */
417 fb_tex_width = next_pow2(width);
418 fb_tex_height = next_pow2(height);
420 /* create and attach the texture that will be used as a color buffer */
421 glBindTexture(GL_TEXTURE_2D, fb_tex);
422 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, fb_tex_width, fb_tex_height, 0,
423 GL_RGBA, GL_UNSIGNED_BYTE, 0);
424 glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fb_tex, 0);
426 /* create and attach the renderbuffer that will serve as our z-buffer */
427 glBindRenderbuffer(GL_RENDERBUFFER, fb_depth);
428 glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, fb_tex_width, fb_tex_height);
429 glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, fb_depth);
431 if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
432 fprintf(stderr, "incomplete framebuffer!\n");
433 }
435 glBindFramebuffer(GL_FRAMEBUFFER, 0);
436 printf("created render target: %dx%d (texture size: %dx%d)\n", width, height, fb_tex_width, fb_tex_height);
437 }
439 int handle_event(SDL_Event *ev)
440 {
441 switch(ev->type) {
442 case SDL_QUIT:
443 return -1;
445 case SDL_KEYDOWN:
446 case SDL_KEYUP:
447 if(key_event(ev->key.keysym.sym, ev->key.state == SDL_PRESSED) == -1) {
448 return -1;
449 }
450 break;
452 default:
453 break;
454 }
456 return 0;
457 }
459 int key_event(int key, int state)
460 {
461 if(state) {
462 /*
463 ovrHSWDisplayState hsw;
464 ovrHmd_GetHSWDisplayState(hmd, &hsw);
465 if(hsw.Displayed) {
466 ovrHmd_DismissHSWDisplay(hmd);
467 }
468 */
470 switch(key) {
471 case 27:
472 return -1;
474 case ' ':
475 /* allow the user to recenter by pressing space */
476 ovrHmd_RecenterPose(hmd);
477 break;
479 case 'f':
480 /* press f to move the window to the HMD */
481 toggle_hmd_fullscreen();
482 break;
484 default:
485 break;
486 }
487 }
488 return 0;
489 }
491 unsigned int next_pow2(unsigned int x)
492 {
493 x -= 1;
494 x |= x >> 1;
495 x |= x >> 2;
496 x |= x >> 4;
497 x |= x >> 8;
498 x |= x >> 16;
499 return x + 1;
500 }
502 /* convert a quaternion to a rotation matrix */
503 void quat_to_matrix(const float *quat, float *mat)
504 {
505 mat[0] = 1.0 - 2.0 * quat[1] * quat[1] - 2.0 * quat[2] * quat[2];
506 mat[4] = 2.0 * quat[0] * quat[1] + 2.0 * quat[3] * quat[2];
507 mat[8] = 2.0 * quat[2] * quat[0] - 2.0 * quat[3] * quat[1];
508 mat[12] = 0.0f;
510 mat[1] = 2.0 * quat[0] * quat[1] - 2.0 * quat[3] * quat[2];
511 mat[5] = 1.0 - 2.0 * quat[0]*quat[0] - 2.0 * quat[2]*quat[2];
512 mat[9] = 2.0 * quat[1] * quat[2] + 2.0 * quat[3] * quat[0];
513 mat[13] = 0.0f;
515 mat[2] = 2.0 * quat[2] * quat[0] + 2.0 * quat[3] * quat[1];
516 mat[6] = 2.0 * quat[1] * quat[2] - 2.0 * quat[3] * quat[0];
517 mat[10] = 1.0 - 2.0 * quat[0]*quat[0] - 2.0 * quat[1]*quat[1];
518 mat[14] = 0.0f;
520 mat[3] = mat[7] = mat[11] = 0.0f;
521 mat[15] = 1.0f;
522 }
524 /* generate a chessboard texture with tiles colored (r0, g0, b0) and (r1, g1, b1) */
525 unsigned int gen_chess_tex(float r0, float g0, float b0, float r1, float g1, float b1)
526 {
527 int i, j;
528 unsigned int tex;
529 unsigned char img[8 * 8 * 3];
530 unsigned char *pix = img;
532 for(i=0; i<8; i++) {
533 for(j=0; j<8; j++) {
534 int black = (i & 1) == (j & 1);
535 pix[0] = (black ? r0 : r1) * 255;
536 pix[1] = (black ? g0 : g1) * 255;
537 pix[2] = (black ? b0 : b1) * 255;
538 pix += 3;
539 }
540 }
542 glGenTextures(1, &tex);
543 glBindTexture(GL_TEXTURE_2D, tex);
544 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
545 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
546 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE, img);
548 return tex;
549 }