MouseEvent GameInputs::convertMouseEvent(EventMouse *mouse) { auto mousePoint = Vec2(mouse->getCursorX(), mouse->getCursorY()); auto visRect = Director::getInstance()->getOpenGLView()->getVisibleRect(); auto height = visRect.origin.y + visRect.size.height; auto gameLayer = GameLevel::instance().getGameLayer(); MouseEvent ret; ret.button = mouse->getMouseButton(); ret.movement = mouse->getLocationInView() - mLastMousePosition; ret.posInScreen = mousePoint; ret.posInScreen.y += height; ret.posInScreen = gameLayer->convertToNodeSpace(ret.posInScreen); ret.posInMap = ret.posInScreen; ret.posInMap += gameLayer->getCamera()->getPosition() - visRect.size / 2; return ret; }
QImage FlyCamera::captureImage() { Image img; unsigned int x = img.GetCols(); unsigned int y = img.GetRows(); getCamera()->RetrieveBuffer(&img); unsigned char* picData = img.GetData(); QImage image(x, y, QImage::Format_RGB32); for(unsigned int i = 0; i <y; i++){ for(unsigned int j = 0; j <x; j++) { unsigned char data = picData[i*x+j]; image.setPixel(j, i, qRgb(data, data, data)); } } return image; }
MyRobot::MyRobot() : DifferentialWheels() { // init default values _time_step = 64; //init velocities of each wheel _left_speed = 0; _right_speed = 0; //Get and enable the spherical camera proccesses _spherical_camera = getCamera("camera_s"); _spherical_camera->enable(_time_step); //Get and enable the compass sensor _my_compass = getCompass("compass"); _my_compass->enable(_time_step); }
void ossimPlanetViewer::addEphemeris(ossim_uint32 memberBitMask) { if(!theEphemerisLayer.valid()) { if(getLight()) { theSavedLight = (osg::Light*)getLight()->clone(osg::CopyOp::DEEP_COPY_ALL); } ossimPlanet* tempPlanet = new ossimPlanet; tempPlanet->setComputeIntersectionFlag(false); theEphemerisRoot = tempPlanet; theEphemerisLayer = new ossimPlanetEphemeris(); theEphemerisLayer->setRoot(theRootNode.get()); theEphemerisLayer->setMembers(memberBitMask); // planet()->addChild(theEphemerisLayer.get()); tempPlanet->addChild(theEphemerisLayer.get()); theRootNode->addChild(tempPlanet); theEphemerisCamera = new osg::Camera; theEphemerisCamera->setProjectionResizePolicy(getCamera()->getProjectionResizePolicy()); theEphemerisCamera->setClearColor(getCamera()->getClearColor()); theEphemerisCamera->setRenderOrder(osg::Camera::PRE_RENDER); theEphemerisCamera->setRenderTargetImplementation( getCamera()->getRenderTargetImplementation() ); // theEphemerisCamera->setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); // getCamera()->setClearMask(getCamera()->getClearMask() & ~GL_COLOR_BUFFER_BIT & ~GL_DEPTH_BUFFER_BIT); theEphemerisCamera->setClearMask(GL_COLOR_BUFFER_BIT); getCamera()->setClearMask(getCamera()->getClearMask() & ~GL_COLOR_BUFFER_BIT); if(getCamera()->getViewport()) { theEphemerisCamera->setViewport(new osg::Viewport(*getCamera()->getViewport())); } else { theEphemerisCamera->setViewport(new osg::Viewport()); } addSlave(theEphemerisCamera.get(), false); theEphemerisLayer->setCamera(theEphemerisCamera.get()); theEphemerisCamera->setEventCallback(new ossimPlanetTraverseCallback()); theEphemerisCamera->setUpdateCallback(new ossimPlanetTraverseCallback()); theEphemerisCamera->setCullCallback(new ossimPlanetTraverseCallback()); //theEphemerisCamera->addChild(theRootNode.get()); //getCamera()->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR); //theEphemerisCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR); //double fov, aspectRatio, near, far; //osg::Matrixd& m = getCamera()->getProjectionMatrix(); //m.getPerspective(fov, aspectRatio, near, far); //theEphemerisCamera->setProjectionMatrixAsPerspective(fov, aspectRatio, .2, 5.0); //getCamera()->setProjectionMatrixAsPerspective(fov, aspectRatio, .0000001, .2); } }
void OBJScene::setupObjects() { NodePointer rootNode(new TransformNode(getCamera().getTransform())); MaterialNodePointer material(new MaterialNode(rootNode)); Color white(1, 1, 1); material->setAmbient(Color(0.5, 0, 0)); material->setDiffuse(white * .5); material->setSpecular(Color(0.5, 0, 1.0)); material->setShininess(20); OBJModel obj = OBJModel::import("objects/magnolia.obj", material); vector<RayObjectPointer> objects = obj.getObjects(); for(size_t i = 0; i < objects.size(); i++) { addObject(objects[i]); } }
void TestScene5::runOsg() { // open window auto viewer = new osgViewer::Viewer(); viewer->setUpViewInWindow(560, 240, 800, 600); // adjust camera auto camera = viewer->getCamera(); camera->setViewMatrixAsLookAt(osg::Vec3d(100, 100, 100), osg::Vec3d(0, 0, 0), osg::Vec3d(0, 1, 0)); // load & integrate model auto modelNode = osgDB::readNodeFile("/home/soulmerge/projects/Diplomarbeit/Prototype/resources/Ogre/alexandria.3ds"); auto modelPositioner = new osg::PositionAttitudeTransform(); modelPositioner->addChild(modelNode); modelPositioner->setPosition(osg::Vec3(-100, -100, -100)); viewer->setSceneData(modelPositioner); // loop runOsgLoop(viewer); }
void CubeScene::setupObjects() { NodePointer rootNode(new TransformNode(getCamera().getTransform())); MaterialNodePointer material(new MaterialNode(rootNode)); Color white(1, 1, 1); material->setAmbient(Color(0.5, 0, 0)); material->setDiffuse(white * .5); material->setSpecular(Color(0.5, 0, 1.0)); material->setShininess(20); RayObjectPointer cube(new Cube(material)); addObject(cube); NodePointer translation(new TranslationNode(-2.5, 0, 0, material)); RayObjectPointer cube2(new Cube(translation)); addObject(cube2); }
void SceneNodeWidget::updateSceneNode() { auto target=m_node.lock(); if(!target){ return; } // position auto &position=target->position(); ui->q_x->setValue(position[0]); ui->q_y->setValue(position[1]); ui->q_z->setValue(position[2]); // rotation auto &quternion=target->quaternion(); // mesh auto mesh=target->getMesh(); if(mesh){ ui->meshWidget->show(); } else{ ui->meshWidget->hide(); } // camera auto camera=target->getCamera(); if(camera){ ui->cameraWidget->show(); } else{ ui->cameraWidget->hide(); } // light auto light=target->getLight(); if(light){ ui->lightWidget->show(); } else{ ui->lightWidget->hide(); } }
void osaOSGMono::Initialize( const std::string& name ){ // Create the graphic context traits. The reason why this is here is because // Windows somehow requires the context to be allocated within the same thread // as the rendering thread. And this method is called within the camera thread osg::ref_ptr<osg::GraphicsContext::Traits> traits; traits = new osg::GraphicsContext::Traits; traits->readDISPLAY(); traits->x = x ; traits->y = y ; traits->width = width; traits->height = height; traits->windowName = name; traits->windowDecoration = true; traits->supportsResize = true; traits->doubleBuffer = true; if( IsQuadBufferStereoEnabled() ){ traits->quadBufferStereo = true; } if( IsOffscreenRenderingEnabled() ) { traits->pbuffer = true; } traits->sharedContext = 0; //osg::DisplaySettings::instance()->setStereo( true ); //osg::DisplaySettings::instance()->setStereoMode( osg::DisplaySettings::QUAD_BUFFER ); // Get the master camera osg::ref_ptr<osg::Camera> camera = getCamera(); //camera->setName( GetName() ); // Create the graphic context osg::ref_ptr<osg::GraphicsContext> gc; gc = osg::GraphicsContext::createGraphicsContext( traits.get() ); camera->setGraphicsContext( gc.get() ); // Create/Set the drawing buffers GLenum buffer = traits->doubleBuffer ? GL_BACK : GL_FRONT; camera->setDrawBuffer( buffer ); camera->setReadBuffer( buffer ); camera->setClearColor( osg::Vec4d( 0.0, 0.0, 0.0, 0.0 ) ); for( size_t i=0; i<huds.size(); i++ ) { huds[i]->Initialize( gc.get() ); } }
void RenderSystem::update() { glm::mat4 view; if(!getCamera(view)) return; glClearColor(0.0f,0.0f,0.5f,1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glm::mat4 projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 10000.0f); for(Entity entity : EM->entities){ if(auto shaders = EM->getGLShaders(entity)){ if(auto mesh = EM->getGLMesh(entity)){ GLuint programId = SM.GetShaderProgram(*shaders); glUseProgram(programId); glm::mat4 Model = glm::mat4(1.0f); if(auto position = EM->getPosition(entity)){ glm::mat4 translate = glm::translate(position->position); glm::mat4 orientation = glm::toMat4(position->quaternion); glm::mat4 scale = glm::scale( glm::vec3(0.5,0.5,0.5) ); Model = translate * orientation * scale * Model; } glm::mat4 MVP = projection * view * Model; GLuint MatrixID = (GLuint)glGetUniformLocation(programId, "MVP"); glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]); GLuint WinScaleID = (GLuint)glGetUniformLocation(programId, "WIN_SCALE"); glUniform2f(WinScaleID, 640, 480); draw(&(*mesh)); } } } SDL_GL_SwapWindow(window); }
ViewerQT::ViewerQT(QWidget * parent, const char * name, const QGLWidget * shareWidget, WindowFlags f): AdapterWidget( parent, name, shareWidget, f) { setCamera(this->getCamera()); // Camera getCamera()->setViewport(new osg::Viewport(0,0,width(),height())); getCamera()->setProjectionMatrixAsPerspective(30.0f, static_cast<double>(width())/static_cast<double>(height()), 1.0f, 10000.0f); getCamera()->setGraphicsContext(getGraphicsWindow()); getCamera()->setClearColor(osg::Vec4d(51/255.0, 51/255.0, 102/255.0, 0)); getCamera()->setViewMatrix(osg::Matrix::identity()); // // getCamera()->setProjectionMatrixAsOrtho2D(0,1280,0,1024); // // getCamera()->setClearColor(osg::Vec4d(1, 1, 1, 0)); // getCamera()->setReferenceFrame(osg::Transform::ABSOLUTE_RF); // getCamera()->setClearMask(GL_DEPTH_BUFFER_BIT); // getCamera()->setRenderOrder(osg::Camera::POST_RENDER); // getCamera()->setUpdateCallback(new AxisCameraUpdateCallback()); // QString axespath = QCoreApplication::applicationDirPath() + "/axes.osg"; // osg::Node* axes = osgDB::readNodeFile(axespath.toLatin1().data()); // qDebug()<<axes->asGroup()->getNumChildren(); // qDebug()<<axespath; // getCamera()->addChild(axes); // Trackball m_rpTrackball = new osgGA::TrackballManipulator; // setCameraManipulator(m_rpTrackball.get()); addEventHandler(new osgGA::StateSetManipulator(getCamera()->getOrCreateStateSet())); // addEventHandler(new osgViewer::WindowSizeHandler); addEventHandler(new osgViewer::StatsHandler); // Scene root m_rpSceneGroupRoot = new osg::Group; setSceneData(m_rpSceneGroupRoot.get()); osg::Camera* camera = createHUD(); addSlave(camera, false); m_rpSceneGroupRoot->addChild(camera); osgText::Text* text = new osgText::Text; m_rpSceneGroupRoot->addChild( createHUD_viewPoint( text));//加入HUD文字 // pickHandler = new PickHandler; // addEventHandler(pickHandler); addEventHandler(new PickDragHandler(text)); osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator; keyswitchManipulator->addMatrixManipulator(1,"Trackball",new osgGA::TrackballManipulator()); keyswitchManipulator->addMatrixManipulator(2,"Flight",new osgGA::FlightManipulator()); keyswitchManipulator->addMatrixManipulator(3,"Drive",new osgGA::DriveManipulator()); keyswitchManipulator->addMatrixManipulator(4,"Terrain",new osgGA::TerrainManipulator()); setCameraManipulator(keyswitchManipulator.get()); setThreadingModel(osgViewer::Viewer::SingleThreaded); connect(&_timer, SIGNAL(timeout()), this, SLOT(updateGL())); _timer.start(10); }
void OLayer2D::render(float interpolation) { if (m_CurrentRenderer) { m_CurrentRenderer->begin(); //Send sprites for ( OSprite* renderable : m_Renderables) if(renderable->shouldBeRendered(m_Camera) && !renderable->hidden){ renderable->submit(m_CurrentRenderer); } //Send particles particleEngine->draw(m_CurrentRenderer); m_CurrentRenderer->end(); m_CurrentRenderer->flush(getCamera()); } }
void PerspRoot::setCamera(const PerspCameraParams& p) { if (mMaster) { #ifdef _DEBUG throw std::runtime_error("PerspRoot::setCamera() illegal: root is a slave"); #endif return; } if (p == getCamera()) return; mCamera.setEyePoint(p.mPosition); mCamera.setCenterOfInterestPoint(p.mTarget); mCamera.setPerspective(p.mFov, ci::app::getWindowAspectRatio(), p.mNearPlane, p.mFarPlane); mCamera.setLensShiftHorizontal(p.mLensShiftH); mCamera.setLensShiftVertical(p.mLensShiftV); //mCamera.setLensShiftHorizontal(1.0f); mCameraDirty = true; }
void CameraWrapper::attach(Ogre::Viewport* viewport) { #if OGRE_VERSION_MAJOR == 1 Ogre::Camera* camera = getCamera(); mViewport = viewport; if (mViewport == 0) { LOG(ERROR) << "Failed to get viewport"; return; } mViewport->setBackgroundColour(mBgColour); camera->setAspectRatio( float(mViewport->getActualWidth()) / float(mViewport->getActualHeight())); mViewport->setCamera(camera); mIsActive = true; LOG(INFO) << "Attached camera to viewport"; #else LOG(ERROR) << "Attaching camera to viewport is not supported in ogre " << OGRE_VERSION_MAJOR << "." << OGRE_VERSION_MINOR << " . Use compositor instead"; #endif }
bool Viewer::initScene(std::string& earthfile) { // 创建基础场景 osg::Node* earthNode = osgDB::readNodeFile(earthfile); if (!earthNode) { QMessageBox::warning(0, "警告", ".earth 文件不存在或加载失败"); return false; } _root = new osg::Group; _root->addChild(earthNode); setSceneData(_root); _mapNode = osgEarth::MapNode::findMapNode(earthNode); getCamera()->addCullCallback(new osgEarth::Util::AutoClipPlaneCullCallback(_mapNode)); _manip = new MyEarth::EarthManipulator; setCameraManipulator(_manip); return true; }
Camera* Map::addCamera(const std::string &id, Layer *layer, const Rect& viewport) { if (layer == NULL) { throw NotSupported("Must have valid layer for camera"); } if (getCamera(id)) { std::string errorStr = "Camera: " + id + " already exists"; throw NameClash(errorStr); } // create new camera and add to list of cameras Camera* camera = new Camera(id, layer, viewport, m_renderbackend); m_cameras.push_back(camera); std::vector<RendererBase*>::iterator iter = m_renderers.begin(); for ( ; iter != m_renderers.end(); ++iter) { camera->addRenderer((*iter)->clone()); } return camera; }
cv::Mat osaOSGStereo::GetRGBImage( size_t idx ) { // Get the left/right slave const osg::View::Slave& slave = getSlave( idx ); osg::ref_ptr< osg::Camera > camera = slave._camera.get(); osg::ref_ptr< osg::Camera::DrawCallback > dcb; dcb = getCamera()->getFinalDrawCallback(); // osg::ref_ptr<osg::Referenced> ref = dcb->getUserData(); osg::ref_ptr<osaOSGCamera::FinalDrawCallback::Data> data = NULL; data = dynamic_cast<osaOSGCamera::FinalDrawCallback::Data*>( ref.get() ); if( data != NULL ){ data->RequestRGBImage(); osaSleep( 1.0 ); return data->GetRGBImage(); } return cv::Mat(); }
void MainCamera::pickInWorld(Ogre::Real mouseX, Ogre::Real mouseY, const MousePickerArgs& mousePickerArgs) { S_LOG_INFO("Trying to pick an entity at mouse coords: " << Ogre::StringConverter::toString(mouseX) << ":" << Ogre::StringConverter::toString(mouseY) << "."); // get the terrain vector for mouse coords when a pick event happens //mAvatarTerrainCursor->getTerrainCursorPosition(); // Start a new ray query Ogre::Ray cameraRay = getCamera().getCameraToViewportRay( mouseX, mouseY ); mCameraRaySceneQuery->setRay(cameraRay); mCameraRaySceneQuery->execute(); //now check the entity picking Ogre::RaySceneQueryResult& queryResult = mCameraRaySceneQuery->getLastResults(); bool continuePicking = true; for (WorldPickListenersStore::iterator I = mPickListeners.begin(); I != mPickListeners.end(); ++I) { (*I)->initializePickingContext(); } Ogre::RaySceneQueryResult::iterator rayIterator = queryResult.begin( ); Ogre::RaySceneQueryResult::iterator rayIterator_end = queryResult.end( ); if (rayIterator != rayIterator_end) { for ( ; rayIterator != rayIterator_end && continuePicking; rayIterator++ ) { for (WorldPickListenersStore::iterator I = mPickListeners.begin(); I != mPickListeners.end(); ++I) { (*I)->processPickResult(continuePicking, *rayIterator, cameraRay, mousePickerArgs); if (!continuePicking) { break; } } } } for (WorldPickListenersStore::iterator I = mPickListeners.begin(); I != mPickListeners.end(); ++I) { (*I)->endPickingContext(mousePickerArgs); } }
void Graphics::enableCam(bool c) { if(c && !isCamEnabled) { glPushMatrix(); Camera* cam = getCamera(); glTranslated(0-cam->getX(), 0-cam->getY(),0); glTranslated(cam->getCenterX(),cam->getCenterY(),0); glRotated(cam->getRot(),0,0,-1); glTranslated(0-cam->getCenterX(),0-cam->getCenterY(),0); glScaled(cam->getZoom(),cam->getZoom(),1); isCamEnabled = true; } if(!c && isCamEnabled) { glPopMatrix(); isCamEnabled = false; } }
void ViewerQT::drawUcs() { static float _lightDir1[] = {-50.0f, 100.0f, 100.0f, 1.0f}; static float _lightDir2[] = {100.0f, -25.0f, 100.0f, 1.0f}; if (_ucsDL < 0) CompileUIElements(); osg::Vec3 axis; double angle; // Get rotation from matrix as axis/angle rotation. getCamera()->getViewMatrix().getRotate().getRotate(angle, axis); glClear(GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_LIGHT1); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, 600.0, 0.0, 600.0, -200.0, 200.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glPushMatrix(); glTranslatef(50.0f, 50.0f, 100.0f); glLightfv(GL_LIGHT0, GL_POSITION, _lightDir1); glLightfv(GL_LIGHT1, GL_POSITION, _lightDir2); glRotated(angle * 180.0 / osg::PI, axis[0], axis[1], axis[2]); DrawUcsIcon(); glPopMatrix(); glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); glDisable(GL_LIGHT1); }
// Rotate the Camera about horizontal and vertical angles given by the user void Navigation::rotateViewHV(float anglehorz, float anglevert) { // FIXME: rotateViewHorz(anglehorz);rotateViewVert(anglevert) would be much more generic ... but maybe more expensive ... // for now, we use quaternion rotation... we'll have to benchmark this quat horz = quat::createQuat(anglehorz, getCamera()->getUpVector()); quat vert = quat::createQuat(anglevert, getCamera()->getStrafe()); // this way, we save calculations by multiplying the quaternions representing // the horizontal and vertical rotations instead of changing the view twice, once // for each angle and axis vec3 look = normalize( quat::rotate(getCamera()->getLook(), vert * horz) ); // we do not allow views that are too similar to the up-vector since this results // in "flickering" if (fabs(dot(look, getCamera()->getUpVector())) > .995f) return; // Set the new focus-point getCamera()->setFocus(getCamera()->getPosition() + getCamera()->getFocalLength()*look); }
void PortVideoSDL::showError(const char* error) { SDL_FillRect(window_,0,0); SDL_Rect *image_rect = new SDL_Rect(); image_rect->x = (width_-camera_rect.w)/2-47; image_rect->y = (height_-camera_rect.h)/2-39; image_rect->w = camera_rect.w; image_rect->h = camera_rect.h; SDL_BlitSurface(getCamera(), &camera_rect, window_, image_rect); delete image_rect; std::string error_message = "Press any key to exit "+app_name_+" ..."; FontTool::drawText((width_- FontTool::getTextWidth(error))/2,height_/2+60,error,window_); FontTool::drawText((width_- FontTool::getTextWidth(error_message.c_str()))/2,height_/2+80,error_message.c_str(),window_); SDL_Flip(window_); error_=true; while(error_) { process_events(); SDL_Delay(1); } }
void meshrenderer::renderForView(CameraID cam) { Camera& c = getCamera(cam); alfar::Vector3 camPos = transform::getWorldPosition(c._tn); for(int i = 0; i < gMeshRendererManager._num_objects; ++i) { MeshRenderer& m = gMeshRendererManager._objects[i]; if(m.transform == -1 || m.material == -1 || m.mesh == -1) continue;//it's not fully set, ignore alfar::Vector3 objPos = transform::getWorldPosition(m.transform); RenderKey key = meshrenderer::createRenderKey(m); key.sortKey.transp_dist = alfar::vector3::sqrMagnitude(alfar::vector3::sub(camPos, objPos)); key.sortKey.cameraID = cam; key.sortKey.layer = 5;//default layer for everything renderer::addRenderable(key); } }
Node::NodeSP SceneLoader::__loadCamera(const QDomElement& og_component, Node::NodeSP dt_node) { Node::NodeSP node = dt_node; if ( !og_component.isNull() ) { QString name = og_component.attribute(SL_NAME); if ( node == nullptr ) { node = mScene->addChildNode(new Node(name + "_node")); QDomElement pos = og_component.firstChildElement(SL_POS); QDomElement rot = og_component.firstChildElement(SL_ROT); node->setPosition(pos.attribute(SL_X).toFloat(), pos.attribute(SL_Y).toFloat(), pos.attribute(SL_Z).toFloat()); node->setRotation(Ogre::Quaternion(rot.attribute(SL_QW).toFloat(), rot.attribute(SL_QX).toFloat(), rot.attribute(SL_QY).toFloat(), rot.attribute(SL_QZ).toFloat())); } //add camera component auto camera = node->addComponent<CameraComponent>(new CameraComponent(name)); auto og_camera = camera->getCamera(); QDomElement clipping = og_component.firstChildElement(SL_CAMERA_CLIPPING); //set camera attributes og_camera->setPolygonMode(Ogre::PolygonMode(og_component.attribute(SL_CAMERA_POLYGON_MODE).toInt())); og_camera->setFOVy(Ogre::Radian(og_component.attribute(SL_CAMERA_FOV).toFloat())); og_camera->setNearClipDistance(Ogre::Real(clipping.attribute(SL_CAMERA_CLIPPING_NEAR).toFloat())); og_camera->setFarClipDistance(Ogre::Real(clipping.attribute(SL_CAMERA_CLIPPING_FAR).toFloat())); camera->enable(); } return node; }
bool CSLevel::create(CSApplication* app, int id) { // log this event CS_LOG(CSLOGTYPE::CSL_DEBUG, "CSLevel::create()"); // remember this m_Application = app; m_Id = id; // create an instance of the base gui window createGUIBaseWindow(); // create our own smgr m_Smgr = getApplication()->getSmgr()->createNewSceneManager(); // get a pointer to this smgr's collision manager m_CollMan = m_Smgr->getSceneCollisionManager(); // creae a default camera setCamera(getSmgr()->addCameraSceneNodeFPS()); getCamera()->setInputReceiverEnabled(false); // create the physx world createPhysXWorld(); m_BlackBoard = new CSBlackBoard(); m_BlackBoard->initialize(); m_BlackBoard->create(this); // safely instantiate, initialize and create the object manager CS_CHECK_BOOL((m_ObjectFactory = new CSObjectFactory()), CSLOGTYPE::CSL_ERROR, "ERROR! unable to instantiate object factory"); CS_SAFE(m_ObjectFactory, initialize()); CS_CHECK_BOOL(m_ObjectFactory->create(this), CSLOGTYPE::CSL_ERROR, "ERROR! object factory creation failed"); // everything went fine return true; }
/// Override original method since it seems to adjust the clipping planes in a weird manner. /// Maybe using a screen-space projection or whatever. virtual void adjustCameraClippingPlanes() { SoCamera * camera = getCamera(); if (!camera) return; SoGetBoundingBoxAction clipbox_action(getViewportRegion()); clipbox_action.apply(getSceneRoot()); SbBox3f bbox = clipbox_action.getBoundingBox(); if (bbox.isEmpty()) return; SbSphere bSphere; bSphere.circumscribe(bbox); SbVec3f forward; camera->orientation.getValue().multVec(SbVec3f(0,0,-1), forward); float denumerator = forward.length(); float numerator = (bSphere.getCenter() - camera->position.getValue()).dot(forward); float distToCenter = (forward * (numerator / denumerator)).length(); float farplane = distToCenter + bSphere.getRadius(); // if scene is behind the camera, don't change the planes if (farplane < 0) return; float nearplane = distToCenter - bSphere.getRadius(); if (nearplane < (0.001 * farplane)) nearplane = 0.001 * farplane; camera->nearDistance = nearplane; camera->farDistance = farplane; }
void SceneWidget::slotVirtualScan(void) { MainWindow* main_window = MainWindow::getInstance(); osg::Vec3 eye, center, up; osg::Matrix matrix = getCamera()->getViewMatrix(); matrix.getLookAt(eye, center, up); osg::ref_ptr<PointCloud> virtual_scan(new PointCloud); for (size_t i = 0, i_end = mesh_models_.size(); i < i_end; ++i) { if (i == 0) { mesh_models_[i]->Renderable::virtualScan(eye, center, up, width(), height(), 0.0, virtual_scan->data()); } else { PclPointCloud::Ptr virtual_scan_mesh_model(new PclPointCloud); mesh_models_[i]->Renderable::virtualScan(eye, center, up, width(), height(), 0.0, virtual_scan_mesh_model); virtual_scan->data()->insert(virtual_scan->data()->end(), virtual_scan_mesh_model->begin(), virtual_scan_mesh_model->end()); } } removeSceneChild(point_cloud_); point_cloud_ = new PointCloud(virtual_scan->data(), virtual_scan->tree()); addSceneChild(point_cloud_); return; }
void FlatView::resizeGL(int width, int height) { glViewport(0, 0, width, qMax(height, 1)); if(pc_.expired()) return; auto pc = pc_.lock(); float war = width/float(height); float sar = pc->scan_width()/float(pc->scan_height()); float cfx = sar/war; float cfy = (1/sar)/(1/war); // screen if wider than scan if(war < sar){ aspect_ = Eigen::Vector2f(2.0f/pc->scan_width(), 2.0/(cfx*pc->scan_height())); } else { aspect_ = Eigen::Vector2f(2.0/(cfy*pc->scan_width()), 2.0f/pc->scan_height()); } program_.bind(); CE(); glUniformMatrix3fv(uni_camera_, 1, GL_FALSE, getCamera().data()); CE(); program_.release(); CE(); }
void LightPropertyWidget::cameraUpdate() { const CameraProperty* camProp = getCamera(); if(!camProp) return; float maxVal = camProp->getMaxValue() / 50.f; if(maxVal != property_->getMaxValue().x) { float oldRelDist = length(property_->get().xyz()) / property_->getMaxValue().x; light_->setMinDist(maxVal * 0.1f); light_->setMaxDist(maxVal); property_->setMinValue(tgt::vec4(-maxVal)); property_->setMaxValue(tgt::vec4(maxVal)); property_->set(property_->get() * oldRelDist); } const tgt::Camera& camera = camProp->get(); if (followCam_->isChecked()) { noUpdateFromProp_ = true; property_->set(camera.getViewMatrixInverse().getRotationalPart() * light_->getLightPosition()); noUpdateFromProp_ = false; } else light_->setLightPosition(camera.getViewMatrix().getRotationalPart() * property_->get()); }
QOSG::ProjectiveARViewer::ProjectiveARViewer( QWidget* parent , const char* name , const QGLWidget* shareWidget , WindowFlags f , osgViewer::Viewer* viewerPerspective ): AdapterWidget( parent, name, shareWidget, f ) { this->viewerPerspective = viewerPerspective; appConf = Util::ApplicationConfig::get(); renderCamera = new osg::Camera; useGraph = true; // setup Graph (radius 0.5m) graphPos = osg::Vec3d(-0.75, -0.25, 0.25); graphRadius = 0.5; // setup Viewer viewerPos = osg::Vec3d(-1.88, -0.95, 1.72); viewerDir = osg::Vec3d( -0.75, 0, 0.238 ) - viewerPos; viewerFOV = 90; this->setSceneData(createProjectorScene()); // setup Projector projectorPos = osg::Vec3d( -0.665, -1.345, 0.825); projectorDir = osg::Vec3d( -0.75, 0, 0.238 ) - projectorPos; projectorFOV = 30; getCamera()->setViewport( new osg::Viewport( 0,0,width(),height() ) ); getCamera()->setProjectionMatrixAsPerspective( projectorFOV, static_cast<double>( width() )/static_cast<double>( height() ), 0.01, appConf->getValue( "Viewer.Display.ViewDistance" ).toFloat() ); getCamera()->setGraphicsContext( getGraphicsWindow() ); getCamera()->setComputeNearFarMode( osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR ); getCamera()->setClearColor( osg::Vec4( 0, 0, 0, 1 ) ); getCamera()->setViewMatrixAsLookAt( projectorPos, projectorDir + projectorPos, osg::Vec3d( 0, 0, 1 ) ); addEventHandler( new osgViewer::StatsHandler ); setThreadingModel( osgViewer::ViewerBase::SingleThreaded ); connect( &_timer, SIGNAL( timeout() ), this, SLOT( updateGL() ) ); _timer.start( 10 ); }