SimpleRiftController.cc 27.3 KB
Newer Older
Robert Menzel's avatar
Robert Menzel committed
1 2 3 4 5 6 7 8 9 10
#include <ACGL/HardwareSupport/SimpleRiftController.hh>
#include <ACGL/OpenGL/Creator/ShaderProgramCreator.hh>

#ifdef ACGL_USE_OCULUS_RIFT

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


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

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

30 31 32 33 34 35 36 37 38 39 40 41
#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 {
42 43 44 45 46 47 48 49 50 51 52 53 54
        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;
        }
55
    }
Robert Menzel's avatar
Robert Menzel committed
56

57
    mORHMDInfo = new OVR::HMDInfo();
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 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
    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;
    }
108 109 110 111 112 113 114 115

    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

116 117 118
    if (profile) {
        mCamera->setInterpupillaryDistance( profile->GetIPD() );
        mCamera->setEyeHeight( profile->GetEyeHeight() );
Robert Menzel's avatar
Robert Menzel committed
119 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 {
        error() << "could not create a Rift device - using default values (SDK: "<<OVR_VERSION_STRING<<")." << endl;
Robert Menzel's avatar
Robert Menzel committed
135 136 137 138 139 140 141 142 143 144 145
    }
}

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;
146 147
    delete mORHMDInfo;
    delete mORSensorFusion;
Robert Menzel's avatar
Robert Menzel committed
148 149 150 151 152
    System::Destroy(); // Oculus Rift
}

void SimpleRiftController::setPrediction( float _seconds )
{
153 154 155 156 157 158 159
    if(getSuccessfulConnected()) {
        if ( _seconds >= 0.0f ) {
            mORSensorFusion->SetPrediction( _seconds );
        } else {
            mORSensorFusion->SetPrediction( 0.0f, false );
        }
        mPredictionTime = _seconds;
Robert Menzel's avatar
Robert Menzel committed
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
    }
}

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;
185
    mCamera->setInterpupillaryDistance( mORHMDInfo->InterpupillaryDistance );
Robert Menzel's avatar
Robert Menzel committed
186 187
    updateCameraFoV();

188 189 190
    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
191 192 193 194 195 196 197 198 199 200 201
    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) {
202
        q = mORSensorFusion->GetPredictedOrientation();
Robert Menzel's avatar
Robert Menzel committed
203
    } else {
204
        q = mORSensorFusion->GetOrientation();
Robert Menzel's avatar
Robert Menzel committed
205 206 207 208 209 210 211 212
    }

    q.Normalize();

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

    q = mInverseNeutralRotation * q;

213
    if (mORSensorFusion->IsYawCorrectionEnabled()) {
Robert Menzel's avatar
Robert Menzel committed
214 215 216 217 218 219 220 221 222
        //debug() << "yaw corrected" << endl;
    }

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

void SimpleRiftController::setNeutralPosition()
{
223
    mInverseNeutralRotation = mORSensorFusion->GetOrientation();
Robert Menzel's avatar
Robert Menzel committed
224 225 226 227 228 229 230 231 232
    mInverseNeutralRotation.Normalize();
    mInverseNeutralRotation.x *= -1.0;
    mInverseNeutralRotation.y *= -1.0;
    mInverseNeutralRotation.z *= -1.0;
}

void SimpleRiftController::setNeutralYaw()
{
    mInverseNeutralRotation = OVR::Quatf();
233
    mORSensorFusion->Reset();
Robert Menzel's avatar
Robert Menzel committed
234 235 236 237 238 239 240 241 242 243 244
}

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

    mCamera->setHMDRotation( getCurrentRotation() );
}

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

249 250 251 252
    vfov *= mFoVMultiplier;
    if (vfov <    5.0f) vfov =   5.0f;
    if (vfov >= 175.0f) vfov = 175.0f;

Robert Menzel's avatar
Robert Menzel committed
253
    mCamera->setVerticalFieldOfView( vfov );
254
    //debug() << "update VFoV: " << vfov << endl;
Robert Menzel's avatar
Robert Menzel committed
255 256 257 258
}

glm::uvec2 SimpleRiftController::getPhysicalScreenResolution()
{
259
    return glm::uvec2( mORHMDInfo->HResolution, mORHMDInfo->VResolution );
Robert Menzel's avatar
Robert Menzel committed
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
}

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;

294 295 296
    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
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 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
    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;
350 351 352 353
    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
354 355 356 357 358 359
    return distortionK;
}

glm::vec4 SimpleRiftController::getChromAbParam()
{
    glm::vec4 chromaK;
360 361 362 363
    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
364 365 366 367 368
    return chromaK;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
Robert Menzel's avatar
Robert Menzel committed
369
// optional rendering nuild-in shaders:
Robert Menzel's avatar
Robert Menzel committed
370 371 372
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Robert Menzel's avatar
Robert Menzel committed
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 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
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\
501
            vec2  theta = (position - LensCenter) * ScaleIn; // Scales to [-1, 1]\n\
Robert Menzel's avatar
Robert Menzel committed
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 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
        \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\
";
571

Robert Menzel's avatar
Robert Menzel committed
572 573 574 575 576
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// optional rendering:
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
577

Robert Menzel's avatar
Robert Menzel committed
578 579 580 581 582 583
void SimpleRiftController::renderDistorted( OpenGL::ConstSharedTexture2D _sideBySideTexture )
{
    if (!mDistortShaderSideBySide) {
        // initialize shaders:
        mDistortShaderSideBySide = OpenGL::ShaderProgramFileManager::the()->get( OpenGL::ShaderProgramCreator("RiftDistortSideBySide.fsh").andFile("RiftDistort.vsh") );
        if (!mDistortShaderSideBySide) {
584 585 586 587 588 589 590 591 592 593 594 595 596
            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
597
            mDistortShaderSideBySide->use();
Robert Menzel's avatar
Robert Menzel committed
598 599 600 601 602 603 604 605 606 607 608 609 610 611


            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
612
            mDistortShaderTwoTextures->setUniform(uScale,        getScale() );
Robert Menzel's avatar
Robert Menzel committed
613 614
            mDistortShaderTwoTextures->setUniform(uHmdWarpParam, getHmdWarpParam() );
            mDistortShaderTwoTextures->setUniform(uChromAbParam, getChromAbParam() );
615 616
        } else {
            ACGL::Utils::debug() << "SimpleRiftController: using application provided shaders" << std::endl;
Robert Menzel's avatar
Robert Menzel committed
617
            mBuildInShader = false;
Robert Menzel's avatar
Robert Menzel committed
618 619 620 621 622 623 624 625 626 627 628 629 630 631
        }
    }

    mDistortShaderSideBySide->use();
    mDistortShaderSideBySide->setTexture("uSamplerColor", _sideBySideTexture, 0 );
    renderDistorted( mDistortShaderSideBySide );
}

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) {
632 633 634 635 636 637 638 639 640 641 642 643 644
            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
645 646 647 648 649 650 651 652 653 654 655 656 657 658
            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
659
            mDistortShaderTwoTextures->setUniform(uScale,        getScale() );
Robert Menzel's avatar
Robert Menzel committed
660 661
            mDistortShaderTwoTextures->setUniform(uHmdWarpParam, getHmdWarpParam() );
            mDistortShaderTwoTextures->setUniform(uChromAbParam, getChromAbParam() );
662 663 664

        } else {
            ACGL::Utils::debug() << "SimpleRiftController: using application provided shaders" << std::endl;
Robert Menzel's avatar
Robert Menzel committed
665
            mBuildInShader = false;
Robert Menzel's avatar
Robert Menzel committed
666 667 668 669 670 671
        }
    }

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

Robert Menzel's avatar
Robert Menzel committed
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
    renderDistorted( mDistortShaderTwoTextures );
}

void SimpleRiftController::renderDistorted( ACGL::OpenGL::ConstSharedShaderProgram _program )
{
    // 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
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704

    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
705 706 707

    // attribute-less rendering:
    // just rendering a fullscreen quad
Robert Menzel's avatar
Robert Menzel committed
708 709 710 711
    if (!mVAO) {
        mVAO = SharedVertexArrayObject( new VertexArrayObject() );
    }
    mVAO->bind(); // 'empty' VAO -> no attributes are defined
Robert Menzel's avatar
Robert Menzel committed
712 713 714 715
    glDrawArrays( GL_TRIANGLE_STRIP, 0, 4 ); // create 2 triangles with no attributes
}

#endif