void OculusWorldDemoApp::OnIdle() { double curtime = pPlatform->GetAppTime(); float dt = float(curtime - LastUpdate); LastUpdate = curtime; if (LoadingState == LoadingState_DoLoad) { LoadingState = LoadingState_Finished; return; } // If one of Stereo setting adjustment keys is pressed, adjust related state. if (pAdjustFunc) { (this->*pAdjustFunc)(dt * AdjustDirection * (ShiftDown ? 5.0f : 1.0f)); } // Rotate and position View Camera, using YawPitchRoll in BodyFrame coordinates. // Matrix4f rollPitchYaw = Matrix4f::RotationY(0) * Matrix4f::RotationX(0) * Matrix4f::RotationZ(0); // YAW PITCH ROLL const Vector3f UpVector(0.0f, 1.0f, 0.0f); const Vector3f ForwardVector(0.0f, 0.0f, -1.0f); Vector3f up = rollPitchYaw.Transform(UpVector); Vector3f forward = rollPitchYaw.Transform(ForwardVector); // Minimal head modeling; should be moved as an option to SensorFusion. float headBaseToEyeHeight = 0.15f; // Vertical height of eye from base of head float headBaseToEyeProtrusion = 0.09f; // Distance forward of eye from base of head Vector3f eyeCenterInHeadFrame(0.0f, headBaseToEyeHeight, -headBaseToEyeProtrusion); Vector3f shiftedEyePos = rollPitchYaw.Transform(eyeCenterInHeadFrame); shiftedEyePos.y -= eyeCenterInHeadFrame.y; // Bring the head back down to original height View = Matrix4f::LookAtRH(shiftedEyePos, shiftedEyePos + forward, up); // Transformation without head modeling. // View = Matrix4f::LookAtRH(EyePos, EyePos + forward, up); // This is an alternative to LookAtRH: // Here we transpose the rotation matrix to get its inverse. // View = (Matrix4f::RotationY(EyeYaw) * Matrix4f::RotationX(EyePitch) * // Matrix4f::RotationZ(EyeRoll)).Transposed() * // Matrix4f::Translation(-EyePos); //case Stereo_LeftDouble_Multipass: Render(SConfig.GetEyeRenderParams(StereoEye_Left)); Render(SConfig.GetEyeRenderParams(StereoEye_Right)); pRender->Present(); // Force GPU to flush the scene, resulting in the lowest possible latency. pRender->ForceFlushGPU(); }
// Fallback monitor enumeration in case newly plugged in monitor wasn't detected. // Added originally for the FactoryTest app. // New Outputs don't seem to be detected unless adapter is re-created, but that would also // require us to re-initialize D3D11 (recreating objects, etc). This bypasses that for "fake" // fullscreen modes. BOOL CALLBACK MonitorEnumFunc(HMONITOR hMonitor, HDC, LPRECT, LPARAM dwData) { RenderDevice* renderer = (RenderDevice*)dwData; MONITORINFOEX monitor; monitor.cbSize = sizeof(monitor); if (::GetMonitorInfo(hMonitor, &monitor) && monitor.szDevice[0]) { DISPLAY_DEVICE dispDev; memset(&dispDev, 0, sizeof(dispDev)); dispDev.cb = sizeof(dispDev); if (::EnumDisplayDevices(monitor.szDevice, 0, &dispDev, 0)) { if (strstr(String(dispDev.DeviceName).ToCStr(), renderer->GetParams().MonitorName.ToCStr())) { renderer->FSDesktopX = monitor.rcMonitor.left; renderer->FSDesktopY = monitor.rcMonitor.top; return FALSE; } } } return TRUE; }
// Helper function static shared_ptr<UniversalMaterial> getSonicSculptureMaterial(int index) { shared_ptr<Texture> lambertianTex = Texture::createEmpty(format("Sonic Sculpture %d", index), 512, 1, ImageFormat::RGBA16F()); static shared_ptr<Framebuffer> fb = Framebuffer::create("Sonic Sculpture Lambertian FB Clearer"); fb->set(Framebuffer::COLOR0, lambertianTex); RenderDevice* rd = RenderDevice::current; rd->push2D(fb); { rd->setColorClearValue(Color3::white() * 0.9f); rd->clear(); } rd->pop2D(); lambertianTex->generateMipMaps(); UniversalMaterial::Specification spec; spec.setLambertian(lambertianTex); static uint32 dummyBytes[512]; for (int i = 0; i < 512; ++i) { dummyBytes[i] = 4294967295; } shared_ptr<Texture> emissiveTex = Texture::fromMemory(format("Sonic Sculpture %d Emissive", index), dummyBytes, ImageFormat::RGBA8(), 512, 1, 1, 1, ImageFormat::RGBA16F()); fb->set(Framebuffer::COLOR0, emissiveTex); rd->push2D(fb); { rd->setColorClearValue(Color3::black()); rd->clear(); } rd->pop2D(); emissiveTex->generateMipMaps(); spec.setEmissive(emissiveTex); //spec.setBump(System::findDataFile("material/10538-bump.jpg")); return UniversalMaterial::create(spec); }
// Implement static initializer function to create this class. RenderDevice* RenderDevice::CreateDevice(const RendererParams& rp, void* oswnd) { RenderDevice* p = new RenderDevice(rp, (HWND)oswnd); if (p) { if (!p->Device) { p->Release(); p = 0; } } return p; }
void App::handlePlayPulses() { for (int i = m_currentPlayPulses.size() - 1; i >= 0; --i) { int currentSampleIndex = (g_sampleWindowIndex * g_currentAudioBuffer.size()); shared_ptr<SonicSculpturePiece> piece = m_currentPlayPulses[i].piece; int endIndex = m_currentPlayPulses[i].initialSample + (piece->size() * g_currentAudioBuffer.size()); RenderDevice* rd = RenderDevice::current; static shared_ptr<Framebuffer> playPulseFB = Framebuffer::create("Play Pulse FB"); shared_ptr<UniversalMaterial> material = piece->material(); if (currentSampleIndex >= endIndex) { playPulseFB->set(Framebuffer::COLOR0, material->emissive().texture()); rd->push2D(playPulseFB); { rd->setColorClearValue(Color3::black()); rd->clear(); } rd->pop2D(); material->emissive().texture()->generateMipMaps(); m_currentPlayPulses.remove(i); continue; } float alpha = float(currentSampleIndex - m_currentPlayPulses[i].initialSample) / (endIndex - m_currentPlayPulses[i].initialSample); playPulseFB->set(Framebuffer::COLOR0, material->emissive().texture()); rd->push2D(playPulseFB); { Args args; args.setUniform("pulsePos", alpha * playPulseFB->width()); args.setRect(rd->viewport()); LAUNCH_SHADER("playPulse.pix", args); } rd->pop2D(); material->emissive().texture()->generateMipMaps(); } }
//----------------------------------------------------------------------------- void OculusWorldDemoApp::CycleDisplay() { int screenCount = pPlatform->GetDisplayCount(); // If Windowed, switch to the HMD screen first in Full-Screen Mode. // If already Full-Screen, cycle to next screen until we reach FirstScreenInCycle. if (pRender->IsFullscreen()) { // Right now, we always need to restore window before going to next screen. pPlatform->SetFullscreen(RenderParams, Display_Window); Screen++; if (Screen == screenCount) Screen = 0; RenderParams.Display = pPlatform->GetDisplay(Screen); if (Screen != FirstScreenInCycle) { pRender->SetParams(RenderParams); pPlatform->SetFullscreen(RenderParams, Display_Fullscreen); } } else { // Try to find HMD Screen, making it the first screen in full-screen Cycle. FirstScreenInCycle = 0; if (pHMD) { DisplayId HMD (SConfig.GetHMDInfo().DisplayDeviceName, SConfig.GetHMDInfo().DisplayId); for (int i = 0; i< screenCount; i++) { if (pPlatform->GetDisplay(i) == HMD) { FirstScreenInCycle = i; break; } } } // Switch full-screen on the HMD. Screen = FirstScreenInCycle; RenderParams.Display = pPlatform->GetDisplay(Screen); pRender->SetParams(RenderParams); pPlatform->SetFullscreen(RenderParams, Display_Fullscreen); } }
void Camera::render( RenderBlock& block, bool clearView ) { if (!activeView) return; RenderDevice* renderDevice = GetRenderDevice(); renderDevice->setActiveView( activeView ); if (clearView) renderDevice->clearView(); for (auto it= drawer.renderables.end() -1;it >= drawer.renderables.begin();--it) block.renderables.Insert(block.renderables.begin(), *it); renderDevice->render( block ); }
void D3DTexture::Init(const std::string& imagePath, RenderDevice& device) { concurrency::create_async([&]() { CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; { std::lock_guard<std::recursive_mutex> lock(mMutex); ThrowIfFailed(DirectX::CreateWICTextureFromFile(mDevice, mContext, converter.from_bytes(imagePath).c_str(), nullptr, &mColorTexture), "CreateWICTextureFromFile() failed."); } // Create a texture sampler D3D11_SAMPLER_DESC samplerDesc; ZeroMemory(&samplerDesc, sizeof(samplerDesc)); samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; { std::lock_guard<std::recursive_mutex> lock(mMutex); ThrowIfFailed(mDevice->CreateSamplerState(&samplerDesc, &mColorSampler), "ID3D11Device::CreateSamplerState() failed."); } device.ResourceLoaded(); }); }
void Camera::render( RenderBlock& block, bool clearView ) { if( !activeView ) return; RenderDevice* renderDevice = GetRenderDevice(); renderDevice->setActiveView( activeView ); if( clearView ) renderDevice->clearView(); block.renderables.insert( block.renderables.begin(), drawer.renderables.begin(), drawer.renderables.end() ); renderDevice->render( block ); }
/** * Render this component */ void RenderComponent::Render(const RenderDevice& device) { // Set the texture resource device.GetImmediateContext()->PSSetShaderResources(0, 1, &_texture); // Set the vertex buffer _mesh->Render(device); }
// Called before the application loop begins. Load data here and // not in the constructor so that common exceptions will be // automatically caught. void App::onInit() { RenderDevice* rd = renderDevice; Vector2 destSize(1024, 1024); const Rect2D& dest = Rect2D::xywh(Vector2(0, 0), destSize); Args args; // args.appendToPreamble("#define KERNEL_RADIUS 9\nfloat gaussCoef[KERNEL_RADIUS] = float[KERNEL_RADIUS](0.00194372, 0.00535662, 0.01289581, 0.02712094, 0.04982645, 0.07996757, 0.11211578, 0.13731514, 0.14691596);"); rd->push2D(dest); { args.setRect(dest); LAUNCH_SHADER("apply.*", args); } rd->pop2D(); // Or Equivalently: //GaussianBlur::apply(renderDevice, Texture::createEmpty("test",1024,1024)); }
/** * Initialize the input layout given the current description * @param * const RenderDevice& The render device used to create * @param * ID3D10Blob* The target shader for this input layout * @return * bool Returns true if successful */ bool InputLayout::Initialize(const RenderDevice& device, ID3D10Blob* targetShader) { // Get the layout description D3D11_INPUT_ELEMENT_DESC* layoutDescription = GetInputLayoutDesc(); // Initialize the layout HRESULT result = device.GetD3DDevice()->CreateInputLayout(layoutDescription, _parameters.size(), targetShader->GetBufferPointer(), targetShader->GetBufferSize(), &_inputLayout); return SUCCEEDED(result); }
RenderTarget::~RenderTarget() { if( !context ) return; RenderDevice* renderDevice = GetRenderDevice(); if( renderDevice->getActiveContext() == context ) { // Remove the context from the render device. renderDevice->setActiveContext(nullptr); } for(size_t i = 0; i < views.size(); ++i) { RenderView* view = views[i]; Deallocate(view); } }
void RenderTarget::removeViews() { RenderDevice* renderDevice = GetRenderDevice(); for( size_t i = 0; i < views.size(); i++ ) { RenderView* view = views[i]; if( renderDevice->getActiveView() == view ) { // Remove the active view from the render device. renderDevice->setActiveView(nullptr); } Deallocate(view); } views.clear(); }
void ModelContainerView::doGraphics() { i_App->renderDevice->clear(); RenderDevice *rd = i_App->renderDevice; rd->setProjectionAndCameraMatrix(i_App->debugCamera); LightingParameters lighting(GameTime(toSeconds(10, 00, AM))); //i_SkyRef->render(rd,lighting); rd->setAmbientLightColor(Color4(Color3::blue())); rd->enableLighting(); GLight light =GLight::directional(i_App->debugController.getPosition() + i_App->debugController.getLookVector()*2,Color3::white()); rd->setLight(0,light); Array<std::string > keys = iTriVarTable.getKeys(); Array<std::string>::ConstIterator i = keys.begin(); while(i != keys.end()) { VAR* var = iTriVarTable.get(*i); Array<int> indexArray = iTriIndexTable.get(*i); rd->beginIndexedPrimitives(); rd->setVertexArray(*var); rd->sendIndices(RenderDevice::LINES, indexArray); rd->endIndexedPrimitives(); ++i; } i_App->renderDevice->disableLighting(); for(int i=0; i<gBoxArray.size(); ++i) { AABox b = gBoxArray[i]; Draw::box(b,rd,Color3::red()); } if(iDrawLine) { Draw::lineSegment(LineSegment::fromTwoPoints(iPos1, iPos2), rd, iColor, 3); if(myfound) { Draw::lineSegment(LineSegment::fromTwoPoints(p1, p2), rd, iColor, 3); Draw::lineSegment(LineSegment::fromTwoPoints(p2, p3), rd, iColor, 3); Draw::lineSegment(LineSegment::fromTwoPoints(p3, p1), rd, iColor, 3); Draw::sphere(Sphere(p4,0.5),rd, iColor); Draw::sphere(Sphere(p5,0.5),rd, Color3::green()); } } }
void MatrixStack::Apply(RenderDevice& render_device) { if(_state_dirty) { State& current_state = _states.top(); render_device.SetUniformMatrix4f("view_matrix", current_state.view_matrix); // model_view = view * model Mat4x4 model_view = matrix::Multiply(current_state.view_matrix, current_state.model_matrix); render_device.SetUniformMatrix4f("model_view_matrix", model_view); // Build our model view projection matrix // model_view_projection = projection * view * model Mat4x4 model_view_projection = matrix::Multiply(current_state.projection_matrix, model_view); render_device.SetUniformMatrix4f("model_view_projection_matrix", model_view_projection); _state_dirty = false; } }
void Render() { RenderDevice* device = Environment::GetSingleton().GetRenderDevice(); SceneManager* sceneMan = Environment::GetSingleton().GetSceneManager(); device->GetScreenFrameBuffer()->Clear(CF_Color | CF_Depth, ColorRGBA::White, 1, 0); float w = static_cast<float>( mMainWindow->GetWidth() ); float h = static_cast<float>( mMainWindow->GetHeight() ); mTessEffect->GetParameterByName("ViewportDim")->SetValue(float2(w, h)); //device->Draw(mBezierCurveEffect->GetTechniqueByName("BezierCurve"), mBezierCurveROP); device->Draw(mTessEffect->GetTechniqueByName("TessQuad"), mTessQuadROP); /*float4x4 world = CreateScaling(5, 5, 5) * CreateTranslation(0, 0, 60); mTessEffect->GetParameterByName("TessLevel")->SetValue(100); mTessEffect->GetParameterByName("World")->SetValue(world); mTessEffect->GetParameterByName("ViewProj")->SetValue(mCamera->GetEngineViewProjMatrix()); device->Draw(mTessEffect->GetTechniqueByName("TessTeapot"), mTessTeapotROP);*/ device->GetScreenFrameBuffer()->SwapBuffers(); }
void InputTestApp::OnIdle() { double curtime = pPlatform->GetAppTime(); // float dt = float(LastUpdate - curtime); LastUpdate = curtime; if (pBox) { Quatf q = SFusion.GetOrientation(); pBox->SetOrientation(q); // Test Euler conversion, alternative to the above: // Vector3f euler; // SFusion.GetOrientation().GetEulerABC<Axis_Y, Axis_X, Axis_Z, Rotate_CCW, Handed_R>(&euler.y, &euler.x, &euler.z); // Matrix4f mat = Matrix4f::RotationY(euler.y) * Matrix4f::RotationX(euler.x) * Matrix4f::RotationZ(euler.z); // pBox->SetMatrix(mat); // Update titlebar every 20th of a second. if ((curtime - LastTitleUpdate) > 0.05f) { char titleBuffer[512]; SensorDevice::CoordinateFrame coord = SensorDevice::Coord_Sensor; if (pSensor) coord = pSensor->GetCoordinateFrame(); OVR_sprintf(titleBuffer, 512, "OVR SensorBox %s %s Ang: %0.3f", (SFusion.IsGravityEnabled() ? "" : "[Grav Off]"), (coord == SensorDevice::Coord_HMD) ? "[HMD Coord]" : "", CalcDownAngleDegrees(q)); pPlatform->SetWindowTitle(titleBuffer); LastTitleUpdate = curtime; } } if (pBox2) { pBox2->SetOrientation(SFusion2.GetOrientation()); } // Render int w, h; pPlatform->GetWindowSize(&w, &h); pRender->SetViewport(0, 0, w, h); pRender->Clear(); pRender->BeginScene(); pRender->SetProjection(Proj); pRender->SetDepthMode(1,1); Sc.Render(pRender, View); pRender->Present(); }
int main(int argc, char** argv) { RenderDevice* rd = new RenderDevice(); OSWindow::Settings settings; settings.width = 960; settings.height = 600; rd->init(settings); for (int i = 0; i < 100; ++i) { drawFrame(settings.width, settings.height, i); // Render at 30 fps System::sleep(1.0/30.0); // See also RenderDevice::beginFrame, RenderDevice::endFrame rd->swapBuffers(); } rd->cleanup(); delete rd; return 0; }
void InputTestApp::OnIdle() { double curtime = pPlatform->GetAppTime(); time_t t = time(0); // get time now struct tm * now = localtime(&t); // float dt = float(LastUpdate - curtime); LastUpdate = curtime; if (pBox) { Vector3f acceldata = SFusion.GetAcceleration(); Vector3f gyrodata = SFusion.GetAngularVelocity(); Vector3f magdata = SFusion.GetMagnetometer(); Quatf q = SFusion.GetOrientation(); pBox->SetOrientation(q); //fstream outFile; //outFile.open("C://Users//Barrett//Documents//oculus_sensor_data.txt"); // Output the sensor data to the text file ofstream outFile("C://Users//Barrett//Documents//oculus_sensor_data.csv", ios::app); outFile << \ now->tm_sec << "," << \ curtime << "," << \ acceldata.x << "," << acceldata.y << "," << acceldata.z << "," << \ gyrodata.x << "," << gyrodata.y << "," << gyrodata.z << "," << \ magdata.x << "," << magdata.y << "," << magdata.z << "," << \ q.x << "," << q.y << "," << q.z << q.w << "\n"; // Test Euler conversion, alternative to the above: // Vector3f euler; // SFusion.GetOrientation().GetEulerABC<Axis_Y, Axis_X, Axis_Z, Rotate_CCW, Handed_R>(&euler.y, &euler.x, &euler.z); // Matrix4f mat = Matrix4f::RotationY(euler.y) * Matrix4f::RotationX(euler.x) * Matrix4f::RotationZ(euler.z); // pBox->SetMatrix(mat); // Update titlebar every 20th of a second. if ((curtime - LastTitleUpdate) > 0.05f) { char titleBuffer[512]; SensorDevice::CoordinateFrame coord = SensorDevice::Coord_Sensor; if (pSensor) coord = pSensor->GetCoordinateFrame(); OVR_sprintf(titleBuffer, 512, "OVR SensorBox %s %s Ang: %0.3f", (SFusion.IsGravityEnabled() ? "" : "[Grav Off]"), (coord == SensorDevice::Coord_HMD) ? "[HMD Coord]" : "", CalcDownAngleDegrees(q)); pPlatform->SetWindowTitle(titleBuffer); LastTitleUpdate = curtime; } } if (pBox2) { pBox2->SetOrientation(SFusion2.GetOrientation()); } // Render int w, h; pPlatform->GetWindowSize(&w, &h); pRender->SetViewport(0, 0, w, h); pRender->Clear(); pRender->BeginScene(); pRender->SetProjection(Proj); pRender->SetDepthMode(1,1); Sc.Render(pRender, View); pRender->Present(); }
int OculusWorldDemoApp::OnStartup(int argc, const char** argv) { // *** Oculus HMD & Sensor Initialization // Create DeviceManager and first available HMDDevice from it. // Sensor object is created from the HMD, to ensure that it is on the // correct device. pManager = *DeviceManager::Create(); pHMD = *pManager->EnumerateDevices<HMDDevice>().CreateDevice(); if (pHMD) { pSensor = *pHMD->GetSensor(); // This will initialize HMDInfo with information about configured IPD, // screen size and other variables needed for correct projection. // We pass HMD DisplayDeviceName into the renderer to select the // correct monitor in full-screen mode. if(pHMD->GetDeviceInfo(&TheHMDInfo)) { //RenderParams.MonitorName = hmd.DisplayDeviceName; SConfig.SetHMDInfo(TheHMDInfo); } // Retrieve relevant profile settings. } else { // If we didn't detect an HMD, try to create the sensor directly. // This is useful for debugging sensor interaction; it is not needed in // a shipping app. pSensor = *pManager->EnumerateDevices<SensorDevice>().CreateDevice(); } // Make the user aware which devices are present. if(pHMD == NULL && pSensor == NULL) { SetAdjustMessage("---------------------------------\nNO HMD DETECTED\nNO SENSOR DETECTED\n---------------------------------"); } else if(pHMD == NULL) { SetAdjustMessage("----------------------------\nNO HMD DETECTED\n----------------------------"); } else { SetAdjustMessage("--------------------------------------------\n" "Press F9 for Full-Screen on Rift\n" "--------------------------------------------"); } // First message should be extra-long. SetAdjustMessageTimeout(10.0f); if(TheHMDInfo.HResolution > 0) { Width = TheHMDInfo.HResolution; Height = TheHMDInfo.VResolution; } if(!pPlatform->SetupWindow(Width, Height)) { return 1; } String Title = "Remote Eyes"; if(TheHMDInfo.ProductName[0]) { Title += " : "; Title += TheHMDInfo.ProductName; } pPlatform->SetWindowTitle(Title); // *** Initialize Rendering const char* graphics = "d3d11"; // Select renderer based on command line arguments. for(int i = 1; i < argc; i++) { if(!strcmp(argv[i], "-r") && i < argc - 1) { graphics = argv[i + 1]; } else if(!strcmp(argv[i], "-fs")) { RenderParams.Fullscreen = true; } } // Enable multi-sampling by default. RenderParams.Multisample = 4; pRender = pPlatform->SetupGraphics(OVR_DEFAULT_RENDER_DEVICE_SET, graphics, RenderParams); // *** Configure Stereo settings. SConfig.SetFullViewport(Viewport(0, 0, Width, Height)); SConfig.SetStereoMode(Stereo_LeftRight_Multipass); // Configure proper Distortion Fit. // For 7" screen, fit to touch left side of the view, leaving a bit of // invisible screen on the top (saves on rendering cost). // For smaller screens (5.5"), fit to the top. if (TheHMDInfo.HScreenSize > 0.0f) { if (TheHMDInfo.HScreenSize > 0.140f) // 7" SConfig.SetDistortionFitPointVP(-1.0f, 0.0f); else SConfig.SetDistortionFitPointVP(0.0f, 1.0f); } pRender->SetSceneRenderScale(SConfig.GetDistortionScale()); //pRender->SetSceneRenderScale(1.0f); SConfig.Set2DAreaFov(DegreeToRad(85.0f)); // Setup frame reader from shared memory pRead = new Read("../../caminfo.log"); return 0; }
void OculusWorldDemoApp::OnKey(OVR::KeyCode key, int chr, bool down, int modifiers) { OVR_UNUSED(chr); switch(key) { case Key_Q: if (down && (modifiers & Mod_Control)) { pPlatform->Exit(0); } break; case Key_B: if (down) { if(SConfig.GetDistortionScale() == 1.0f) { if(SConfig.GetHMDInfo().HScreenSize > 0.140f) // 7" { SConfig.SetDistortionFitPointVP(-1.0f, 0.0f); } else { SConfig.SetDistortionFitPointVP(0.0f, 1.0f); } } else { // No fitting; scale == 1.0. SConfig.SetDistortionFitPointVP(0, 0); } } break; // Support toggling background color for distortion so that we can see // the effect on the periphery. case Key_V: if (down) { if(DistortionClearColor.B == 0) { DistortionClearColor = Color(0, 128, 255); } else { DistortionClearColor = Color(0, 0, 0); } pRender->SetDistortionClearColor(DistortionClearColor); } break; case Key_F1: SConfig.SetStereoMode(Stereo_None); PostProcess = PostProcess_None; SetAdjustMessage("StereoMode: None"); break; case Key_F2: SConfig.SetStereoMode(Stereo_LeftRight_Multipass); PostProcess = PostProcess_None; SetAdjustMessage("StereoMode: Stereo + No Distortion"); break; case Key_F3: SConfig.SetStereoMode(Stereo_LeftRight_Multipass); PostProcess = PostProcess_Distortion; SetAdjustMessage("StereoMode: Stereo + Distortion"); break; // Stereo adjustments. case Key_BracketLeft: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustFov : 0; AdjustDirection = 1; break; case Key_BracketRight: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustFov : 0; AdjustDirection = -1; break; case Key_Insert: case Key_Num0: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustIPD : 0; AdjustDirection = 1; break; case Key_Delete: case Key_Num9: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustIPD : 0; AdjustDirection = -1; break; case Key_Home: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustPS : 0; AdjustDirection = 1; break; case Key_End: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustPS : 0; AdjustDirection = -1; break; case Key_PageUp: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustAspect : 0; AdjustDirection = 1; break; case Key_PageDown: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustAspect : 0; AdjustDirection = -1; break; // Distortion correction adjustments case Key_H: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK0 : NULL; AdjustDirection = -1; break; case Key_Y: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK0 : NULL; AdjustDirection = 1; break; case Key_J: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK1 : NULL; AdjustDirection = -1; break; case Key_U: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK1 : NULL; AdjustDirection = 1; break; case Key_K: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK2 : NULL; AdjustDirection = -1; break; case Key_I: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK2 : NULL; AdjustDirection = 1; break; case Key_L: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK3 : NULL; AdjustDirection = -1; break; case Key_O: pAdjustFunc = down ? &OculusWorldDemoApp::AdjustDistortionK3 : NULL; AdjustDirection = 1; break; case Key_C: if (down) { // Toggle chromatic aberration correction on/off. RenderDevice::PostProcessShader shader = pRender->GetPostProcessShader(); if (shader == RenderDevice::PostProcessShader_Distortion) { pRender->SetPostProcessShader(RenderDevice::PostProcessShader_DistortionAndChromAb); SetAdjustMessage("Chromatic Aberration Correction On"); } else if (shader == RenderDevice::PostProcessShader_DistortionAndChromAb) { pRender->SetPostProcessShader(RenderDevice::PostProcessShader_Distortion); SetAdjustMessage("Chromatic Aberration Correction Off"); } else OVR_ASSERT(false); } break; case Key_F9: #ifndef OVR_OS_LINUX // On Linux F9 does the same as F11. if (!down) { CycleDisplay(); } break; #endif #ifdef OVR_OS_MAC case Key_F10: // F11 is reserved on Mac #else case Key_F11: #endif if (!down) { RenderParams = pRender->GetParams(); RenderParams.Display = DisplayId(SConfig.GetHMDInfo().DisplayDeviceName,SConfig.GetHMDInfo().DisplayId); pRender->SetParams(RenderParams); pPlatform->SetMouseMode(Mouse_Normal); pPlatform->SetFullscreen(RenderParams, pRender->IsFullscreen() ? Display_Window : Display_FakeFullscreen); pPlatform->SetMouseMode(Mouse_Relative); // Avoid mode world rotation jump. // If using an HMD, enable post-process (for distortion) and stereo. if(RenderParams.IsDisplaySet() && pRender->IsFullscreen()) { SConfig.SetStereoMode(Stereo_LeftRight_Multipass); PostProcess = PostProcess_Distortion; } } break; default: break; } }
void OculusWorldDemoApp::Render(const StereoEyeParams& stereo) { if(stereo.Eye == StereoEye_Left) { GrabFrame(); } pRender->BeginScene(PostProcess); // *** 3D - Configures Viewport/Projection and Render pRender->ApplyStereoParams(stereo); pRender->Clear(); pRender->SetDepthMode(true, true); MainScene.Render(pRender, stereo.ViewAdjust * View); // *** 2D Text & Grid - Configure Orthographic rendering. // Render UI in 2D orthographic coordinate system that maps [-1,1] range // to a readable FOV area centered at your eye and properly adjusted. pRender->ApplyStereoParams2D(stereo); pRender->SetDepthMode(false, false); float unitPixel = SConfig.Get2DUnitPixel(); float textHeight= unitPixel * 22; // Display Loading screen-shot in frame 0. if (LoadingState != LoadingState_Finished) { LoadingScene.Render(pRender, Matrix4f()); String loadMessage = String("Loading...."); DrawTextBox(pRender, 0.0f, 0.0f, textHeight, loadMessage.ToCStr(), DrawText_HCenter); LoadingState = LoadingState_DoLoad; } cv::Size size = lastFrame->size(); char * imageData = (char *)malloc(size.width * size.height * 4); int pointer = 0; int c = 0; while(c < size.width * size.height * 3) { imageData[pointer++] = lastFrame->data[(c++)+2]; imageData[pointer++] = lastFrame->data[c++]; imageData[pointer++] = lastFrame->data[(c++)-2]; imageData[pointer++] = 0xFF; } Texture* tex = pRender->CreateTexture(Texture_RGBA, size.width, size.height, imageData, 1); ShaderFill* image = (ShaderFill*)pRender->CreateTextureFill(tex, false); // Left, top, right, bottom, image, alpha pRender->RenderImage(pictureSize, pictureSize, -pictureSize, -pictureSize, image, 255); delete image; delete tex; free(imageData); if(!AdjustMessage.IsEmpty() && AdjustMessageTimeout > pPlatform->GetAppTime()) { DrawTextBox(pRender,0.0f,0.4f, textHeight, AdjustMessage.ToCStr(), DrawText_HCenter); } switch(TextScreen) { case Text_Config: { char textBuff[2048]; OVR_sprintf(textBuff, sizeof(textBuff), "Fov\t300 %9.4f\n" "EyeDistance\t300 %9.4f\n" "DistortionK0\t300 %9.4f\n" "DistortionK1\t300 %9.4f\n" "DistortionK2\t300 %9.4f\n" "DistortionK3\t300 %9.4f\n" "TexScale\t300 %9.4f", SConfig.GetYFOVDegrees(), SConfig.GetIPD(), SConfig.GetDistortionK(0), SConfig.GetDistortionK(1), SConfig.GetDistortionK(2), SConfig.GetDistortionK(3), SConfig.GetDistortionScale()); DrawTextBox(pRender, 0.0f, 0.0f, textHeight, textBuff, DrawText_Center); } break; default: break; } pRender->FinishScene(); }
void Render() { RenderDevice* device = Environment::GetSingleton().GetRenderDevice(); SceneManager* sceneMan = Environment::GetSingleton().GetSceneManager(); shared_ptr<FrameBuffer> screenFB = device->GetScreenFrameBuffer(); device->BindFrameBuffer(screenFB); screenFB->Clear(CF_Color | CF_Depth, ColorRGBA::White, 1.0, 0); mRenderPath->RenderScene(); auto center = mCamera->GetPosition() + mCamera->GetForward() * 200.0f; DebugDrawManager::GetSingleton().DrawSphere(center, 10.0f, ColorRGBA::Red, true); //const float3 Points[] = { // float3(1240, 50, -510), // float3(1240, 50, 610), // float3(-1350, 50, 610), // float3(-1350, 50, -510), // float3(750, 50, -120), // float3(750, 50, 230), // float3(-900, 50, 230), // float3(-900, 50, -100), //}; //for (int i = 0; i < ARRAY_SIZE(Points); ++i) // DebugDrawManager::GetSingleton().DrawSphere(Points[i], 10.0f, ColorRGBA::Red, true); //const int NumEllipses = 10; //const int NumLightsEllipse = 20; //for (int i = 0; i < NumEllipses; ++i) //{ // for (int j = 0; j < NumLightsEllipse; ++j) // { // float Height = Lerp(10.0f, 1200.0f, float(i) / NumEllipses); // float Angle = Mathf::TWO_PI / NumLightsEllipse * j; // float3 pos(950.0f * cosf(Angle), Height, 175.0f * sinf(Angle)); // DebugDrawManager::GetSingleton().DrawSphere(pos, 10.0f, ColorRGBA::Red, true); // } //} DebugDrawManager::GetSingleton().DrawSphere(float3(-1320, 160, 40), 150, ColorRGBA::Red, true); sceneMan->UpdateOverlayQueue(); RenderBucket& guiBucket =sceneMan->GetRenderQueue().GetRenderBucket(RenderQueue::BucketOverlay, false); for (const RenderQueueItem& renderItem : guiBucket) renderItem.Renderable->Render(); //auto bbox = mDudeSceneNode->GetWorldBoundingBox(); //DebugDrawManager::GetSingleton().DrawBoundingBox(bbox, ColorRGBA::Red); //shared_ptr<Skeleton> skeleton = mDudeEntity->GetSkeleton(); //DebugDrawManager::GetSingleton().DrawSkeleton(mDudeEntity->GetWorldTransform(), skeleton, ColorRGBA::Red); /*for (size_t i = 0; i < skeleton->GetNumBones(); ++i) { Bone* bone = skeleton->GetBone(i); float3 center = bone->GetWorldPosition(); center = Transform(center, mDudeEntity->GetWorldTransform()); ColorRGBA color = ColorRGBA::Red; DebugDrawManager::GetSingleton().DrawSphere(center, 0.5, color, true); }*/ //for (size_t i = 0; i < mDudeCollisionSpheres.size(); ++i) //{ // Bone* bone = skeleton->GetBone(mDudeCollisionSpheres[i].BoneName); // float3 center(mDudeCollisionSpheres[i].Offset, 0, 0); // center = Transform(center, bone->GetWorldTransform()); // center = bone->GetWorldPosition(); // DebugDrawManager::GetSingleton().DrawSphere(center, mDudeCollisionSpheres[i].Radius * 0.5, ColorRGBA::Red); //} screenFB->SwapBuffers(); }
int main(int argc, char* argv[]) { (void)argc; (void)argv; RenderDevice* renderDevice = NULL; NetworkDevice* networkDevice = new NetworkDevice(); if (networkDevice) {networkDevice->init();} std::string s; System::describeSystem(s); printf("%s\n", s.c_str()); if (networkDevice) { networkDevice->describeSystem(s); printf("%s\n", s.c_str()); } # ifndef _DEBUG printf("Performance analysis:\n\n"); perfCollisionDetection(); perfArray(); perfTable(); printf("%s\n", System::mallocPerformance().c_str()); perfQueue(); perfMatrix3(); perfTextOutput(); perfSystemMemcpy(); perfBinaryIO(); perfAABSPTree(); measureMemsetPerformance(); measureNormalizationPerformance(); GWindow::Settings settings; settings.width = 800; settings.height = 600; settings.alphaBits = 0; settings.rgbBits = 8; settings.stencilBits = 0; settings.fsaaSamples = 1; if (!renderDevice) { renderDevice = new RenderDevice(); } renderDevice->init(settings); if (renderDevice) { renderDevice->describeSystem(s); printf("%s\n", s.c_str()); } measureRDPushPopPerformance(renderDevice); getch(); # else printf("\n\nTests:\n\n"); testTable(); testCollisionDetection(); testCoordinateFrame(); testReliableConduit(networkDevice); testAABSPTree(); testQuat(); testReferenceCount(); testAtomicInt32(); testGThread(); testSystemMemset(); testSystemMemcpy(); testQueue(); // Don't run contrib tests until the new 7.00 build system is in place // testMatrix(); // testGChunk(); testArray(); testMeshAlgTangentSpace(); testConvexPolygon2D(); testPlane(); printf(" passed\n"); testAABox(); testRandom(); printf(" passed\n"); testAABoxCollision(); printf(" passed\n"); testAdjacency(); printf(" passed\n"); testWildcards(); printf(" passed\n"); testFloat(); printf(" passed\n"); testRandom(); testTextInput(); printf(" passed\n"); testBox(); printf(" passed\n"); testColor3uint8Array(); printf(" passed\n"); testglFormatOf(); printf(" passed\n"); testSwizzle(); testBinaryIO(); # ifdef RUN_SLOW_TESTS testHugeBinaryIO(); printf(" passed\n"); # endif printf("%s\n", System::mallocPerformance().c_str()); System::resetMallocPerformanceCounters(); printf("\nAll tests succeeded.\n"); #endif if (renderDevice) { renderDevice->cleanup(); delete renderDevice; } if (networkDevice) { networkDevice->cleanup(); delete networkDevice; } return 0; }
/// TODO: Output errors EffectPass::EffectPass(RenderDevice& device, ResourceManager& resources, const MaterialDescription& matDesc, const PassDescription& passDesc) : pipeline_(device.createPipelineState()) , constantUpdateInfoMap_() , textureUpdateInfoMap_() , samplerUpdateInfoMap_() , lightIteration_(passDesc.lightIteration) { std::unordered_map<std::shared_ptr<const BasicShader>, ShaderBoundDescription> eachShaders; for (const auto& ref : passDesc.shaderRef) { const auto& bound = matDesc.getShaderBound(ref.first, ref.second); if (ref.first == ShaderType::vertex) { const Resource<VertexShader> shader(resources, bound.path); pipeline_->setVShader(shader); eachShaders.emplace(shader.access(), bound); } else if (ref.first == ShaderType::pixel) { const Resource<PixelShader> shader(resources, bound.path); pipeline_->setPShader(shader); eachShaders.emplace(shader.access(), bound); } else if (ref.first == ShaderType::geometry) { const Resource<GeometryShader> shader(resources, bound.path); pipeline_->setGShader(shader); eachShaders.emplace(shader.access(), bound); } } pipeline_->setBlendState(0, passDesc.blendState); const auto resourceTable = pipeline_->getGpuResourceTable(); const auto numHeaps = resourceTable->getNumRequiredHeaps(); for (size_t i = 0; i < numHeaps; ++i) { const auto& requiredHeap = resourceTable->getRequiredHeap(i); const auto numResources = requiredHeap.getNumResources(); const auto heap = device.createGpuResourceHeap(numResources, requiredHeap.getType(), true); for (size_t j = 0; j < numResources; ++j) { const auto& requiredResource = requiredHeap.getResource(j); const auto& boundDesc = eachShaders[requiredResource.boundShader.lock()]; if (requiredResource.type == BoundResourceType::cbuffer) { const auto cbuffer = device.createConstantBuffer(requiredResource.cbuffer.getSize()); for (const auto& var : requiredResource.cbuffer.describeVariables()) { if (var.second.init) { cbuffer->update(var.second.init.get(), var.second.offset, var.second.size); } const auto it = boundDesc.constantMapping.find(var.first); if (it != std::cend(boundDesc.constantMapping)) { detail::ConstantUpdateInfo update; update.desc = var.second; update.dest = cbuffer; constantUpdateInfoMap_.emplace(it->second, std::move(update)); } } heap->locate(j, cbuffer); } else if (requiredResource.type == BoundResourceType::texture) { const auto it = boundDesc.textureMapping.find(requiredResource.texture.getName()); if (it != std::cend(boundDesc.textureMapping)) { detail::TextureUpdateInfo update; update.index = j; update.dest = heap; textureUpdateInfoMap_.emplace(it->second, std::move(update)); } } else if (requiredResource.type == BoundResourceType::sampler) { const auto it = boundDesc.samplerMapping.find(requiredResource.sampler.getName()); if (it != std::cend(boundDesc.samplerMapping)) { detail::SamplerUpdateInfo update; update.index = j; update.dest = heap; samplerUpdateInfoMap_.emplace(it->second, std::move(update)); } } } for (const auto rootIndex : requiredHeap.getRootIndices()) { resourceTable->set(rootIndex, heap); } } }
int main(int argc, char* argv[]) { (void)argc; (void)argv; # ifdef G3D_WINDOWS { // Change to the executable directory chdir(FilePath::parent(argv[0]).c_str()); } # endif char x[2000]; getcwd(x, sizeof(x)); debugAssertM(FileSystem::exists("apiTest.zip", false), format("Tests are being run from the wrong directory. cwd = %s", x)); RenderDevice* renderDevice = NULL; std::string s; System::describeSystem(s); printf("%s\n", s.c_str()); NetworkDevice::instance()->describeSystem(s); printf("%s\n", s.c_str()); # ifndef _DEBUG printf("Performance analysis:\n\n"); perfSystemMemcpy(); perfSystemMemset(); // Pause so that we can see the values in the debugger // getch(); printf("%s\n", System::mallocPerformance().c_str()); perfArray(); perfBinaryIO(); perfTable(); perfHashTrait(); perfKDTree(); perfCollisionDetection(); perfQueue(); perfMatrix3(); perfTextOutput(); perfPointHashGrid(); measureNormalizationPerformance(); OSWindow::Settings settings; settings.width = 800; settings.height = 600; settings.alphaBits = 0; settings.rgbBits = 8; settings.stencilBits = 0; settings.msaaSamples = 1; if (! renderDevice) { renderDevice = new RenderDevice(); } renderDevice->init(settings); if (renderDevice) { renderDevice->describeSystem(s); printf("%s\n", s.c_str()); } measureRDPushPopPerformance(renderDevice); # ifdef G3D_WIN32 // Pause so that we can see the values in the debugger // getch(); # endif # else printf("\n\nTests:\n\n"); testunorm16(); testunorm8(); testsnorm8(); testsnorm16(); testMatrix(); testAny(); testBinaryIO(); testSpeedLoad(); testReliableConduit(NetworkDevice::instance()); testFileSystem(); testCollisionDetection(); testTextInput(); testTextInput2(); printf(" passed\n"); testSphere(); testImageConvert(); testKDTree(); testLineSegment2D(); testGLight(); testZip(); testMap2D(); testfilter(); testArray(); testSmallArray(); testSpline(); testMatrix3(); testMatrix4(); testTable(); testTableTable(); testCoordinateFrame(); testQuat(); testReferenceCount(); testAtomicInt32(); testGThread(); testWeakCache(); testSystemMemset(); testSystemMemcpy(); testuint128(); testQueue(); testMeshAlgTangentSpace(); testConvexPolygon2D(); testPlane(); printf(" passed\n"); testAABox(); testRandom(); printf(" passed\n"); testAABoxCollision(); printf(" passed\n"); testAdjacency(); printf(" passed\n"); testWildcards(); printf(" passed\n"); testFloat(); printf(" passed\n"); testRandom(); testFuzzy(); printf(" passed\n"); testBox(); printf(" passed\n"); testBox2D(); printf(" passed\n"); testglFormatOf(); printf(" passed\n"); testSwizzle(); testGCamera(); testCallback(); testPointHashGrid(); # ifdef RUN_SLOW_TESTS testHugeBinaryIO(); printf(" passed\n"); # endif printf("%s\n", System::mallocPerformance().c_str()); System::resetMallocPerformanceCounters(); printf("\nAll tests succeeded.\n"); #endif if (renderDevice) { renderDevice->cleanup(); delete renderDevice; } NetworkDevice::cleanup(); return 0; }
HorizontalBlurPass::HorizontalBlurPass(RenderDevice& p_render_device) : PostProcessPass{ p_render_device } { if (!p_render_device.create_shader(Shader::Type::Pixel, horizontal_blur_ps_code, "main", Shader::macro_t(), m_shader)) std::abort(); }