SimpleRiftController.cc 27.9 KB
Newer Older
Robert Menzel's avatar
Robert Menzel committed
1
2
3
4
#include <ACGL/HardwareSupport/SimpleRiftController.hh>
#include <ACGL/OpenGL/Creator/ShaderProgramCreator.hh>

#ifdef ACGL_USE_OCULUS_RIFT
5
#if ACGL_RIFT_SDK_VERSION < 32
Robert Menzel's avatar
Robert Menzel committed
6
7
8
9
10
11

using namespace OVR;
using namespace ACGL;
using namespace ACGL::Utils;
using namespace ACGL::Scene;
using namespace ACGL::HardwareSupport;
12
using namespace ACGL::OpenGL;
Robert Menzel's avatar
Robert Menzel committed
13
14
15
using namespace std;


16
SimpleRiftController::SimpleRiftController( uint32_t _riftnumber )
Robert Menzel's avatar
Robert Menzel committed
17
18
19
20
21
22
{
    mSuccessfulConnected = false;
    mDistortionScaleFactor = 1.0f;
    mUseDistortion = true;
    mUseChromaticAberation = true;
    mPredictionTime = -1.0f;
23
    mFoVMultiplier  =  1.0f;
24
    mORSensorFusion = NULL;
Robert Menzel's avatar
Robert Menzel committed
25
26
27

    if (_riftnumber != 0) {
        error() << "opening any other Rift than ID 0 is not supported yet! Trying to open Rift nr 0" << endl;
28
        _riftnumber = 0;
Robert Menzel's avatar
Robert Menzel committed
29
30
    }

31
32
33
34
35
36
37
38
39
40
41
42
#ifdef ACGL_DEBUG
    LogMaskConstants mask = LogMask_All;
#else
    LogMaskConstants mask = LogMask_None;
#endif
    System::Init( Log::ConfigureDefaultLog( mask) );

    mORManager = *DeviceManager::Create();
    if (!mORManager) {
        error() << "could not create a Rift Device Manager" << endl;
        mORDevice = NULL;
    } else {
43
44
45
46
47
48
49
50
51
52
53
54
55
        DeviceEnumerator<HMDDevice> hmdEnumerator = mORManager->EnumerateDevices<HMDDevice>();

        bool riftOK = true;
        for (uint32_t i = 0; i < _riftnumber; ++i) {
            riftOK = hmdEnumerator.Next();
        }

        if (riftOK) {
            mORDevice = *hmdEnumerator.CreateDevice();
        } else {
            error() << "Rift number " << _riftnumber << " not found" << endl;
            mORDevice = NULL;
        }
56
    }
Robert Menzel's avatar
Robert Menzel committed
57

58
    mORHMDInfo = new OVR::HMDInfo();
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
    const char *profileName = NULL;
    OVR::Ptr<OVR::Profile> profile = NULL;
    if (mORDevice) {
        // get profile of this device:
        profile     = mORDevice->GetProfile();
        profileName = mORDevice->GetProfileName();

        // get device info:
        if (!mORDevice->GetDeviceInfo( mORHMDInfo )) {
            error() << "could not get HMD device info" << endl;
            return;
        }

        mORSensor = *mORDevice->GetSensor();
        if (!mORSensor) {
            error() << "could not get sensor of HMD (is the USB pluged in?)" << endl;
            #ifdef __linux
            error() << "do you have read/write permissions of /dev/hidraw* ?" << endl;
            #endif
        } else {
            // configure sensor
            mORSensorFusion = new OVR::SensorFusion();
            mORSensorFusion->AttachToSensor( mORSensor );

            mSuccessfulConnected = true;
        }
    } else {
        // get the default profile:
        OVR::Ptr<OVR::ProfileManager> pm = *OVR::ProfileManager::Create();
        profileName = pm->GetDefaultProfileName(OVR::Profile_RiftDK1);
        profile     = pm->LoadProfile(OVR::Profile_RiftDK1, profileName);

        // default device info from the first devkit:
        mORHMDInfo->HResolution = 1280;
        mORHMDInfo->VResolution =  800;
        mORHMDInfo->HScreenSize = 0.14976f;
        mORHMDInfo->VScreenSize = 0.0935f;
        mORHMDInfo->VScreenCenter = mORHMDInfo->VScreenSize*0.5f;
        mORHMDInfo->DistortionK[0]        = 1.0f;
        mORHMDInfo->DistortionK[1]        = 0.22f;
        mORHMDInfo->DistortionK[2]        = 0.24f;
        mORHMDInfo->EyeToScreenDistance   = 0.041f;
        mORHMDInfo->ChromaAbCorrection[0] = 0.996f;
        mORHMDInfo->ChromaAbCorrection[1] = -0.004f;
        mORHMDInfo->ChromaAbCorrection[2] = 1.014f;
        mORHMDInfo->ChromaAbCorrection[3] = 0.0f;
        mORHMDInfo->LensSeparationDistance = 0.0635f;
        mORHMDInfo->InterpupillaryDistance = 0.064f;
        mORHMDInfo->DisplayDeviceName[0] = 0;
    }
109
110
111
112
113
114
115
116

    mCamera = SharedHMDCamera(); // set to NULL
    attachCamera( SharedHMDCamera( new HMDCamera() ) ); // attach a blank camera
    // set a good default viewport:
    glm::uvec2 viewport = getPhysicalScreenResolution();
    mCamera->resize( viewport.x/2, viewport.y );
    updateCameraFoV(); // indirectly based on the viewport

117
118
119
    if (profile) {
        mCamera->setInterpupillaryDistance( profile->GetIPD() );
        mCamera->setEyeHeight( profile->GetEyeHeight() );
Robert Menzel's avatar
Robert Menzel committed
120
121
    }

122
123
124
125
126
127
128
129
130
131
132
133
134
    if (mSuccessfulConnected) {
        bool magneticYawCorrection = (mORSensorFusion->IsYawCorrectionEnabled() && mORSensorFusion->HasMagCalibration());

        if (magneticYawCorrection && profile) {
            debug() << "Connected to Rift (SDK: "<<OVR_VERSION_STRING<<"). Using local user settings of profile " << profileName << ". Yaw correction active." << endl;
        } else if (!magneticYawCorrection && profile) {
            debug() << "Connected to Rift (SDK: "<<OVR_VERSION_STRING<<"). Using local user settings of profile " << profileName << ". Yaw correction inactive." << endl;
        } else if (magneticYawCorrection && !profile) {
            debug() << "Connected to Rift (SDK: "<<OVR_VERSION_STRING<<"). Yaw correction active. No local user profile found." << endl;
        } else {
            debug() << "Connected to Rift (SDK: "<<OVR_VERSION_STRING<<"). Yaw correction inactive. No local user profile found." << endl;
        }
    } else {
135
136
        error() << "Could not create a Rift device - using default values (SDK: "<<OVR_VERSION_STRING<<")." << endl;
        error() << "In some cases this happens if the Rift is NOT set to the native resolution (1280*800 in case of the first/old DevKit)." << endl;
Robert Menzel's avatar
Robert Menzel committed
137
138
139
140
141
142
143
144
145
146
147
    }
}

SimpleRiftController::~SimpleRiftController()
{
    // setting the reference counted pointers to NULL will call the object destructors:
    debug() << "disconnecting from Oculus Rift..." << endl;

    mORSensor  = NULL;
    mORDevice  = NULL;
    mORManager = NULL;
148
149
    delete mORHMDInfo;
    delete mORSensorFusion;
Robert Menzel's avatar
Robert Menzel committed
150
151
152
153
154
    System::Destroy(); // Oculus Rift
}

void SimpleRiftController::setPrediction( float _seconds )
{
155
156
157
158
159
160
161
    if(getSuccessfulConnected()) {
        if ( _seconds >= 0.0f ) {
            mORSensorFusion->SetPrediction( _seconds );
        } else {
            mORSensorFusion->SetPrediction( 0.0f, false );
        }
        mPredictionTime = _seconds;
Robert Menzel's avatar
Robert Menzel committed
162
163
164
    }
}

165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
glm::quat riftQuatToGLM( const Quatf &_q )
{
    glm::quat glmQuat;

    glmQuat.x = _q.x;
    glmQuat.y = _q.y;
    glmQuat.z = _q.z;
    glmQuat.w = _q.w;

    return glmQuat;
}

glm::quat SimpleRiftController::getFusedRotationQuaternion()
{
    return riftQuatToGLM( mORSensorFusion->GetPredictedOrientation() );
}

glm::quat SimpleRiftController::getRotationQuaternion()
{
    return riftQuatToGLM( mORSensorFusion->GetOrientation() );
}

Robert Menzel's avatar
Robert Menzel committed
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
glm::mat4 SimpleRiftController::getProjectionMatrixFromCamera()
{
    if (!mCamera) return glm::mat4();
    return mCamera->getProjectionMatrix();
}

glm::mat3 riftMatrixToGLM( const Matrix4f &_mat4 )
{
    glm::mat3 glmMat3;

    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            glmMat3[i][j] = _mat4.M[i][j];
        }
    }

    return glmMat3;
}

void SimpleRiftController::attachCamera( ACGL::Scene::SharedHMDCamera _camera )
{
    mCamera = _camera;
209
    mCamera->setInterpupillaryDistance( mORHMDInfo->InterpupillaryDistance );
Robert Menzel's avatar
Robert Menzel committed
210
211
    updateCameraFoV();

212
213
214
    float viewCenterH = mORHMDInfo->HScreenSize * 0.25f;
    float eyeProjectionShift = viewCenterH - mORHMDInfo->LensSeparationDistance * 0.5f;
    float offsetX = 4.0f * eyeProjectionShift / mORHMDInfo->HScreenSize;
Robert Menzel's avatar
Robert Menzel committed
215
216
217
218
219
220
221
222
223
224
225
    mCamera->setProjectionCenterOffset( glm::vec2(offsetX, 0.0f));

    mCamera->setNeckToEyeVerticalDistance(   0.12f );
    mCamera->setNeckToEyeHorizontalDistance( 0.08f );
}

glm::mat3 SimpleRiftController::getCurrentRotation()
{
    // update orientation:
    Quatf q;
    if (mPredictionTime > 0.0f) {
226
        q = mORSensorFusion->GetPredictedOrientation();
Robert Menzel's avatar
Robert Menzel committed
227
    } else {
228
        q = mORSensorFusion->GetOrientation();
Robert Menzel's avatar
Robert Menzel committed
229
230
231
232
233
234
235
236
    }

    q.Normalize();

    //debug() << "Rift orientation: " << q.x << " " << q.y << " " << q.z << " " << q.w << endl;

    q = mInverseNeutralRotation * q;

237
    if (mORSensorFusion->IsYawCorrectionEnabled()) {
Robert Menzel's avatar
Robert Menzel committed
238
239
240
241
242
243
244
245
246
        //debug() << "yaw corrected" << endl;
    }

    Matrix4f orientation( q );
    return riftMatrixToGLM( orientation );
}

void SimpleRiftController::setNeutralPosition()
{
247
    mInverseNeutralRotation = mORSensorFusion->GetOrientation();
Robert Menzel's avatar
Robert Menzel committed
248
249
250
251
252
253
254
255
256
    mInverseNeutralRotation.Normalize();
    mInverseNeutralRotation.x *= -1.0;
    mInverseNeutralRotation.y *= -1.0;
    mInverseNeutralRotation.z *= -1.0;
}

void SimpleRiftController::setNeutralYaw()
{
    mInverseNeutralRotation = OVR::Quatf();
257
    mORSensorFusion->Reset();
Robert Menzel's avatar
Robert Menzel committed
258
259
260
261
262
263
264
265
266
267
268
}

void SimpleRiftController::updateCamera()
{
    if (!mSuccessfulConnected) return;

    mCamera->setHMDRotation( getCurrentRotation() );
}

void SimpleRiftController::updateCameraFoV()
{
269
270
    float percievedHalfRTDist = (mORHMDInfo->VScreenSize / 2) * mDistortionScaleFactor;
    float vfov = 2.0f * atan( percievedHalfRTDist/mORHMDInfo->EyeToScreenDistance );
Robert Menzel's avatar
Robert Menzel committed
271
272
    vfov = ACGL::Math::Functions::calcRadToDeg( vfov );

273
274
275
276
    vfov *= mFoVMultiplier;
    if (vfov <    5.0f) vfov =   5.0f;
    if (vfov >= 175.0f) vfov = 175.0f;

Robert Menzel's avatar
Robert Menzel committed
277
    mCamera->setVerticalFieldOfView( vfov );
278
    //debug() << "update VFoV: " << vfov << endl;
Robert Menzel's avatar
Robert Menzel committed
279
280
281
282
}

glm::uvec2 SimpleRiftController::getPhysicalScreenResolution()
{
283
    return glm::uvec2( mORHMDInfo->HResolution, mORHMDInfo->VResolution );
Robert Menzel's avatar
Robert Menzel committed
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
}

void SimpleRiftController::setDistortionScaleFactor( float _f ) {
    if (mDistortionScaleFactor == _f) return;
    ACGL::Utils::debug() << "set distortion scale " << _f << std::endl;
    mDistortionScaleFactor = _f;
    updateCameraFoV();
}

glm::vec4 SimpleRiftController::getShaderValue( int v )
{
    //
    // note that this isn't the virtul camera viewport (the size the offscreen rendering is performed in)
    // but the physical size of the Rifts screen:
    glm::vec2 windowSize = glm::vec2( getPhysicalScreenResolution() );

    glm::vec2 viewport = windowSize;
    viewport.x /= 2;

    glm::vec2 viewportPosL = glm::vec2(          0, 0 );
    glm::vec2 viewportPosR = glm::vec2( viewport.x, 0 );
    glm::vec2 viewportSize = glm::vec2( viewport.x, viewport.y ); // viewport of one eye

    float w  = float(viewportSize.x) / float(windowSize.x);
    float h  = float(viewportSize.y) / float(windowSize.y);
    float xl = float(viewportPosL.x) / float(windowSize.x);
    float yl = float(viewportPosL.y) / float(windowSize.y);

    float xr = float(viewportPosR.x) / float(windowSize.x);
    float yr = float(viewportPosR.y) / float(windowSize.y);

    // both eyes have the same aspect ratio: hals the windowsize as the image was rendered side by side
    float aspectRatio =  (0.5 * windowSize.x) / windowSize.y;

318
319
320
    float lensOffset        = mORHMDInfo->LensSeparationDistance * 0.5f;
    float lensShift         = mORHMDInfo->HScreenSize * 0.25f - lensOffset;
    float lensViewportShift = 4.0f * lensShift / mORHMDInfo->HScreenSize;
Robert Menzel's avatar
Robert Menzel committed
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
    float lensViewportShiftL =  lensViewportShift;
    float lensViewportShiftR = -lensViewportShift;

    glm::vec4 lensCenter;
    lensCenter.x = xl + (w + lensViewportShiftL * 0.5f)*0.5f;
    lensCenter.y = yl + h*0.5f;
    lensCenter.z = xr + (w + lensViewportShiftR * 0.5f)*0.5f;
    lensCenter.w = yr + h*0.5f;

    glm::vec4 screenCenter;
    screenCenter.x = xl + w*0.5f;
    screenCenter.y = yl + h*0.5f;
    screenCenter.z = xr + w*0.5f;
    screenCenter.w = yr + h*0.5f;

    glm::vec4 scale;
    scale.x = (w/2);
    scale.y = (h/2) * aspectRatio;
    scale /= mDistortionScaleFactor;

    glm::vec4 scaleIn;
    scaleIn.x = (2/w);
    scaleIn.y = (2/h) / aspectRatio;

    if (v == 0) return lensCenter;
    if (v == 1) return screenCenter;
    if (v == 2) return scale;
    return scaleIn;
}

glm::vec4 SimpleRiftController::getLensCenter()
{
    return getShaderValue(0);
}

glm::vec4 SimpleRiftController::getScreenCenter()
{
    return getShaderValue(1);
}

glm::vec4 SimpleRiftController::getScale()
{
    return getShaderValue(2);
}

glm::vec4 SimpleRiftController::getScaleIn()
{
    return getShaderValue(3);
}

glm::vec4 SimpleRiftController::getHmdWarpParam()
{
    glm::vec4 distortionK;
374
375
376
377
    distortionK.x = mORHMDInfo->DistortionK[0];
    distortionK.y = mORHMDInfo->DistortionK[1];
    distortionK.z = mORHMDInfo->DistortionK[2];
    distortionK.w = mORHMDInfo->DistortionK[3];
Robert Menzel's avatar
Robert Menzel committed
378
379
380
381
382
383
    return distortionK;
}

glm::vec4 SimpleRiftController::getChromAbParam()
{
    glm::vec4 chromaK;
384
385
386
387
    chromaK.x = mORHMDInfo->ChromaAbCorrection[0];
    chromaK.y = mORHMDInfo->ChromaAbCorrection[1];
    chromaK.z = mORHMDInfo->ChromaAbCorrection[2];
    chromaK.w = mORHMDInfo->ChromaAbCorrection[3];
Robert Menzel's avatar
Robert Menzel committed
388
389
390
391
392
    return chromaK;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
Robert Menzel's avatar
Robert Menzel committed
393
// optional rendering nuild-in shaders:
Robert Menzel's avatar
Robert Menzel committed
394
395
396
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Robert Menzel's avatar
Robert Menzel committed
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
const char *VS_SOURCE = "#version 150 core \n\
\n\
        out vec2 vTexCoord;\n\
\n\
        const vec2 quad[4] = vec2[] (\n\
            vec2(-1.0, 1.0),\n\
            vec2(-1.0,-1.0),\n\
            vec2( 1.0, 1.0),\n\
            vec2( 1.0,-1.0)\n\
        );\n\
\n\
        void main()\n\
        {\n\
            vec2 p = quad[ gl_VertexID ];\n\
\n\
            vTexCoord   = p * vec2(0.5, 0.5) + vec2(0.5, 0.5);\n\
            gl_Position = vec4(p, 0.0, 1.0);\n\
        }";

const char *FS_SOURCE_SIDE_BY_SIDE = "#version 150 core\n\
        \n\
        uniform sampler2D uSamplerColor;\n\
        \n\
        // defaults are the values of the first dev kit rendered at 1280 by 800:\n\
        uniform vec4 uLensCenter    = vec4(0.287994, 0.5, 0.712006, 0.5);\n\
        uniform vec4 uScreenCenter  = vec4(0.25, 0.5,  0.75, 0.5);\n\
        uniform vec4 uScale         = vec4(0.25, 0.4,  0.25, 0.4);\n\
        uniform vec4 uScaleIn       = vec4(4.0,  2.5,  4.0,  2.5);\n\
        uniform vec4 uHmdWarpParam  = vec4(1.0,  0.22, 0.24, 0.0);\n\
        uniform vec4 uChromAbParam  = vec4(0.996, -0.004, 1.014, 0.0);\n\
        uniform bool uDistort = true;\n\
        uniform bool uCorrectChromaticAberation = true;\n\
        in vec2 vTexCoord;\n\
        out vec4 oColor;\n\
        \n\
        //\n\
        // taken and adjusted from the SDK sample:\n\
        //\n\
        vec4 getDistortedColorAt( in vec2 position, in bool leftEye )\n\
        {\n\
            vec2 LensCenter;\n\
            vec2 ScreenCenter;\n\
            vec2 Scale   = uScale.xy;\n\
            vec2 ScaleIn = uScaleIn.xy;\n\
            if (leftEye) {\n\
                // left half\n\
                LensCenter   = uLensCenter.xy;\n\
                ScreenCenter = uScreenCenter.xy;\n\
            } else {\n\
                // right half\n\
                LensCenter   = uLensCenter.zw;\n\
                ScreenCenter = uScreenCenter.zw;\n\
            }\n\
            // vector from the lens center to the current point:\n\
            vec2  theta = (position - LensCenter) * ScaleIn; \n\
            // scaled distance from the lens center:\n\
            float rSq = theta.x * theta.x + theta.y * theta.y;\n\
            vec2  theta1 = theta * (uHmdWarpParam.x + uHmdWarpParam.y * rSq + uHmdWarpParam.z * rSq * rSq + uHmdWarpParam.w * rSq * rSq * rSq);\n\
            // Detect whether blue texture coordinates are out of range since these will scaled out the furthest.\n\
            vec2 thetaBlue = theta1 * (uChromAbParam.z + uChromAbParam.w * rSq);\n\
            vec2 tcBlue = Scale * thetaBlue + LensCenter;\n\
            if (!all(equal(clamp(tcBlue, ScreenCenter-vec2(0.25,0.5), ScreenCenter+vec2(0.25,0.5)), tcBlue)))\n\
            {\n\
                return vec4(0.0);\n\
            }\n\
            // Do green lookup (no scaling).\n\
            vec2  tcGreen = Scale * theta1 + LensCenter;\n\
            vec4  center = texture(uSamplerColor, tcGreen);\n\
            if (!uCorrectChromaticAberation) {\n\
                return center;\n\
            }\n\
            // Now do blue texture lookup.\n\
            float blue = texture(uSamplerColor, tcBlue).b;\n\
            // Do red scale and lookup.\n\
            vec2  thetaRed = theta1 * (uChromAbParam.x + uChromAbParam.y * rSq);\n\
            vec2  tcRed = Scale * thetaRed + LensCenter;\n\
            float red = texture(uSamplerColor, tcRed).r;\n\
            return vec4(red, center.g, blue, center.a);\n\
        }\n\
 \n\
        void main()\n\
        {\n\
            if (uDistort) {\n\
                bool leftEye = (vTexCoord.x < 0.5);\n\
                oColor = getDistortedColorAt( vTexCoord, leftEye );\n\
            } else {\n\
                oColor = texture(uSamplerColor, vTexCoord);\n\
            }\n\
        }\n\
";

const char *FS_SOURCE_TWO_TEXTURE = "#version 150 core\n\
        \n\
        uniform sampler2D uSamplerColorLeft;\n\
        uniform sampler2D uSamplerColorRight;\n\
        \n\
        // defaults are the values of the first dev kit rendered at 1280 by 800:\n\
        uniform vec4 uLensCenter    = vec4(0.287994, 0.5, 0.712006, 0.5);\n\
        uniform vec4 uScreenCenter  = vec4(0.25, 0.5,  0.75, 0.5);\n\
        uniform vec4 uScale         = vec4(0.25, 0.4,  0.25, 0.4);\n\
        uniform vec4 uScaleIn       = vec4(4.0,  2.5,  4.0,  2.5);\n\
        uniform vec4 uHmdWarpParam  = vec4(1.0,  0.22, 0.24, 0.0);\n\
        uniform vec4 uChromAbParam  = vec4(0.996, -0.004, 1.014, 0.0);\n\
        uniform bool uDistort = true;\n\
        uniform bool uCorrectChromaticAberation = true;\n\
        in vec2 vTexCoord;\n\
        out vec4 oColor;\n\
        \n\
        //\n\
        // taken and adjusted from the SDK sample:\n\
        //\n\
        vec4 getDistortedColorAt( in vec2 position, in bool leftEye )\n\
        {\n\
            vec2 LensCenter;\n\
            vec2 ScreenCenter;\n\
            vec2 Scale   = uScale.xy;\n\
            vec2 ScaleIn = uScaleIn.xy;\n\
            if (leftEye) {\n\
                // left half\n\
                LensCenter   = uLensCenter.xy;\n\
                ScreenCenter = uScreenCenter.xy;\n\
            } else {\n\
                // right half\n\
                LensCenter   = uLensCenter.zw;\n\
                ScreenCenter = uScreenCenter.zw;\n\
            }\n\
        \n\
            // vector from the lens center to the current point:\n\
525
            vec2  theta = (position - LensCenter) * ScaleIn; // Scales to [-1, 1]\n\
Robert Menzel's avatar
Robert Menzel committed
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
        \n\
            // scaled distance from the lens center:\n\
            float rSq = theta.x * theta.x + theta.y * theta.y;\n\
        \n\
            vec2  theta1 = theta * (uHmdWarpParam.x + uHmdWarpParam.y * rSq + uHmdWarpParam.z * rSq * rSq + uHmdWarpParam.w * rSq * rSq * rSq);\n\
        \n\
            // Detect whether blue texture coordinates are out of range since these will scaled out the furthest.\n\
            vec2 thetaBlue = theta1 * (uChromAbParam.z + uChromAbParam.w * rSq);\n\
            vec2 tcBlue = Scale * thetaBlue + LensCenter;\n\
            if (!all(equal(clamp(tcBlue, ScreenCenter-vec2(0.25,0.5), ScreenCenter+vec2(0.25,0.5)), tcBlue)))\n\
            {\n\
                return vec4(0.0);\n\
            }\n\
            // Do green lookup (no scaling).\n\
            vec2  tcGreen = Scale * theta1 + LensCenter;\n\
            vec4  center;\n\
            if (leftEye) {\n\
                tcGreen.x *= 2.0;\n\
                center = texture(uSamplerColorLeft, tcGreen);\n\
            } else {\n\
                tcGreen.x -= 0.5;\n\
                tcGreen.x *= 2.0;\n\
                center = texture(uSamplerColorRight, tcGreen);\n\
            }\n\
            if (!uCorrectChromaticAberation) {\n\
                return center;\n\
            }\n\
            // Now do blue texture lookup.\n\
            float blue;\n\
            if (leftEye) {\n\
                tcBlue.x *= 2.0;\n\
                blue = texture(uSamplerColorLeft, tcBlue).b;\n\
            } else {\n\
                tcBlue.x -= 0.5;\n\
                tcBlue.x *= 2.0;\n\
                blue = texture(uSamplerColorRight, tcBlue).b;\n\
            }\n\
            // Do red scale and lookup.\n\
            vec2  thetaRed = theta1 * (uChromAbParam.x + uChromAbParam.y * rSq);\n\
            vec2  tcRed = Scale * thetaRed + LensCenter;\n\
            float red;\n\
            if (leftEye) {\n\
                tcRed.x *= 2.0;\n\
                red = texture(uSamplerColorLeft, tcRed).r;\n\
            } else {\n\
                tcRed.x -= 0.5;\n\
                tcRed.x *= 2.0;\n\
                red = texture(uSamplerColorRight, tcRed).r;\n\
            }\n\
            return vec4(red, center.g, blue, center.a);\n\
        }\n\
        \n\
        void main()\n\
        {\n\
            bool leftEye = (vTexCoord.x < 0.5);\n\
            if (uDistort) {\n\
                oColor = getDistortedColorAt( vTexCoord, leftEye );\n\
            } else {\n\
                vec2 inTextureCoordinate = vTexCoord;\n\
                inTextureCoordinate.x *= 2.0;\n\
                if (leftEye) {\n\
                    oColor = texture( uSamplerColorLeft, inTextureCoordinate );\n\
                } else {\n\
                    oColor = texture( uSamplerColorRight, inTextureCoordinate );\n\
                }\n\
            }\n\
        }\n\
\n\
";
595

Robert Menzel's avatar
Robert Menzel committed
596
597
598
599
600
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// optional rendering:
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
601

Robert Menzel's avatar
Robert Menzel committed
602
603
604
605
606
607
void SimpleRiftController::renderDistorted( OpenGL::ConstSharedTexture2D _sideBySideTexture )
{
    if (!mDistortShaderSideBySide) {
        // initialize shaders:
        mDistortShaderSideBySide = OpenGL::ShaderProgramFileManager::the()->get( OpenGL::ShaderProgramCreator("RiftDistortSideBySide.fsh").andFile("RiftDistort.vsh") );
        if (!mDistortShaderSideBySide) {
608
609
610
611
612
613
614
615
616
617
618
619
620
            ACGL::Utils::debug() << "SimpleRiftController: using build-in shaders" << std::endl;

            mDistortShaderSideBySide = SharedShaderProgram( new ShaderProgram() );

            SharedShader vs = SharedShader( new Shader( GL_VERTEX_SHADER ) );
            vs->setSource( VS_SOURCE );

            SharedShader fs = SharedShader( new Shader( GL_FRAGMENT_SHADER ) );
            fs->setSource( FS_SOURCE_SIDE_BY_SIDE );

            mDistortShaderSideBySide->attachShader( vs );
            mDistortShaderSideBySide->attachShader( fs );
            mDistortShaderSideBySide->link();
Robert Menzel's avatar
Robert Menzel committed
621
            mDistortShaderSideBySide->use();
Robert Menzel's avatar
Robert Menzel committed
622
623
624
625
626
627
628
629
630
631
632
633
634
635


            uLensCenter    = mDistortShaderSideBySide->getUniformLocation("uLensCenter");
            uScreenCenter  = mDistortShaderSideBySide->getUniformLocation("uScreenCenter");
            uScale         = mDistortShaderSideBySide->getUniformLocation("uScale");
            uScaleIn       = mDistortShaderSideBySide->getUniformLocation("uScaleIn");
            uHmdWarpParam  = mDistortShaderSideBySide->getUniformLocation("uHmdWarpParam");
            uChromAbParam  = mDistortShaderSideBySide->getUniformLocation("uChromAbParam");
            uDistort       = mDistortShaderSideBySide->getUniformLocation("uDistort");
            uCorrectChromaticAberation = mDistortShaderSideBySide->getUniformLocation("uCorrectChromaticAberation");

            mBuildInShader = true;
            mDistortShaderTwoTextures->setUniform(uLensCenter,   getLensCenter() );
            mDistortShaderTwoTextures->setUniform(uScreenCenter, getScreenCenter() );
Robert Menzel's avatar
Robert Menzel committed
636
            mDistortShaderTwoTextures->setUniform(uScale,        getScale() );
Robert Menzel's avatar
Robert Menzel committed
637
638
            mDistortShaderTwoTextures->setUniform(uHmdWarpParam, getHmdWarpParam() );
            mDistortShaderTwoTextures->setUniform(uChromAbParam, getChromAbParam() );
639
640
        } else {
            ACGL::Utils::debug() << "SimpleRiftController: using application provided shaders" << std::endl;
Robert Menzel's avatar
Robert Menzel committed
641
            mBuildInShader = false;
Robert Menzel's avatar
Robert Menzel committed
642
643
644
645
646
        }
    }

    mDistortShaderSideBySide->use();
    mDistortShaderSideBySide->setTexture("uSamplerColor", _sideBySideTexture, 0 );
Robert Menzel's avatar
Robert Menzel committed
647
    renderDistortedP( mDistortShaderSideBySide );
Robert Menzel's avatar
Robert Menzel committed
648
649
650
651
652
653
654
655
}

void SimpleRiftController::renderDistorted( OpenGL::ConstSharedTexture2D _leftTexture, OpenGL::ConstSharedTexture2D _rightTexture )
{
    if (!mDistortShaderTwoTextures) {
        // initialize shaders:
        mDistortShaderTwoTextures = OpenGL::ShaderProgramFileManager::the()->get( OpenGL::ShaderProgramCreator("RiftDistortTwoTexture.fsh").andFile("RiftDistort.vsh") );
        if (!mDistortShaderTwoTextures) {
656
657
658
659
660
661
662
663
664
665
666
667
668
            ACGL::Utils::debug() << "SimpleRiftController: using build-in shaders" << std::endl;

            mDistortShaderTwoTextures = SharedShaderProgram( new ShaderProgram() );

            SharedShader vs = SharedShader( new Shader( GL_VERTEX_SHADER ) );
            vs->setSource( VS_SOURCE );

            SharedShader fs = SharedShader( new Shader( GL_FRAGMENT_SHADER ) );
            fs->setSource( FS_SOURCE_TWO_TEXTURE );

            mDistortShaderTwoTextures->attachShader( vs );
            mDistortShaderTwoTextures->attachShader( fs );
            mDistortShaderTwoTextures->link();
Robert Menzel's avatar
Robert Menzel committed
669
670
671
672
673
674
675
676
677
678
679
680
681
682
            mDistortShaderTwoTextures->use();

            uLensCenter    = mDistortShaderTwoTextures->getUniformLocation("uLensCenter");
            uScreenCenter  = mDistortShaderTwoTextures->getUniformLocation("uScreenCenter");
            uScale         = mDistortShaderTwoTextures->getUniformLocation("uScale");
            uScaleIn       = mDistortShaderTwoTextures->getUniformLocation("uScaleIn");
            uHmdWarpParam  = mDistortShaderTwoTextures->getUniformLocation("uHmdWarpParam");
            uChromAbParam  = mDistortShaderTwoTextures->getUniformLocation("uChromAbParam");
            uDistort       = mDistortShaderTwoTextures->getUniformLocation("uDistort");
            uCorrectChromaticAberation = mDistortShaderTwoTextures->getUniformLocation("uCorrectChromaticAberation");

            mBuildInShader = true;
            mDistortShaderTwoTextures->setUniform(uLensCenter,   getLensCenter() );
            mDistortShaderTwoTextures->setUniform(uScreenCenter, getScreenCenter() );
Robert Menzel's avatar
Robert Menzel committed
683
            mDistortShaderTwoTextures->setUniform(uScale,        getScale() );
Robert Menzel's avatar
Robert Menzel committed
684
685
            mDistortShaderTwoTextures->setUniform(uHmdWarpParam, getHmdWarpParam() );
            mDistortShaderTwoTextures->setUniform(uChromAbParam, getChromAbParam() );
686
687
688

        } else {
            ACGL::Utils::debug() << "SimpleRiftController: using application provided shaders" << std::endl;
Robert Menzel's avatar
Robert Menzel committed
689
            mBuildInShader = false;
Robert Menzel's avatar
Robert Menzel committed
690
691
692
693
694
695
        }
    }

    mDistortShaderTwoTextures->use();
    mDistortShaderTwoTextures->setTexture("uSamplerColorLeft",  _leftTexture,  0 );
    mDistortShaderTwoTextures->setTexture("uSamplerColorRight", _rightTexture, 1 );
Robert Menzel's avatar
Robert Menzel committed
696

Robert Menzel's avatar
Robert Menzel committed
697
    renderDistortedP( mDistortShaderTwoTextures );
Robert Menzel's avatar
Robert Menzel committed
698
699
}

Robert Menzel's avatar
Robert Menzel committed
700
void SimpleRiftController::renderDistortedP( ACGL::OpenGL::ConstSharedShaderProgram _program )
Robert Menzel's avatar
Robert Menzel committed
701
702
703
704
705
706
707
708
709
710
711
712
{
    // if the user defined an output size, use that, otherwise default to the Rifts size:
    glm::uvec2 windowSize = mOutputViewport;
    if (windowSize.x == 0) {
        windowSize = getPhysicalScreenResolution();
    }

    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    glViewport( 0, 0, windowSize.x, windowSize.y );
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // we assume that _program is in use as this should only get called from our own functions
Robert Menzel's avatar
Robert Menzel committed
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728

    if (!mBuildInShader) {
        // the shader might have been reloaded
        _program->setUniform("uLensCenter",   getLensCenter() );
        _program->setUniform("uScreenCenter", getScreenCenter() );
        _program->setUniform("uScale",        getScale() );
        _program->setUniform("uScaleIn",      getScaleIn() );
        _program->setUniform("uHmdWarpParam", getHmdWarpParam() );
        _program->setUniform("uChromAbParam", getChromAbParam() );
        _program->setUniform("uDistort",      (int)mUseDistortion );
        _program->setUniform("uCorrectChromaticAberation", (int)mUseChromaticAberation );
    } else {
        _program->setUniform(uScaleIn,      getScaleIn() );
        _program->setUniform(uDistort,      (int)mUseDistortion );
        _program->setUniform(uCorrectChromaticAberation, (int)mUseChromaticAberation );
    }
Robert Menzel's avatar
Robert Menzel committed
729
730
731

    // attribute-less rendering:
    // just rendering a fullscreen quad
Robert Menzel's avatar
Robert Menzel committed
732
733
734
735
    if (!mVAO) {
        mVAO = SharedVertexArrayObject( new VertexArrayObject() );
    }
    mVAO->bind(); // 'empty' VAO -> no attributes are defined
Robert Menzel's avatar
Robert Menzel committed
736
737
738
739
    glDrawArrays( GL_TRIANGLE_STRIP, 0, 4 ); // create 2 triangles with no attributes
}

#endif
740
#endif