/** * keylift is registered as a GLUT callback for when a user * releases a depressed key. * * @param key The key that was lifted. * @param x The x coordinate of the mouse at the time the key was released. * @param y The y coordinate of the mouse at the time the key was released. */ void keylift( unsigned char key, int x, int y ) { Cameras *camList = Engine::instance()->cams(); if ( camList->numCameras() < 1 ) return; Camera &cam = *(camList->active()); switch ( key ) { case 'w': cam.stop( Camera::DIR_FORWARD ); break; case 's': cam.stop( Camera::DIR_BACKWARD ); break; case 'a': cam.stop( Camera::DIR_LEFT ); break; case 'd': cam.stop( Camera::DIR_RIGHT ); break; case 'q': cam.stop( Camera::DIR_UP ); break; case 'e': cam.stop( Camera::DIR_DOWN ); break; } }
void CompositeViewer::getOperationThreads(OperationThreads& threads, bool onlyActive) { threads.clear(); Contexts contexts; getContexts(contexts); for(Contexts::iterator gcitr = contexts.begin(); gcitr != contexts.end(); ++gcitr) { osg::GraphicsContext* gc = *gcitr; if (gc->getGraphicsThread() && (!onlyActive || gc->getGraphicsThread()->isRunning()) ) { threads.push_back(gc->getGraphicsThread()); } } Cameras cameras; getCameras(cameras); for(Cameras::iterator citr = cameras.begin(); citr != cameras.end(); ++citr) { osg::Camera* camera = *citr; if (camera->getCameraThread() && (!onlyActive || camera->getCameraThread()->isRunning()) ) { threads.push_back(camera->getCameraThread()); } } }
int main(int argc, char **argv) { init(); // For catching a CTRL-C signal(SIGINT,exit_handler); // Initialize int retVal = stereo.init(); if (retVal !=0 ) exit_handler(0); // Start the acquisition flow retVal = stereo.start(); if (retVal !=0 ) exit_handler(0); // Main loop while(true) { // Capture stereo images retVal = stereo.saveTwoImages(); if (retVal !=0 ) exit_handler(0); // Wait 1s between each images usleep(300000); // Handle pause/unpause and ESC int c = cvWaitKey(1); if(c == 'p') { DEBUG<<"Acquisition is now paused"<<endl; c = 0; while(c != 'p' && c != 27){ c = cvWaitKey(250); } DEBUG<<"Acquisition is now unpaused"<<endl; } if(c == 27) { DEBUG<<"Acquisition has been stopped by user"<<endl; break; } } // Stop the acquisition flow stereo.stop(); // Close cameras stereo.close(); return 0; }
CameraPtr cameraFindOrInsert(std::string key, std::function <CameraPtr()> createFunc) { camsMutex.lock(); CameraPtr cam; auto camIt = cams.find(key); if (camIt != cams.end()) { cam = camIt->second; } else { cam = createFunc(); cams.insert({key, cam}); } camsMutex.unlock(); return cam; }
TEST(CamerasTest, rotated) { Cameras cameras; size_t id = cameras.addCameraFovX( "dummy", vec3(0.0f, 0.0f, 0.0f), vec3(1.0f, 0.0f, 0.0f), vec3(0.0f, 1.0f, 0.0f), half_pi<float>()); ASSERT_EQ(1, cameras.numCameras()); auto r0 = cameras.shoot(id, vec2(0.0f, 0.0f), 0.01f, 0.01f, 1, 0.0f, 0.0f); EXPECT_VEC3_EQ(vec3(0.577f, -0.577f, -0.577f), r0.direction, 0.001f); }
ViewerBase::ThreadingModel ViewerBase::suggestBestThreadingModel() { const char* str = getenv("OSG_THREADING"); if (str) { if (strcmp(str,"SingleThreaded")==0) return SingleThreaded; else if (strcmp(str,"CullDrawThreadPerContext")==0) return CullDrawThreadPerContext; else if (strcmp(str,"DrawThreadPerContext")==0) return DrawThreadPerContext; else if (strcmp(str,"CullThreadPerCameraDrawThreadPerContext")==0) return CullThreadPerCameraDrawThreadPerContext; } Contexts contexts; getContexts(contexts); if (contexts.empty()) return SingleThreaded; #if 0 // temporary hack to disable multi-threading under Windows till we find good solutions for // crashes that users are seeing. return SingleThreaded; #endif Cameras cameras; getCameras(cameras); if (cameras.empty()) return SingleThreaded; int numProcessors = OpenThreads::GetNumberOfProcessors(); if (contexts.size()==1) { if (numProcessors==1) return SingleThreaded; else return DrawThreadPerContext; } #if 1 if (numProcessors >= static_cast<int>(cameras.size()+contexts.size())) { return CullThreadPerCameraDrawThreadPerContext; } #endif return DrawThreadPerContext; }
void Filterwheel_internals::assign(const std::string& filterwheelid, const std::vector<std::string>& arguments) { debug(LOG_DEBUG, DEBUG_LOG, 0, "assigning filterwheel of name %s", filterwheelid.c_str()); // make sure we have enough arguments if (arguments.size() < 3) { throw devicemap_error("filterwheel assign needs 3 arguments"); } // first locate the camera specified by the arguments std::string cameraid = arguments[2]; debug(LOG_DEBUG, DEBUG_LOG, 0, "get filterwheel from camera %s", cameraid.c_str()); // first try to get the camera with that id Cameras cameras; CameraWrapper camera = cameras.byname(cameraid); // then check whether it has enough ccds if (!camera->hasFilterWheel()) { debug(LOG_ERR, DEBUG_LOG, 0, "camera %s has no filter wheel", camera->getName()); throw devicemap_error("camera has no filterwheel"); } // get the ccd from the camera Astro::FilterWheel_ptr filterwheel; try { filterwheel = camera->getFilterWheel(); } catch (const CORBA::Exception& x) { std::string s = Astro::exception2string(x); debug(LOG_ERR, DEBUG_LOG, 0, "getFilterWheel exception: %s", s.c_str()); throw std::runtime_error(s); } if (CORBA::is_nil(filterwheel)) { throw devicemap_error("could not get filterwheel"); } // store it in the device map DeviceMap<Astro::FilterWheel>::assign(filterwheelid, filterwheel); }
/** * keyboard_ctrl is registered as a GLUT callback. * It is responsible for catching when special keys are pressed. * * @param key The key pressed. * @param x The x coordinate of the mouse when the key was pressed. * @param y The y coordinate of the mouse when the key was pressed. */ void keyboard_ctrl( int key, int x, int y ) { Scene *theScene = Engine::instance()->rootScene(); Cameras *camList = Engine::instance()->cams(); switch ( key ) { //Cycle between active Objects ... case GLUT_KEY_LEFT: theScene->prev(); break; case GLUT_KEY_RIGHT: theScene->next(); break; //Change the Draw Mode ... case GLUT_KEY_F1: theScene->active()->Mode( GL_POINTS ); break; case GLUT_KEY_F2: theScene->active()->Mode( GL_LINE_STRIP ); break; case GLUT_KEY_F3: theScene->active()->Mode( GL_TRIANGLE_STRIP ); break; case GLUT_KEY_F4: theScene->active()->Mode( GL_TRIANGLES ); break; } // If there are no Cameras, don't muck around with this section. if ( camList->numCameras() < 1 ) return; switch ( key ) { case GLUT_KEY_PAGE_UP: camList->prev(); break; case GLUT_KEY_PAGE_DOWN: camList->next(); break; } }
int main(int argc, char **argv) { init(); // For catching a CTRL-C signal(SIGINT,exit_handler); // Initialize int retVal = stereo.init("../examples/stereo_calib_dataset_3/"); if (retVal !=0 ) exit_handler(0); // Main loop retVal = stereo.calib(); if (retVal !=0 ) exit_handler(0); // Close camera stereo.close(); return 0; }
void GraphSceneUI::updateInitValues() { if (initValuesUpdated) return; drawingModeRadioGroupSelectedItemID = ((GraphScene*) scene)->getGlobals()->getDrawing()->getMode() - GL_POINT; shadingModeRadioGroupSelectedItemID = ((GraphScene*) scene)->getGlobals()->getDrawing()->getShading() - GL_FLAT; int i = 0; Cameras* cams = ((GraphScene*) scene)->getCameras(); for (map<string, Camera*>::iterator it = cams->getCameras()->begin(); it != cams->getCameras()->end(); it++, i++) { if ((*it).first.compare(cams->getActiveCameraID()) == 0) { activeCameraRadioGroupSelectedItemID = i; break; } } initValuesUpdated = true; }
void load_cameras(const aiScene* scene, Materials& materials, Cameras& cameras) { for (size_t i = 0; i < scene->mNumCameras; ++i) { auto camera = scene->mCameras[i]; cameras.addCameraFovX(toString(camera->mName), toVec3(camera->mPosition), normalize(toVec3(camera->mLookAt)), normalize(toVec3(camera->mUp)), camera->mHorizontalFOV * 2.0f, camera->mClipPlaneNear, camera->mClipPlaneFar); materials.names.push_back("camera"); materials.bsdfs.push_back(unique<BSDF>(new CameraBSDF())); } }
namespace cam { CvCamera::CvCamera(int devNo) : cam(new cv::VideoCapture(devNo)) {}; void CvCamera::read(cv::Mat &frame) { cam->read(frame); }; void CvCamera::readWithDepth(cv::Mat &frame, cv::Mat &depth) { return read(frame); }; bool CvCamera::isOpen() { return cam->isOpened(); }; // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- std::mutex camsMutex; Cameras cams; CameraPtr cameraFindOrInsert(std::string key, std::function <CameraPtr()> createFunc) { camsMutex.lock(); CameraPtr cam; auto camIt = cams.find(key); if (camIt != cams.end()) { cam = camIt->second; } else { cam = createFunc(); cams.insert({key, cam}); } camsMutex.unlock(); return cam; } CameraPtr getCamera(int devNo) { return cameraFindOrInsert( std::to_string(devNo), [&]() -> CameraPtr { return std::make_shared<CvCamera>(CvCamera(devNo)); }); } CameraPtr getCamera(std::string key) { std::cout << "kinect action? " << key << std::endl; if (key == "kinect") { return cameraFindOrInsert( key, [&]() -> CameraPtr { return std::make_shared<kinect::sensor::KinectCamera>(); }); } throw std::invalid_argument(key); } }
void CompositeViewer::getCameras(Cameras& cameras, bool onlyActive) { cameras.clear(); for(RefViews::iterator vitr = _views.begin(); vitr != _views.end(); ++vitr) { View* view = vitr->get(); if (view->getCamera() && (!onlyActive || (view->getCamera()->getGraphicsContext() && view->getCamera()->getGraphicsContext()->valid())) ) cameras.push_back(view->getCamera()); for(View::Slaves::iterator itr = view->_slaves.begin(); itr != view->_slaves.end(); ++itr) { if (itr->_camera.valid() && (!onlyActive || (itr->_camera->getGraphicsContext() && itr->_camera->getGraphicsContext()->valid())) ) cameras.push_back(itr->_camera.get()); } } }
TEST(CamerasTest, basic_tests) { Cameras cameras; size_t id = cameras.addCameraFovX( "dummy", vec3(0.0f, 0.0f, 0.0f), vec3(0.0f, 0.0f, -1.0f), vec3(0.0f, 1.0f, 0.0f), half_pi<float>()); ASSERT_EQ(1, cameras.numCameras()); EXPECT_EQ("dummy", cameras.name(id)); EXPECT_FLOAT_EQ(half_pi<float>(), cameras.fovx(id, 1.0f)); EXPECT_FLOAT_EQ(half_pi<float>(), cameras.fovx(id, 4.0f / 3.0f)); EXPECT_FLOAT_EQ(half_pi<float>(), cameras.fovy(id, 1.0f)); EXPECT_FLOAT_EQ(1.2870022f, cameras.fovy(id, 4.0f / 3.0f)); const float w = 800; const float h = 600; const float wInv = 1.0f / w; const float hInv = 1.0f / h; const float a = w / h; auto r0 = cameras.shoot(id, vec2(0.0f, 0.0f), wInv, hInv, a, 400.0f, 300.0f); auto r1 = cameras.shoot(id, vec2(0.0f, 0.0f), wInv, hInv, a, 0.0f, 0.0f); auto r2 = cameras.shoot(id, vec2(0.0f, 0.0f), wInv, hInv, a, 800.0f, 600.0f); auto r3 = cameras.shoot(id, vec2(0.0f, 0.0f), 0.01f, 0.01f, 1, 0.0f, 0.0f); EXPECT_VEC3_EQ(vec3(0.0f, 0.0f, 0.0f), r0.origin, 0.00001f); EXPECT_VEC3_EQ(vec3(0.0f, 0.0f, -1.0f), r0.direction, 0.00001f); EXPECT_VEC3_EQ(vec3(0.0f), r1.origin, 0.000001f); EXPECT_VEC3_EQ(vec3(-0.685994f, -0.514496f, -0.514496f), r1.direction, 0.000001f); EXPECT_VEC3_EQ(vec3(0.0f), r2.origin, 0.000001f); EXPECT_VEC3_EQ(vec3(0.685994f, 0.514496f, -0.514496f), r2.direction, 0.0001f); EXPECT_VEC3_EQ(vec3(0.0f), r3.origin, 0.00001f); EXPECT_VEC3_EQ(vec3(-0.577f, -0.577f, -0.577f), r3.direction, 0.001f); }
/** * keyboard is a callback registered with GLUT. * It handles (surprise!) keyboard input. * * @param key The key pressed by the user. * @param x The x coordinate of the mouse when the key was pressed. * @param y The y coordinate of the mouse when the key was pressed. */ void keyboard( unsigned char key, int x, int y ) { Scene *theScene = Engine::instance()->rootScene(); Cameras *camList = Engine::instance()->cams(); #ifdef WII // Hacky, for the wii reset, below. Camera *camptr = dynamic_cast< Camera* >( (*_camList)["AutoCamera2"] ); #endif switch ( key ) { case 033: // Escape Key /* cleanup(); Disabled for now; not crucial. Intend to fix later when I profile a bit more with valgrind. */ glutLeaveMainLoop(); break; case ';': // Print Info fprintf( stderr, "Active Object: %s\n", theScene->active()->Name().c_str() ); break; case '~': #ifdef WII CalibrateGyro( Wii ); if (camptr) camptr->resetRotation(); #endif break; case '+': std::stringstream camName; camName << "AutoCamera" << camList->numCameras() + 1; camList->addCamera( camName.str() ); break; } if ( camList->numCameras() < 1 ) return; /* A shorthand variable with local scope that refers to "The active Camera." */ Camera &cam = *(camList->active()); switch ( key ) { case '-': camList->popCamera(); break; case ';': fprintf( stderr, "Camera Position: (%f,%f,%f)\n", cam.x(), cam.y(), cam.z() ); break; case 'w': cam.move( Camera::DIR_FORWARD ); break; case 's': cam.move( Camera::DIR_BACKWARD ); break; case 'a': cam.move( Camera::DIR_LEFT ); break; case 'd': cam.move( Camera::DIR_RIGHT ); break; case 'q': cam.move( Camera::DIR_UP ); break; case 'e': cam.move( Camera::DIR_DOWN ); break; //Perspectives case 'z': cam.changePerspective( Camera::PERSPECTIVE ); break; case 'x': cam.changePerspective( Camera::ORTHO ); break; case 'c': cam.changePerspective( Camera::ORTHO2D ); break; case 'v': cam.changePerspective( Camera::FRUSTUM ); break; case 'b': cam.changePerspective( Camera::IDENTITY ); break; } }
void ViewerBase::renderingTraversals() { bool _outputMasterCameraLocation = false; if (_outputMasterCameraLocation) { Views views; getViews(views); for(Views::iterator itr = views.begin(); itr != views.end(); ++itr) { osgViewer::View* view = *itr; if (view) { const osg::Matrixd& m = view->getCamera()->getInverseViewMatrix(); OSG_NOTICE<<"View "<<view<<", Master Camera position("<<m.getTrans()<<"), rotation("<<m.getRotate()<<")"<<std::endl; } } } Contexts contexts; getContexts(contexts); // check to see if windows are still valid checkWindowStatus(contexts); if (_done) return; double beginRenderingTraversals = elapsedTime(); osg::FrameStamp* frameStamp = getViewerFrameStamp(); if (getViewerStats() && getViewerStats()->collectStats("scene")) { unsigned int frameNumber = frameStamp ? frameStamp->getFrameNumber() : 0; Views views; getViews(views); for(Views::iterator vitr = views.begin(); vitr != views.end(); ++vitr) { View* view = *vitr; osg::Stats* stats = view->getStats(); osg::Node* sceneRoot = view->getSceneData(); if (sceneRoot && stats) { osgUtil::StatsVisitor statsVisitor; sceneRoot->accept(statsVisitor); statsVisitor.totalUpStats(); unsigned int unique_primitives = 0; osgUtil::Statistics::PrimitiveCountMap::iterator pcmitr; for(pcmitr = statsVisitor._uniqueStats.GetPrimitivesBegin(); pcmitr != statsVisitor._uniqueStats.GetPrimitivesEnd(); ++pcmitr) { unique_primitives += pcmitr->second; } stats->setAttribute(frameNumber, "Number of unique StateSet", static_cast<double>(statsVisitor._statesetSet.size())); stats->setAttribute(frameNumber, "Number of unique Group", static_cast<double>(statsVisitor._groupSet.size())); stats->setAttribute(frameNumber, "Number of unique Transform", static_cast<double>(statsVisitor._transformSet.size())); stats->setAttribute(frameNumber, "Number of unique LOD", static_cast<double>(statsVisitor._lodSet.size())); stats->setAttribute(frameNumber, "Number of unique Switch", static_cast<double>(statsVisitor._switchSet.size())); stats->setAttribute(frameNumber, "Number of unique Geode", static_cast<double>(statsVisitor._geodeSet.size())); stats->setAttribute(frameNumber, "Number of unique Drawable", static_cast<double>(statsVisitor._drawableSet.size())); stats->setAttribute(frameNumber, "Number of unique Geometry", static_cast<double>(statsVisitor._geometrySet.size())); stats->setAttribute(frameNumber, "Number of unique Vertices", static_cast<double>(statsVisitor._uniqueStats._vertexCount)); stats->setAttribute(frameNumber, "Number of unique Primitives", static_cast<double>(unique_primitives)); unsigned int instanced_primitives = 0; for(pcmitr = statsVisitor._instancedStats.GetPrimitivesBegin(); pcmitr != statsVisitor._instancedStats.GetPrimitivesEnd(); ++pcmitr) { instanced_primitives += pcmitr->second; } stats->setAttribute(frameNumber, "Number of instanced Stateset", static_cast<double>(statsVisitor._numInstancedStateSet)); stats->setAttribute(frameNumber, "Number of instanced Group", static_cast<double>(statsVisitor._numInstancedGroup)); stats->setAttribute(frameNumber, "Number of instanced Transform", static_cast<double>(statsVisitor._numInstancedTransform)); stats->setAttribute(frameNumber, "Number of instanced LOD", static_cast<double>(statsVisitor._numInstancedLOD)); stats->setAttribute(frameNumber, "Number of instanced Switch", static_cast<double>(statsVisitor._numInstancedSwitch)); stats->setAttribute(frameNumber, "Number of instanced Geode", static_cast<double>(statsVisitor._numInstancedGeode)); stats->setAttribute(frameNumber, "Number of instanced Drawable", static_cast<double>(statsVisitor._numInstancedDrawable)); stats->setAttribute(frameNumber, "Number of instanced Geometry", static_cast<double>(statsVisitor._numInstancedGeometry)); stats->setAttribute(frameNumber, "Number of instanced Vertices", static_cast<double>(statsVisitor._instancedStats._vertexCount)); stats->setAttribute(frameNumber, "Number of instanced Primitives", static_cast<double>(instanced_primitives)); } } } Scenes scenes; getScenes(scenes); for(Scenes::iterator sitr = scenes.begin(); sitr != scenes.end(); ++sitr) { Scene* scene = *sitr; osgDB::DatabasePager* dp = scene ? scene->getDatabasePager() : 0; if (dp) dp->signalBeginFrame(frameStamp); osgDB::ImagePager* ip = scene ? scene->getImagePager() : 0; if (ip) ip->signalBeginFrame(frameStamp); if (scene->getSceneData()) { // fire off a build of the bounding volumes while we // are still running single threaded. scene->getSceneData()->getBound(); } } // OSG_NOTICE<<std::endl<<"Start frame"<<std::endl; Cameras cameras; getCameras(cameras); Contexts::iterator itr; bool doneMakeCurrentInThisThread = false; if (_endDynamicDrawBlock.valid()) { _endDynamicDrawBlock->reset(); } // dispatch the rendering threads if (_startRenderingBarrier.valid()) _startRenderingBarrier->block(); // reset any double buffer graphics objects for(Cameras::iterator camItr = cameras.begin(); camItr != cameras.end(); ++camItr) { osg::Camera* camera = *camItr; Renderer* renderer = dynamic_cast<Renderer*>(camera->getRenderer()); if (renderer) { if (!renderer->getGraphicsThreadDoesCull() && !(camera->getCameraThread())) { renderer->cull(); } } } for(itr = contexts.begin(); itr != contexts.end() && !_done; ++itr) { if (!((*itr)->getGraphicsThread()) && (*itr)->valid()) { doneMakeCurrentInThisThread = true; makeCurrent(*itr); (*itr)->runOperations(); } } // OSG_NOTICE<<"Joing _endRenderingDispatchBarrier block "<<_endRenderingDispatchBarrier.get()<<std::endl; // wait till the rendering dispatch is done. if (_endRenderingDispatchBarrier.valid()) _endRenderingDispatchBarrier->block(); for(itr = contexts.begin(); itr != contexts.end() && !_done; ++itr) { if (!((*itr)->getGraphicsThread()) && (*itr)->valid()) { doneMakeCurrentInThisThread = true; makeCurrent(*itr); (*itr)->swapBuffers(); } } for(Scenes::iterator sitr = scenes.begin(); sitr != scenes.end(); ++sitr) { Scene* scene = *sitr; osgDB::DatabasePager* dp = scene ? scene->getDatabasePager() : 0; if (dp) dp->signalEndFrame(); osgDB::ImagePager* ip = scene ? scene->getImagePager() : 0; if (ip) ip->signalEndFrame(); } // wait till the dynamic draw is complete. if (_endDynamicDrawBlock.valid()) { // osg::Timer_t startTick = osg::Timer::instance()->tick(); _endDynamicDrawBlock->block(); // OSG_NOTICE<<"Time waiting "<<osg::Timer::instance()->delta_m(startTick, osg::Timer::instance()->tick())<<std::endl;; } if (_releaseContextAtEndOfFrameHint && doneMakeCurrentInThisThread) { //OSG_NOTICE<<"Doing release context"<<std::endl; releaseContext(); } if (getViewerStats() && getViewerStats()->collectStats("update")) { double endRenderingTraversals = elapsedTime(); // update current frames stats getViewerStats()->setAttribute(frameStamp->getFrameNumber(), "Rendering traversals begin time ", beginRenderingTraversals); getViewerStats()->setAttribute(frameStamp->getFrameNumber(), "Rendering traversals end time ", endRenderingTraversals); getViewerStats()->setAttribute(frameStamp->getFrameNumber(), "Rendering traversals time taken", endRenderingTraversals-beginRenderingTraversals); } _requestRedraw = false; }
void ViewerBase::startThreading() { if (_threadsRunning) return; OSG_INFO<<"Viewer::startThreading() - starting threading"<<std::endl; // release any context held by the main thread. releaseContext(); _threadingModel = _threadingModel==AutomaticSelection ? suggestBestThreadingModel() : _threadingModel; Contexts contexts; getContexts(contexts); OSG_INFO<<"Viewer::startThreading() - contexts.size()="<<contexts.size()<<std::endl; Cameras cameras; getCameras(cameras); unsigned int numThreadsOnStartBarrier = 0; unsigned int numThreadsOnEndBarrier = 0; switch(_threadingModel) { case(SingleThreaded): numThreadsOnStartBarrier = 1; numThreadsOnEndBarrier = 1; return; case(CullDrawThreadPerContext): numThreadsOnStartBarrier = contexts.size()+1; numThreadsOnEndBarrier = contexts.size()+1; break; case(DrawThreadPerContext): numThreadsOnStartBarrier = 1; numThreadsOnEndBarrier = 1; break; case(CullThreadPerCameraDrawThreadPerContext): numThreadsOnStartBarrier = cameras.size()+1; numThreadsOnEndBarrier = 1; break; default: OSG_NOTICE<<"Error: Threading model not selected"<<std::endl; return; } // using multi-threading so make sure that new objects are allocated with thread safe ref/unref osg::Referenced::setThreadSafeReferenceCounting(true); Scenes scenes; getScenes(scenes); for(Scenes::iterator scitr = scenes.begin(); scitr != scenes.end(); ++scitr) { if ((*scitr)->getSceneData()) { OSG_INFO<<"Making scene thread safe"<<std::endl; // make sure that existing scene graph objects are allocated with thread safe ref/unref (*scitr)->getSceneData()->setThreadSafeRefUnref(true); // update the scene graph so that it has enough GL object buffer memory for the graphics contexts that will be using it. (*scitr)->getSceneData()->resizeGLObjectBuffers(osg::DisplaySettings::instance()->getMaxNumberOfGraphicsContexts()); } } int numProcessors = OpenThreads::GetNumberOfProcessors(); bool affinity = numProcessors>1; Contexts::iterator citr; unsigned int numViewerDoubleBufferedRenderingOperation = 0; bool graphicsThreadsDoesCull = _threadingModel == CullDrawThreadPerContext || _threadingModel==SingleThreaded; for(Cameras::iterator camItr = cameras.begin(); camItr != cameras.end(); ++camItr) { osg::Camera* camera = *camItr; Renderer* renderer = dynamic_cast<Renderer*>(camera->getRenderer()); if (renderer) { renderer->setGraphicsThreadDoesCull(graphicsThreadsDoesCull); renderer->setDone(false); renderer->reset(); ++numViewerDoubleBufferedRenderingOperation; } } if (_threadingModel==CullDrawThreadPerContext) { _startRenderingBarrier = 0; _endRenderingDispatchBarrier = 0; _endDynamicDrawBlock = 0; } else if (_threadingModel==DrawThreadPerContext || _threadingModel==CullThreadPerCameraDrawThreadPerContext) { _startRenderingBarrier = 0; _endRenderingDispatchBarrier = 0; _endDynamicDrawBlock = new osg::EndOfDynamicDrawBlock(numViewerDoubleBufferedRenderingOperation); #ifndef OSGUTIL_RENDERBACKEND_USE_REF_PTR if (!osg::Referenced::getDeleteHandler()) osg::Referenced::setDeleteHandler(new osg::DeleteHandler(2)); else osg::Referenced::getDeleteHandler()->setNumFramesToRetainObjects(2); #endif } if (numThreadsOnStartBarrier>1) { _startRenderingBarrier = new osg::BarrierOperation(numThreadsOnStartBarrier, osg::BarrierOperation::NO_OPERATION); } if (numThreadsOnEndBarrier>1) { _endRenderingDispatchBarrier = new osg::BarrierOperation(numThreadsOnEndBarrier, _endBarrierOperation); } osg::ref_ptr<osg::BarrierOperation> swapReadyBarrier = contexts.empty() ? 0 : new osg::BarrierOperation(contexts.size(), osg::BarrierOperation::NO_OPERATION); osg::ref_ptr<osg::SwapBuffersOperation> swapOp = new osg::SwapBuffersOperation(); typedef std::map<OpenThreads::Thread*, int> ThreadAffinityMap; ThreadAffinityMap threadAffinityMap; unsigned int processNum = 1; for(citr = contexts.begin(); citr != contexts.end(); ++citr, ++processNum) { osg::GraphicsContext* gc = (*citr); if (!gc->isRealized()) { OSG_INFO<<"ViewerBase::startThreading() : Realizng window "<<gc<<std::endl; gc->realize(); } gc->getState()->setDynamicObjectRenderingCompletedCallback(_endDynamicDrawBlock.get()); // create the a graphics thread for this context gc->createGraphicsThread(); if (affinity) gc->getGraphicsThread()->setProcessorAffinity(processNum % numProcessors); threadAffinityMap[gc->getGraphicsThread()] = processNum % numProcessors; // add the startRenderingBarrier if (_threadingModel==CullDrawThreadPerContext && _startRenderingBarrier.valid()) gc->getGraphicsThread()->add(_startRenderingBarrier.get()); // add the rendering operation itself. gc->getGraphicsThread()->add(new osg::RunOperations()); if (_threadingModel==CullDrawThreadPerContext && _endBarrierPosition==BeforeSwapBuffers && _endRenderingDispatchBarrier.valid()) { // add the endRenderingDispatchBarrier gc->getGraphicsThread()->add(_endRenderingDispatchBarrier.get()); } if (swapReadyBarrier.valid()) gc->getGraphicsThread()->add(swapReadyBarrier.get()); // add the swap buffers gc->getGraphicsThread()->add(swapOp.get()); if (_threadingModel==CullDrawThreadPerContext && _endBarrierPosition==AfterSwapBuffers && _endRenderingDispatchBarrier.valid()) { // add the endRenderingDispatchBarrier gc->getGraphicsThread()->add(_endRenderingDispatchBarrier.get()); } } if (_threadingModel==CullThreadPerCameraDrawThreadPerContext && numThreadsOnStartBarrier>1) { Cameras::iterator camItr; for(camItr = cameras.begin(); camItr != cameras.end(); ++camItr, ++processNum) { osg::Camera* camera = *camItr; camera->createCameraThread(); if (affinity) camera->getCameraThread()->setProcessorAffinity(processNum % numProcessors); threadAffinityMap[camera->getCameraThread()] = processNum % numProcessors; osg::GraphicsContext* gc = camera->getGraphicsContext(); // add the startRenderingBarrier if (_startRenderingBarrier.valid()) camera->getCameraThread()->add(_startRenderingBarrier.get()); Renderer* renderer = dynamic_cast<Renderer*>(camera->getRenderer()); renderer->setGraphicsThreadDoesCull(false); camera->getCameraThread()->add(renderer); if (_endRenderingDispatchBarrier.valid()) { // add the endRenderingDispatchBarrier gc->getGraphicsThread()->add(_endRenderingDispatchBarrier.get()); } } for(camItr = cameras.begin(); camItr != cameras.end(); ++camItr) { osg::Camera* camera = *camItr; if (camera->getCameraThread() && !camera->getCameraThread()->isRunning()) { OSG_INFO<<" camera->getCameraThread()-> "<<camera->getCameraThread()<<std::endl; camera->getCameraThread()->startThread(); } } } #if 0 if (affinity) { OpenThreads::SetProcessorAffinityOfCurrentThread(0); if (_scene.valid() && _scene->getDatabasePager()) { #if 0 _scene->getDatabasePager()->setProcessorAffinity(1); #else _scene->getDatabasePager()->setProcessorAffinity(0); #endif } } #endif #if 0 if (affinity) { for(ThreadAffinityMap::iterator titr = threadAffinityMap.begin(); titr != threadAffinityMap.end(); ++titr) { titr->first->setProcessorAffinity(titr->second); } } #endif for(citr = contexts.begin(); citr != contexts.end(); ++citr) { osg::GraphicsContext* gc = (*citr); if (gc->getGraphicsThread() && !gc->getGraphicsThread()->isRunning()) { OSG_INFO<<" gc->getGraphicsThread()->startThread() "<<gc->getGraphicsThread()<<std::endl; gc->getGraphicsThread()->startThread(); // OpenThreads::Thread::YieldCurrentThread(); } } _threadsRunning = true; OSG_INFO<<"Set up threading"<<std::endl; }
void ViewerBase::stopThreading() { if (!_threadsRunning) return; OSG_INFO<<"ViewerBase::stopThreading() - stopping threading"<<std::endl; Contexts contexts; getContexts(contexts); Cameras cameras; getCameras(cameras); Contexts::iterator gcitr; Cameras::iterator citr; for(Cameras::iterator camItr = cameras.begin(); camItr != cameras.end(); ++camItr) { osg::Camera* camera = *camItr; Renderer* renderer = dynamic_cast<Renderer*>(camera->getRenderer()); if (renderer) renderer->release(); } // delete all the graphics threads. for(gcitr = contexts.begin(); gcitr != contexts.end(); ++gcitr) { (*gcitr)->setGraphicsThread(0); } // delete all the camera threads. for(citr = cameras.begin(); citr != cameras.end(); ++citr) { (*citr)->setCameraThread(0); } for(Cameras::iterator camItr = cameras.begin(); camItr != cameras.end(); ++camItr) { osg::Camera* camera = *camItr; Renderer* renderer = dynamic_cast<Renderer*>(camera->getRenderer()); if (renderer) { renderer->setGraphicsThreadDoesCull( true ); renderer->setDone(false); } } _threadsRunning = false; _startRenderingBarrier = 0; _endRenderingDispatchBarrier = 0; _endDynamicDrawBlock = 0; OSG_INFO<<"Viewer::stopThreading() - stopped threading."<<std::endl; }
// Create a CTRL-C handler void exit_handler(int s){ stereo.close(); exit(1); }