TextRegion::TextRegion(TextRegionStyle* style) : StrokeRegion(style), _string(""), _text(NULL), _fontHeight(-1), _fontName(""), _boarderPadding(5.0f), _alignmentMode(NO_ALIGN_SET), _textColor(osg::Vec4(-0.1f,-0.1f,-0.1f,-1.0f)), _backdropType(NO_BACKDROP_SET), _backdropColor(osg::Vec4(-0.1f,-0.1f,-0.1f,-0.7f)), //callback events _onTextChangedEvent(new HudCallbackEvent(this, "OnTextChanged")) { //create the text label to add to the button _text = new osgText::Text; _text->setUseDisplayList(false); _text->setUseVertexBufferObjects(true); //_text->setCharacterSizeMode(osgText::TextBase::OBJECT_COORDS_WITH_MAXIMU_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT); //add the text to a geode for drawing osg::Geode* textGeode = new osg::Geode(); //geode is visible, not pickable textGeode->setNodeMask(hogbox::MAIN_CAMERA_CULL); MakeHudGeodes(textGeode, new RegionWrapper(this)); osg::StateSet* stateset = textGeode->getOrCreateStateSet(); stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF); #ifndef OSG_GL_FIXED_FUNCTION_AVAILABLE if(!g_textQuadProgram.get()){ g_textQuadProgram = new osg::Program; g_textQuadProgram->setName("textShader"); g_textQuadProgram->addShader(new osg::Shader(osg::Shader::VERTEX, textVertSource)); g_textQuadProgram->addShader(new osg::Shader(osg::Shader::FRAGMENT, textFragSource)); } stateset->setAttributeAndModes(g_textQuadProgram, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE); stateset->addUniform(new osg::Uniform("glyphTexture", 0)); #endif textGeode->setStateSet(stateset); textGeode->addDrawable(_text.get()); _textScale = new osg::MatrixTransform(); _textScale->addChild(textGeode); //use transform to orientate the text into correct plane and forward of the backdrop osg::MatrixTransform* oriText = new osg::MatrixTransform(); //flip plane float temp = 0.0f; osg::Vec3 offset = osg::Vec3(0,0,0.1); osg::Matrix oriMatrix; switch(_args->_planeType){ case hogbox::Quad::PLANE_XY: oriMatrix = osg::Matrix::translate(offset); break; case hogbox::Quad::PLANE_XZ: //flip x and z temp = offset.y(); offset.y() = offset.z(); offset.z() = temp; oriMatrix = osg::Matrix::translate(offset) * osg::Matrix::rotate(osg::DegreesToRadians(90.0f), osg::Vec3(1,0,0)); break; default:break; } oriText->setMatrix(oriMatrix); oriText->addChild(_textScale.get()); //attach the text to translate for now _rotate->addChild(oriText); _text->setColor(osg::Vec4(0.1f,0.1f,0.1f,1.0f)); this->SetFontType("Fonts/arial.ttf"); this->SetFontHeight(18.0f); this->SetAlignment(CENTER_ALIGN); this->SetBackDropType(NO_BACKDROP); this->SetBackDropColor(osg::Vec4(0.1f,0.1f,0.1f,0.7f)); }
virtual bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter&) { if (ea.getEventType() == osgGA::GUIEventAdapter::KEYDOWN) { if (ea.getKey() == 'm' || ea.getKey() == 'M') { switch (MouseWheelFocusPolicy) { case ManualFocusPolicy: eh_->setMouseWheelFocusPolicy( OSGUIsh::FocusPolicyFactoryMason<OSGUIsh::MouseOverFocusPolicy>()); MouseWheelFocusPolicy = MouseOverFocusPolicy; TextMouseWheelFocusPolicy->setText( "Mouse wheel focus policy: mouse over sets focus"); break; case MouseOverFocusPolicy: eh_->setMouseWheelFocusPolicy( OSGUIsh::FocusPolicyFactoryMason< OSGUIsh::MouseDownFocusPolicy>()); MouseWheelFocusPolicy = MouseDownFocusPolicy; TextMouseWheelFocusPolicy->setText( "Mouse wheel focus policy: mouse down sets focus"); break; case MouseDownFocusPolicy: eh_->setMouseWheelFocusPolicy( OSGUIsh::FocusPolicyFactoryMason< OSGUIsh::ManualFocusPolicy>()); TextMouseWheelFocusPolicy->setText( std::string("Mouse wheel focus policy: manual focus ") + "change (don't change focus)"); MouseWheelFocusPolicy = ManualFocusPolicy; break; } } else if (ea.getKey() == 'k' || ea.getKey() == 'K') { switch (KeyboardFocusPolicy) { case ManualFocusPolicy: eh_->setKeyboardFocusPolicy( OSGUIsh::FocusPolicyFactoryMason< OSGUIsh::MouseOverFocusPolicy>()); KeyboardFocusPolicy = MouseOverFocusPolicy; TextKeyboardFocusPolicy->setText( "Keyboard focus policy: mouse over sets focus"); break; case MouseOverFocusPolicy: eh_->setKeyboardFocusPolicy( OSGUIsh::FocusPolicyFactoryMason< OSGUIsh::MouseDownFocusPolicy>()); KeyboardFocusPolicy = MouseDownFocusPolicy; TextKeyboardFocusPolicy->setText( "Keyboard focus policy: mouse down sets focus"); break; case MouseDownFocusPolicy: eh_->setKeyboardFocusPolicy( OSGUIsh::FocusPolicyFactoryMason< OSGUIsh::ManualFocusPolicy>()); KeyboardFocusPolicy = ManualFocusPolicy; TextKeyboardFocusPolicy->setText( std::string("Keyboard focus policy: manual focus ") + "change (don't change focus)"); break; } } } return false; }
void SlideEventHandler::rotateImage(float rx,float ry) { const float scale = 0.5f; _texmatLeft->setMatrix(_texmatLeft->getMatrix()*osg::Matrix::translate(-rx*scale,-ry*scale,0.0f)); _texmatRight->setMatrix(_texmatRight->getMatrix()*osg::Matrix::translate(-rx*scale,-ry*scale,0.0f)); }
void HandleMouseEnter(OSGUIsh::HandlerParams& params) { TextMouseOver->setText("Mouse over " + params.node->getName()); }
void HandleMouseWheelDown(OSGUIsh::HandlerParams& params) { TextMouseWheelEvent->setText(params.node->getName() + ": Mouse wheel down!"); }
void KeyboardModel::createKeyboard() { _scene = new osg::Group; osg::Vec3 origin(0.0f,0.0f,0.0f); osg::Vec3 pos=origin; addKey(pos,osgGA::GUIEventAdapter::KEY_Control_L,"Ctrl",2.0f,0.5f); addKey(pos,osgGA::GUIEventAdapter::KEY_Super_L,"Super",2.0f,0.5f); addKey(pos,osgGA::GUIEventAdapter::KEY_Alt_L,"Alt",2.0f,0.5f); addKey(pos,osgGA::GUIEventAdapter::KEY_Space,"Space",3.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_Mode_switch,"Switch",2.0f,0.5f); addKey(pos,osgGA::GUIEventAdapter::KEY_Super_R,"Super",2.0f,0.5f); addKey(pos,osgGA::GUIEventAdapter::KEY_Menu,"Menu",2.0f,0.5f); addKey(pos,osgGA::GUIEventAdapter::KEY_Control_R,"Ctrl",2.0f,0.5f); osg::Vec3 middle(pos.x()+1.0f,0.0f,0.0f); pos.x() = 0.0f; pos.z() += 1.0f; addKey(pos,osgGA::GUIEventAdapter::KEY_Shift_L,"Shift",2.0f,0.5f); addKey(pos,osgGA::GUIEventAdapter::KEY_Backslash,"\\",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_Z,"Z",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_X,"X",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_C,"C",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_V,"V",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_B,"B",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_N,"N",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_M,"M",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_Comma,",",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_Period,".",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_Slash,"/",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_Shift_R,"Shift",2.0f,0.5f); pos.x() = 0.0f; pos.z() += 1.0f; addKey(pos,osgGA::GUIEventAdapter::KEY_Caps_Lock,"Caps",2.0f,0.5f); addKey(pos,osgGA::GUIEventAdapter::KEY_A,"A",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_S,"S",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_D,"D",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_F,"F",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_G,"G",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_H,"H",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_J,"J",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_K,"K",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_L,"L",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_Semicolon,";",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_Quote,"'",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_Hash,"#",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_Return,"Return",4.0f,0.5f); pos.x() = 0.0f; pos.z() += 1.0f; addKey(pos,osgGA::GUIEventAdapter::KEY_Tab,"Tab",2.0f,0.5f); addKey(pos,osgGA::GUIEventAdapter::KEY_Q,"Q",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_W,"W",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_E,"E",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_R,"R",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_T,"T",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_Y,"Y",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_U,"U",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_I,"I",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_O,"O",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_P,"P",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_Leftbracket,"[",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_Rightbracket,"]",1.0f,1.0f); pos.x() = 0.0f; pos.z() += 1.0f; addKey(pos,osgGA::GUIEventAdapter::KEY_Backquote,"`",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_1,"1",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_2,"2",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_3,"3",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_4,"4",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_5,"5",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_6,"6",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_7,"7",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_8,"8",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_9,"9",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_0,"0",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_Minus,"-",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_Equals,"=",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_BackSpace,"Backspace",3.0f,0.5f); pos.x() = 0.0f; pos.z() += 1.5f; float F_height = 0.5f; addKey(pos,osgGA::GUIEventAdapter::KEY_Escape,"Esc",2.0f,F_height); addKey(pos,osgGA::GUIEventAdapter::KEY_F1,"F1",1.0f,F_height); addKey(pos,osgGA::GUIEventAdapter::KEY_F2,"F2",1.0f,F_height); addKey(pos,osgGA::GUIEventAdapter::KEY_F3,"F3",1.0f,F_height); addKey(pos,osgGA::GUIEventAdapter::KEY_F4,"F4",1.0f,F_height); addKey(pos,osgGA::GUIEventAdapter::KEY_F5,"F5",1.0f,F_height); addKey(pos,osgGA::GUIEventAdapter::KEY_F6,"F6",1.0f,F_height); addKey(pos,osgGA::GUIEventAdapter::KEY_F7,"F7",1.0f,F_height); addKey(pos,osgGA::GUIEventAdapter::KEY_F8,"F8",1.0f,F_height); addKey(pos,osgGA::GUIEventAdapter::KEY_F9,"F9",1.0f,F_height); addKey(pos,osgGA::GUIEventAdapter::KEY_F10,"F10",1.0f,F_height); addKey(pos,osgGA::GUIEventAdapter::KEY_F11,"F11",1.0f,F_height); addKey(pos,osgGA::GUIEventAdapter::KEY_F12,"F12",1.0f,F_height); float cursorMoveHeight=0.35f; pos = middle; addKey(pos,osgGA::GUIEventAdapter::KEY_Left,"Left",1.0f,cursorMoveHeight); osg::Vec3 down = pos; addKey(pos,osgGA::GUIEventAdapter::KEY_Down,"Down",1.0f,cursorMoveHeight); addKey(pos,osgGA::GUIEventAdapter::KEY_Right,"Right",1.0f,cursorMoveHeight); osg::Vec3 keypad = pos; keypad.x()+=1.0f; pos = down; pos.z() += 1.0f; addKey(pos,osgGA::GUIEventAdapter::KEY_Up,"Up",1.0f,cursorMoveHeight); float homeHeight = 0.35f; pos = middle; pos.z() += 3.0; addKey(pos,osgGA::GUIEventAdapter::KEY_Delete,"Delete",1.0f,homeHeight); addKey(pos,osgGA::GUIEventAdapter::KEY_End,"End",1.0f,homeHeight); addKey(pos,osgGA::GUIEventAdapter::KEY_Page_Down,"Page\nDown",1.0f,homeHeight); pos = middle; pos.z() += 4.0; addKey(pos,osgGA::GUIEventAdapter::KEY_Insert,"Insert",1.0f,homeHeight); addKey(pos,osgGA::GUIEventAdapter::KEY_Home,"Home",1.0f,homeHeight); addKey(pos,osgGA::GUIEventAdapter::KEY_Page_Up,"Page\nUp",1.0f,homeHeight); pos = middle; pos.z() += 5.5; addKey(pos,osgGA::GUIEventAdapter::KEY_Print,"PrtScrn\nSysRq",1.0f,homeHeight); addKey(pos,osgGA::GUIEventAdapter::KEY_Scroll_Lock,"ScrLk",1.0f,homeHeight); addKey(pos,osgGA::GUIEventAdapter::KEY_Pause,"Pause\nBreak",1.0f,homeHeight); pos = keypad; addKey(pos,osgGA::GUIEventAdapter::KEY_KP_Insert,"0",2.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_KP_Delete,".",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_KP_Enter,"Enter",1.0f,homeHeight); pos = keypad; pos.z() += 1.0f; addKey(pos,osgGA::GUIEventAdapter::KEY_KP_End,"1",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_KP_Down,"2",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_KP_Page_Down,"3",1.0f,1.0f); pos = keypad; pos.z() += 2.0f; addKey(pos,osgGA::GUIEventAdapter::KEY_KP_Left,"4",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_KP_Begin,"5",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_KP_Right,"6",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_KP_Add,"+",1.0f,1.0f); pos = keypad; pos.z() += 3.0f; addKey(pos,osgGA::GUIEventAdapter::KEY_KP_Home,"7",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_KP_Up,"8",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_KP_Page_Up,"9",1.0f,1.0f); pos = keypad; pos.z() += 4.0f; addKey(pos,osgGA::GUIEventAdapter::KEY_Num_Lock,"Num\nLock",1.0f,0.3f); addKey(pos,osgGA::GUIEventAdapter::KEY_KP_Divide,"/",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_KP_Multiply,"*",1.0f,1.0f); addKey(pos,osgGA::GUIEventAdapter::KEY_KP_Subtract,"-",1.0f,1.0f); float totalWidth = pos.x()-origin.x(); pos = origin; pos.z() += -1.5f; osg::Geode* geodeInput = new osg::Geode; { _inputText = new osgText::Text; _inputText->setFont("fonts/arial.ttf"); _inputText->setColor(osg::Vec4(1.0f,1.0f,0.0f,1.0f)); _inputText->setCharacterSize(1.0f); _inputText->setMaximumWidth(totalWidth); _inputText->setPosition(pos); _inputText->setDrawMode(osgText::Text::TEXT/*||osgText::Text::BOUNDINGBOX*/); _inputText->setAlignment(osgText::Text::BASE_LINE); _inputText->setAxisAlignment(osgText::Text::XZ_PLANE); _inputText->setDataVariance(osg::Object::DYNAMIC); _inputText->setText("Press some keys..."); geodeInput->addDrawable(_inputText.get()); _scene->addChild(geodeInput); } }
bool ShaderGenerator::processGeometry(const osg::StateSet* original, osg::ref_ptr<osg::StateSet>& replacement) { // do nothing if there's no GLSL support if ( !_active ) return false; // capture the active current state: osg::ref_ptr<osg::StateSet> current = static_cast<StateEx*>(_state.get())->capture(); // check for a real osg::Program in the whole state stack. If it exists, bail out // so that OSG can use the program already in the graph. We never override a // full Program. osg::StateAttribute* program = current->getAttribute(osg::StateAttribute::PROGRAM); if ( dynamic_cast<osg::Program*>(program) != 0L ) return false; // Copy or create a new stateset (that we may or may not use depending on // what we find). Never modify an existing stateset! osg::ref_ptr<osg::StateSet> newStateSet = original ? osg::clone(original, osg::CopyOp::SHALLOW_COPY) : new osg::StateSet(); // likewise, create a VP that we might populate. osg::ref_ptr<VirtualProgram> vp = VirtualProgram::cloneOrCreate(original, newStateSet); // we'll set this to true if the new stateset goes into effect and // needs to be returned. bool needNewStateSet = false; bool needVertexFunction = false; bool needFragmentFunction = false; // give the VP a name if it needs one. if ( vp->getName().empty() ) { vp->setName( _name ); } // Check whether the lighting state has changed and install a mode uniform. // TODO: fix this if ( original && original->getMode(GL_LIGHTING) != osg::StateAttribute::INHERIT ) { needNewStateSet = true; osg::StateAttribute::GLModeValue value = current->getMode(GL_LIGHTING); newStateSet->addUniform( Registry::shaderFactory()->createUniformForGLMode(GL_LIGHTING, value) ); } // start generating the shader source. GenBuffers buf; buf._stateSet = newStateSet.get(); // if the stateset changes any texture attributes, we need a new virtual program: if (current->getTextureAttributeList().size() > 0) { bool wroteTexelDecl = false; // Loop over all possible texture image units. int maxUnit = Registry::capabilities().getMaxGPUTextureUnits(); for( int unit = 0; unit < maxUnit; ++unit ) { if ( !wroteTexelDecl ) { buf._fragBody << INDENT << MEDIUMP "vec4 texel; \n"; wroteTexelDecl = true; } osg::Texture* tex = dynamic_cast<osg::Texture*>( current->getTextureAttribute(unit, osg::StateAttribute::TEXTURE) ); if (accept(tex) && !ImageUtils::isFloatingPointInternalFormat(tex->getInternalFormat())) { osg::TexGen* texgen = dynamic_cast<osg::TexGen*>(current->getTextureAttribute(unit, osg::StateAttribute::TEXGEN)); osg::TexEnv* texenv = dynamic_cast<osg::TexEnv*>(current->getTextureAttribute(unit, osg::StateAttribute::TEXENV)); osg::TexMat* texmat = dynamic_cast<osg::TexMat*>(current->getTextureAttribute(unit, osg::StateAttribute::TEXMAT)); osg::PointSprite* sprite = dynamic_cast<osg::PointSprite*>(current->getTextureAttribute(unit, osg::StateAttribute::POINTSPRITE)); if ( apply(tex, texgen, texenv, texmat, sprite, unit, buf) == true ) { needNewStateSet = true; } } } } // Process the state attributes. osg::StateSet::AttributeList& attrs = current->getAttributeList(); if ( apply(attrs, buf) ) { needNewStateSet = true; } if ( needNewStateSet ) { std::string version = GLSL_VERSION_STR; std::string vertHeadSource; vertHeadSource = buf._vertHead.str(); std::string vertBodySource; vertBodySource = buf._vertBody.str(); if ( !vertHeadSource.empty() || !vertBodySource.empty() ) { std::string vertSource = Stringify() << "#version " << version << "\n" GLSL_PRECISION "\n" << vertHeadSource << "void " VERTEX_FUNCTION "(inout vec4 vertex_view)\n{\n" << vertBodySource << "}\n"; vp->setFunction(VERTEX_FUNCTION, vertSource, ShaderComp::LOCATION_VERTEX_VIEW, 0.5f); } std::string fragHeadSource; fragHeadSource = buf._fragHead.str(); std::string fragBodySource; fragBodySource = buf._fragBody.str(); if ( !fragHeadSource.empty() || !fragBodySource.empty() ) { std::string fragSource = Stringify() << "#version " << version << "\n" GLSL_PRECISION "\n" << fragHeadSource << "void " FRAGMENT_FUNCTION "(inout vec4 color)\n{\n" << fragBodySource << "}\n"; vp->setFunction(FRAGMENT_FUNCTION, fragSource, ShaderComp::LOCATION_FRAGMENT_COLORING, 0.5f); } } if ( needNewStateSet ) { replacement = newStateSet.get(); } return replacement.valid(); }
/** * Create and return an image for the given TileKey. */ osg::Image* createImage( const TileKey& key, ProgressCallback* progress ) { if (_debugDirect) { //osg::Image* image = new osg::Image; //image->allocateImage(256,256,1, GL_RGB, GL_UNSIGNED_BYTE); //return image; return osgDB::readImageFile( getDirectURI(key) ); //return URI(getDirectURI(key)).getImage(_dbOptions.get(), progress); } // center point of the tile (will be in spherical mercator) double x, y; key.getExtent().getCentroid(x, y); // transform it to lat/long: GeoPoint geo; GeoPoint( getProfile()->getSRS(), x, y ).transform( getProfile()->getSRS()->getGeographicSRS(), geo ); // contact the REST API. Docs are here: // http://msdn.microsoft.com/en-us/library/ff701716.aspx // construct the request URI: std::string request = Stringify() << std::setprecision(12) << _options.imageryMetadataAPI().get() // base REST API << "/" << _options.imagerySet().get() // imagery set to use << "/" << geo.y() << "," << geo.x() // center point in lat/long << "?zl=" << key.getLOD() + 1 // zoom level << "&o=json" // response format << "&key=" << _options.key().get(); // API key // check the URI cache. URI location; TileURICache::Record rec; if ( _tileURICache.get(request, rec) ) { location = URI(rec.value()); //CacheStats stats = _tileURICache.getStats(); //OE_INFO << "Ratio = " << (stats._hitRatio*100) << "%" << std::endl; } else { unsigned c = ++_apiCount; if ( c % 25 == 0 ) OE_INFO << LC << "API calls = " << c << std::endl; // fetch it: ReadResult metadataResult = URI(request).readString(_dbOptions, progress); if ( metadataResult.failed() ) { // check for a REST error: if ( metadataResult.code() == ReadResult::RESULT_SERVER_ERROR ) { OE_WARN << LC << "REST API request error!" << std::endl; Config metadata; std::string content = metadataResult.getString(); metadata.fromJSON( content ); ConfigSet errors = metadata.child("errorDetails").children(); for(ConfigSet::const_iterator i = errors.begin(); i != errors.end(); ++i ) { OE_WARN << LC << "REST API: " << i->value() << std::endl; } return 0L; } else { OE_WARN << LC << "Request error: " << metadataResult.getResultCodeString() << std::endl; } return 0L; } // decode it: Config metadata; if ( !metadata.fromJSON(metadataResult.getString()) ) { OE_WARN << LC << "Error decoding REST API response" << std::endl; return 0L; } // check the vintage field. If it's empty, that means we got a "no data" tile. Config* vintageEnd = metadata.find("vintageEnd"); if ( !vintageEnd || vintageEnd->value().empty() ) { OE_DEBUG << LC << "NO data image encountered." << std::endl; return 0L; } // find the tile URI: Config* locationConf= metadata.find("imageUrl"); if ( !locationConf ) { OE_WARN << LC << "REST API JSON parsing error (imageUrl not found)" << std::endl; return 0L; } location = URI( locationConf->value() ); _tileURICache.insert( request, location.full() ); } // request the actual tile //OE_INFO << "key = " << key.str() << ", URL = " << location->value() << std::endl; //osg::Image* image = location.getImage(_dbOptions.get(), progress); osg::Image* image = osgDB::readImageFile( location.full() ); if ( image && _geom.valid() ) { GeometryRasterizer rasterizer( image->s(), image->t() ); rasterizer.draw( _geom.get(), osg::Vec4(1,1,1,1) ); osg::ref_ptr<osg::Image> overlay = rasterizer.finalize(); ImageUtils::PixelVisitor<AlphaBlend> blend; blend.accept( overlay.get(), image ); } return image; }
GlobalFadeText* getGlobalFadeText() { static osg::ref_ptr<GlobalFadeText> s_globalFadeText = new GlobalFadeText; return s_globalFadeText.get(); }
// Add model to scene void ViewerQT::AddModelNode(osg::ref_ptr<osg::Node> mnode) { m_rpSceneGroupRoot->addChild(mnode.get()); }
int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName()); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); arguments.getApplicationUsage()->addCommandLineOption("--image <filename>","Load an image and render it on a quad"); arguments.getApplicationUsage()->addCommandLineOption("--dem <filename>","Load an image/DEM and render it on a HeightField"); arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display command line parameters"); arguments.getApplicationUsage()->addCommandLineOption("--help-env","Display environmental variables available"); arguments.getApplicationUsage()->addCommandLineOption("--help-keys","Display keyboard & mouse bindings available"); arguments.getApplicationUsage()->addCommandLineOption("--help-all","Display all command line, env vars and keyboard & mouse bindings."); arguments.getApplicationUsage()->addCommandLineOption("--dragger <draggername>","Use the specified dragger for manipulation [TabPlaneDragger, TabPlaneTrackballDragger, TrackballDragger, Translate1DDragger, Translate2DDragger, TranslateAxisDragger, TabBoxDragger, TranslatePlaneDragger, Scale1DDragger, Scale2DDragger, RotateCylinderDragger, RotateSphereDragger]"); arguments.getApplicationUsage()->addCommandLineOption("--fixedDraggerSize","Fix the size of the dragger geometry in the screen space"); bool fixedSizeInScreen = false; while (arguments.read("--fixedDraggerSize")) { fixedSizeInScreen = true; } // construct the viewer. osgViewer::Viewer viewer(arguments); // add the window size toggle handler viewer.addEventHandler(new osgViewer::WindowSizeHandler); // get details on keyboard and mouse bindings used by the viewer. viewer.getUsage(*arguments.getApplicationUsage()); if (arguments.read("--test-NodeMask")) { const osg::ref_ptr<osg::Group> group = new osg::Group(); group->setNodeMask(0); const osg::ref_ptr<osgManipulator::AntiSquish> antiSquish = new osgManipulator::AntiSquish(); group->addChild(antiSquish.get()); const osg::ref_ptr<osg::Node> node = new osg::Node(); node->setInitialBound(osg::BoundingSphere(osg::Vec3(0.0, 0.0, 0.0), 1.0)); antiSquish->addChild(node.get()); group->getBound(); return 1; } // if user request help write it out to cout. bool helpAll = arguments.read("--help-all"); unsigned int helpType = ((helpAll || arguments.read("-h") || arguments.read("--help"))? osg::ApplicationUsage::COMMAND_LINE_OPTION : 0 ) | ((helpAll || arguments.read("--help-env"))? osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE : 0 ) | ((helpAll || arguments.read("--help-keys"))? osg::ApplicationUsage::KEYBOARD_MOUSE_BINDING : 0 ); if (helpType) { arguments.getApplicationUsage()->write(std::cout, helpType); return 1; } // report any errors if they have occurred when parsing the program arguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } std::string dragger_name = "TabBoxDragger"; arguments.read("--dragger", dragger_name); osg::Timer_t start_tick = osg::Timer::instance()->tick(); // read the scene from the list of file specified command line args. osg::ref_ptr<osg::Node> loadedModel = osgDB::readRefNodeFiles(arguments); // if no model has been successfully loaded report failure. bool tragger2Scene(true); if (!loadedModel) { //std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl; //return 1; loadedModel = createDemoScene(fixedSizeInScreen); tragger2Scene=false; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occurred when parsing the program arguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); } osg::Timer_t end_tick = osg::Timer::instance()->tick(); std::cout << "Time to load = "<<osg::Timer::instance()->delta_s(start_tick,end_tick)<<std::endl; // optimize the scene graph, remove redundant nodes and state etc. osgUtil::Optimizer optimizer; optimizer.optimize(loadedModel); // pass the loaded scene graph to the viewer. if ( tragger2Scene ) { viewer.setSceneData(addDraggerToScene(loadedModel.get(), dragger_name, fixedSizeInScreen)); } else { viewer.setSceneData(loadedModel); } return viewer.run(); }
/** * Returns rotation of root node. */ Quat rot() const { return _root->getAttitude(); }
/** * Returns position of root node. */ Vec3 pos() const { return _root->getPosition(); }
static FlexUpdater* instance() { static osg::ref_ptr<FlexUpdater> s_instance = new FlexUpdater; return s_instance.get(); }
bool Geometry::geounion( const Geometry* other, osg::ref_ptr<Geometry>& output ) const { #ifdef OSGEARTH_HAVE_GEOS bool success = false; output = 0L; GEOSContext gc; //Create the GEOS Geometries geom::Geometry* inGeom = gc.importGeometry( this ); geom::Geometry* otherGeom = gc.importGeometry( other ); if ( inGeom ) { geom::Geometry* outGeom = 0L; try { outGeom = overlay::OverlayOp::overlayOp( inGeom, otherGeom, overlay::OverlayOp::opUNION ); } catch(const geos::util::GEOSException& ex) { OE_NOTICE << LC << "Union(GEOS): " << (ex.what()? ex.what() : " no error message") << std::endl; outGeom = 0L; } if ( outGeom ) { output = gc.exportGeometry( outGeom ); if ( output.valid()) { if ( output->isValid() ) { success = true; } else { // GEOS result is invalid output = 0L; } } else { // set output to empty geometry to indicate the (valid) empty case, // still returning false but allows for check. if (outGeom->getNumPoints() == 0) { output = new osgEarth::Symbology::Geometry(); } } gc.disposeGeometry( outGeom ); } } //Destroy the geometry gc.disposeGeometry( otherGeom ); gc.disposeGeometry( inGeom ); return success; #else // OSGEARTH_HAVE_GEOS OE_WARN << LC << "Union failed - GEOS not available" << std::endl; return false; #endif // OSGEARTH_HAVE_GEOS }
void updateControlPanel() { // erase all child controls and just rebuild them b/c we're lazy. //Rebuild all the image layers s_imageBox->clearControls(); int row = 0; LabelControl* activeLabel = new LabelControl( "Image Layers", 20, osg::Vec4f(1,1,0,1) ); s_imageBox->setControl( 1, row++, activeLabel ); // the active map layers: MapFrame mapf( s_activeMap.get() ); ImageLayerVector imageLayers; mapf.getLayers(imageLayers); int layerNum = imageLayers.size()-1; for( ImageLayerVector::const_reverse_iterator i = imageLayers.rbegin(); i != imageLayers.rend(); ++i ) createLayerItem( s_imageBox, row++, layerNum--, imageLayers.size(), i->get(), true ); MapFrame mapf2( s_inactiveMap.get() ); imageLayers.clear(); mapf2.getLayers(imageLayers); if ( imageLayers.size() > 0 ) { LabelControl* inactiveLabel = new LabelControl( "Removed:", 18, osg::Vec4f(1,1,0,1) ); s_imageBox->setControl( 1, row++, inactiveLabel ); for( unsigned int i=0; i<imageLayers.size(); ++i ) { createLayerItem( s_imageBox, row++, -1, -1, imageLayers[i].get(), false ); } } //Rebuild the elevation layers s_elevationBox->clearControls(); row = 0; activeLabel = new LabelControl( "Elevation Layers", 20, osg::Vec4f(1,1,0,1) ); s_elevationBox->setControl( 1, row++, activeLabel ); // the active map layers: ElevationLayerVector elevationLayers; mapf.getLayers(elevationLayers); layerNum = elevationLayers.size()-1; for( ElevationLayerVector::const_reverse_iterator i = elevationLayers.rbegin(); i != elevationLayers.rend(); ++i ) createLayerItem( s_elevationBox, row++, layerNum--, elevationLayers.size(), i->get(), true ); if ( mapf2.elevationLayers().size() > 0 ) { LabelControl* inactiveLabel = new LabelControl( "Removed:", 18, osg::Vec4f(1,1,0,1) ); s_elevationBox->setControl( 1, row++, inactiveLabel ); for( unsigned int i=0; i<mapf2.elevationLayers().size(); ++i ) { createLayerItem( s_elevationBox, row++, -1, -1, mapf2.elevationLayers().at(i), false ); } } //Rebuild the model layers s_modelBox->clearControls(); row = 0; activeLabel = new LabelControl( "Model Layers", 20, osg::Vec4f(1,1,0,1) ); s_modelBox->setControl( 1, row++, activeLabel ); // the active map layers: ModelLayerVector modelLayers; mapf.getLayers(modelLayers); for( ModelLayerVector::const_reverse_iterator i = modelLayers.rbegin(); i != modelLayers.rend(); ++i ) createModelLayerItem( s_modelBox, row++, i->get(), true ); }
namespace vrc { static const char glsl_vp[] = "/* \n" "* Vertex shader for rendering the player \n" "* http://yag2002.sf.net \n" "* 11/28/2005 \n" "*/ \n" "varying vec4 diffuse,ambient; \n" "varying vec3 normal,lightDir,halfVector; \n" " \n" "void main() \n" "{ \n" " normal = normalize(gl_NormalMatrix * gl_Normal); \n" " lightDir = normalize(vec3(gl_LightSource[0].position)); \n" " halfVector = normalize(gl_LightSource[0].halfVector.xyz); \n" " diffuse = gl_FrontMaterial.diffuse * gl_LightSource[0].diffuse; \n" " ambient = gl_FrontMaterial.ambient * gl_LightSource[0].ambient; \n" " ambient += gl_LightModel.ambient * gl_FrontMaterial.ambient; \n" " gl_Position = ftransform(); \n" "} \n" ; static const char glsl_fp[] = "/* \n" "* Fragment shader for rendering the player \n" "* http://yag2002.sf.net \n" "* 11/28/2005 \n" "*/ \n" "varying vec4 diffuse,ambient; \n" "varying vec3 normal,lightDir,halfVector; \n" "uniform sampler2D tex; \n" " \n" "void main() \n" "{ \n" " vec3 n,halfV; \n" " float NdotL,NdotHV; \n" " \n" " vec4 color = ambient; \n" " n = normalize(normal); \n" " NdotL = max(dot(n,lightDir),0.0); \n" " if (NdotL > 0.0) { \n" " color += diffuse * NdotL; \n" " halfV = normalize(halfVector); \n" " NdotHV = max(dot(n,halfV),0.0); \n" " color += gl_FrontMaterial.specular * \n" " gl_LightSource[0].specular * \n" " pow(NdotHV, gl_FrontMaterial.shininess); \n" " } \n" " \n" " vec4 texcolor = texture2D(tex,gl_TexCoord[0].st); \n" " gl_FragColor = color * texcolor; \n" "} \n" ; static osg::ref_ptr< osg::Program > s_program; //! "Implement and register the player animation entity factory YAF3D_IMPL_ENTITYFACTORY( PlayerAnimationEntityFactory ); EnPlayerAnimation::EnPlayerAnimation() : _anim( eIdle ), _p_player( NULL ), _renderingEnabled( true ), _scale( 1.0f ), _IdAnimIdle( -1 ), _IdAnimWalk( -1 ), _IdAnimRun( -1 ), _IdAnimJump( -1 ), _IdAnimLand( -1 ), _IdAnimTurn( -1 ) { // register attributes getAttributeManager().addAttribute( "animconfig" , _animCfgFile ); getAttributeManager().addAttribute( "position" , _position ); getAttributeManager().addAttribute( "rotation" , _rotation ); getAttributeManager().addAttribute( "scale" , _scale ); } EnPlayerAnimation::~EnPlayerAnimation() { if ( _animNode.get() ) _animNode = NULL; // delete the anim node } void EnPlayerAnimation::initialize() { log_info << " initializing player animation instance '" << getInstanceName() << "' ..." << std::endl; if ( !_animCfgFile.length() ) { log_error << "*** missing animation config file parameter" << std::endl; return; } // setup and create a new model std::string file = yaf3d::Application::get()->getMediaPath() + _animCfgFile; std::string rootDir = yaf3d::extractPath( file ); std::string configfilename = yaf3d::extractFileName( file ); // all textures and cal3d files must be in root dir! if ( !setupAnimation( rootDir, configfilename ) ) return; // set initial animation _model->startLoop( _IdAnimIdle, 1.0f, 0.0f ); _anim = eIdle; // scale the model _coreModel->get()->scale( _scale ); // create a transform node in order to set position and rotation offsets _animNode = new osg::PositionAttitudeTransform; _animNode->setPosition( _position ); osg::Quat quat( _rotation.x() * osg::PI / 180.0f, osg::Vec3f( 1, 0, 0 ), _rotation.y() * osg::PI / 180.0f, osg::Vec3f( 0, 1, 0 ), _rotation.z() * osg::PI / 180.0f, osg::Vec3f( 0, 0, 1 ) ); _animNode->setAttitude( quat ); _animNode->addChild( _model.get() ); // setup the shaders for ( currently just disable glsl usage ) // first check if glsl is supported before setting up the shaders ( gl context 0 is assumed ) const osg::GL2Extensions* p_extensions = osg::GL2Extensions::Get( 0, true ); if ( p_extensions->isGlslSupported() ) { if ( !s_program.valid() ) { s_program = new osg::Program; s_program->setName( "_playerAnim_" ); s_program->addShader( new osg::Shader( osg::Shader::VERTEX, glsl_vp ) ); s_program->addShader( new osg::Shader( osg::Shader::FRAGMENT, glsl_fp ) ); } osg::StateSet* p_stateSet = _animNode->getOrCreateStateSet(); p_stateSet->setAttributeAndModes( s_program.get(), osg::StateAttribute::ON ); _animNode->setStateSet( p_stateSet ); } log << " initializing player animation instance completed" << std::endl; } void EnPlayerAnimation::enableRendering( bool render ) { if ( ( _renderingEnabled && render ) || ( !_renderingEnabled && !render ) ) return; if ( !render ) _p_player->getPlayerEntity()->removeTransformationNode( _animNode.get() ); else _p_player->getPlayerEntity()->appendTransformationNode( _animNode.get() ); _renderingEnabled = render; } void EnPlayerAnimation::setPlayer( BasePlayerImplementation* p_player ) { _p_player = p_player; // add the new mesh into player's transformable scene group _p_player->getPlayerEntity()->appendTransformationNode( _animNode.get() ); } bool EnPlayerAnimation::setupAnimation( const std::string& rootDir, const std::string& configfilename ) { // this code is basing on cal3d's miniviewer std::string destFileName, cfgFileName; cfgFileName = rootDir; cfgFileName += "/"; cfgFileName += configfilename; std::ifstream file; // open the model configuration file file.open( cfgFileName.c_str(), std::ios::in | std::ios::binary ); if( !file ) { log_error << "*** failed to open model configuration file: " << file << std::endl; return false; } // set cal3d's texture coord loading mode CalLoader::setLoadingMode( LOADER_INVERT_V_COORD | LOADER_ROTATE_X_AXIS ); // create a core model instance std::string modelname = "character_" + configfilename; _coreModel = new osgCal::CoreModel( modelname ); CalCoreModel* p_calCoreModel = _coreModel->get(); // parse all lines from the model configuration file int line; for( line = 1; ; ++line ) { // read the next model configuration line std::string textBuffer; getline( file, textBuffer ); // stop if we reached the end of file if( file.eof() ) break; // check if an error happend while reading from the file if( !file ) { log_error << "*** error reading config file: " << configfilename << std::endl; return false; } // find the first non-whitespace character std::string::size_type pos; pos = textBuffer.find_first_not_of( " \t" ); // check for empty lines if( ( pos == std::string::npos) || ( textBuffer[ pos ] == '\n' ) || ( textBuffer[ pos ] == '\r' ) || ( textBuffer[ pos ] == 0 ) ) continue; // check for comment lines if( textBuffer[ pos ] == '#' ) { continue; } // get the key std::string strKey; strKey = textBuffer.substr( pos, textBuffer.find_first_of( " =\t\n\r", pos ) - pos ); pos += strKey.size(); // get the '=' character pos = textBuffer.find_first_not_of( " \t", pos ); if( (pos == std::string::npos ) || ( textBuffer[ pos ] != '=' ) ) { log_error << "*** invalid syntax in config file: '" << configfilename; log_error << "' at line" << line << std::endl; return false; } // find the first non-whitespace character after the '=' character pos = textBuffer.find_first_not_of( " \t", pos + 1 ); // get the data std::string strData; strData = textBuffer.substr( pos, textBuffer.find_first_of( "\n\r", pos ) - pos ); destFileName = rootDir + "/" + strData; // handle the model creation if( strKey == "skeleton" ) { if ( !p_calCoreModel->loadCoreSkeleton( destFileName ) ) log_error << "*** line " << line << ", problem loading skeleton: " << destFileName << std::endl; } else if( strKey == "mesh" ) { if ( p_calCoreModel->loadCoreMesh( destFileName ) < 0 ) log_error << "*** line " << line << ", problem loading mesh: " << destFileName << std::endl; } else if( strKey == "material" ) { int materialId = p_calCoreModel->loadCoreMaterial( destFileName ); if( materialId < 0 ) { log_error << "*** line " << line << ", problem loading material: " << destFileName; log_error << " reason: " << CalError::getLastErrorDescription() << std::endl; } else { p_calCoreModel->createCoreMaterialThread( materialId ); p_calCoreModel->setCoreMaterialId( materialId, 0, materialId ); CalCoreMaterial* p_material = p_calCoreModel->getCoreMaterial( materialId ); // the texture file path is relative to the CRF data directory std::vector< CalCoreMaterial::Map >::iterator p_beg = p_material->getVectorMap().begin(), p_end = p_material->getVectorMap().end(); for( ; p_beg != p_end; ++p_beg ) p_material->setFilename( p_beg->strFilename ); } } // read animation ids else if( strKey == "animation_idle" ) { _IdAnimIdle = p_calCoreModel->loadCoreAnimation( destFileName ); if ( _IdAnimIdle < 0 ) log_error << "*** line " << line << ", problem loading animation: " << destFileName << std::endl; } else if( strKey == "animation_walk" ) { _IdAnimWalk = p_calCoreModel->loadCoreAnimation( destFileName ); if ( _IdAnimWalk < 0 ) log_error << "*** line " << line << ", problem loading animation: " << destFileName << std::endl; } else if( strKey == "animation_run" ) { _IdAnimRun = p_calCoreModel->loadCoreAnimation( destFileName ); if ( _IdAnimRun < 0 ) log_error << "*** line " << line << ", problem loading animation: " << destFileName << std::endl; } else if( strKey == "animation_turn" ) { _IdAnimTurn = p_calCoreModel->loadCoreAnimation( destFileName ); if ( _IdAnimTurn < 0 ) log_error << "*** line" << line << ", problem loading animation: " << destFileName << std::endl; } else if( strKey == "animation_jump" ) { _IdAnimJump = p_calCoreModel->loadCoreAnimation( destFileName ); if ( _IdAnimJump < 0 ) log_error << "*** line" << line << ", problem loading animation: " << destFileName << std::endl; } else if( strKey == "animation_landing" ) { _IdAnimLand = p_calCoreModel->loadCoreAnimation( destFileName ); if ( _IdAnimLand < 0 ) log_error << "*** line " << line << ", problem loading animation: " << destFileName << std::endl; } else if( strKey == "animation" ) { log_error << "*** token 'animation' is not valid, line: " << line << std::endl; log_error << "*** use one of following animation tokens instead: " << std::endl;; log_error << "*** animation_idle" << std::endl;; log_error << "*** animation_walk" << std::endl;; log_error << "*** animation_run" << std::endl;; log_error << "*** animation_jump" << std::endl;; log_error << "*** animation_land" << std::endl;; } else { // everything else triggers an error message log_error << "*** invalid syntax in config file: '" << configfilename; log_error << "' at line: " << line << std::endl; return false; } } file.close(); // now load all textures, before creating the model below _coreModel->loadAllTextures( rootDir ); // create the model _model = new osgCal::Model(); _model->create( _coreModel.get() ); return true; } unsigned char EnPlayerAnimation::getAnimationFlags() { return static_cast< unsigned char >( _anim ); } void EnPlayerAnimation::setAnimation( unsigned char flags ) { switch( flags ) { case eIdle: animIdle(); break; case eWalk: animWalk(); break; case eJump: animJump(); break; case eTurn: animTurn(); break; } } void EnPlayerAnimation::animIdle() { if ( _anim == eIdle ) return; _model->startLoop( _IdAnimIdle, 1.0f, 0.5f ); _model->stopLoop( _IdAnimWalk, 0.4f ); _model->stopLoop( _IdAnimTurn, 0.4f ); _anim = eIdle; } void EnPlayerAnimation::animWalk() { if ( _anim == eWalk ) return; _model->startLoop( _IdAnimWalk, 1.0f, 0.5f ); _model->stopLoop( _IdAnimIdle, 0.5f ); _model->stopLoop( _IdAnimTurn, 0.0f ); _anim = eWalk; } void EnPlayerAnimation::animJump() { if ( _anim == eJump ) return; _model->startAction( _IdAnimJump, 0.0f, 0.9f ); _anim = eJump; } void EnPlayerAnimation::animTurn() { if ( _anim == eTurn ) return; _model->startLoop( _IdAnimTurn, 1.0f, 0.0f ); _anim = eTurn; } } // namespace vrc
int main(void){ osg::DisplaySettings::instance()->setNumMultiSamples( 4 ); viewer.setUpViewInWindow( 100, 50, 800, 600 ); viewer.getCamera()->setClearColor( osg::Vec4( 0.5,0.5,0.5,1) ); viewer.addEventHandler(new osgViewer::StatsHandler); osg::Group* scene = new osg::Group; // Création d'une boîte centrée à l'origine, de dimensions 2x3x4: osg::Box* boite = new osg::Box(osg::Vec3(-10, 0, 0), 2,3,4); osg::ShapeDrawable* boiteDrawable = new osg::ShapeDrawable(boite); osg::Geode* geodeBoite = new osg::Geode(); geodeBoite->addDrawable(boiteDrawable); osg::Sphere* sphere = new osg::Sphere( osg::Vec3(10,0,0), 1.0); osg::ShapeDrawable* sphereDrawable = new osg::ShapeDrawable(sphere); osg::Geode* geodeSphere = new osg::Geode(); geodeSphere->addDrawable(sphereDrawable); osg::Capsule* capsule = new osg::Capsule(osg::Vec3(0, 0, 0), 1.0, 3.0); osg::ShapeDrawable* capsuleDrawable = new osg::ShapeDrawable(capsule); osg::Geode* geodeCapsule = new osg::Geode(); geodeCapsule->addDrawable(capsuleDrawable); osg::Cone* cone = new osg::Cone(osg::Vec3(0, 10, 0), 1, 2); osg::ShapeDrawable* coneDrawable = new osg::ShapeDrawable(cone); osg::Geode* geodeCone= new osg::Geode(); geodeCone->addDrawable(coneDrawable); osg::Material* matBoite = new osg::Material; matBoite->setAmbient (osg::Material::FRONT_AND_BACK, osg::Vec4(0.5, 0.0, 0.0, 1.0)); matBoite->setDiffuse (osg::Material::FRONT_AND_BACK, osg::Vec4(0.9, 0.0, 0.0, 1.0)); matBoite->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(0.2, 0.2, 0.2, 1.0)); matBoite->setShininess(osg::Material::FRONT_AND_BACK, 64); osg::Material* matCone = new osg::Material; matCone->setAmbient (osg::Material::FRONT_AND_BACK, osg::Vec4(0.5, 0.0, 0.5, 1.0)); matCone->setDiffuse (osg::Material::FRONT_AND_BACK, osg::Vec4(0.9, 0.0, 0.9, 1.0)); matCone->setSpecular(osg::Material::FRONT_AND_BACK, osg::Vec4(0.2, 0.2, 0.2, 1.0)); matCone->setShininess(osg::Material::FRONT_AND_BACK, 64); osg::Node* aregne = osgDB::readNodeFile("cow_high.3ds"); transformAregne->setPosition(osg::Vec3(5, 0, 0)); transformAregne->setScale(osg::Vec3(0.2, 0.2, 0.2)); transformAregne->getOrCreateStateSet()->setMode(GL_NORMALIZE,osg::StateAttribute::ON); transformAregne->addChild(aregne); boiteDrawable->getOrCreateStateSet()->setAttributeAndModes(matBoite); coneDrawable->getOrCreateStateSet()->setAttributeAndModes(matCone); /*scene->addChild(geodeCapsule); scene->addChild(geodeCone); scene->addChild(geodeBoite); scene->addChild(geodeSphere); scene->addChild(transformAregne);*/ scene->addChild(aregne); // Création d'une texture osg::ref_ptr<osg::Texture2D> tex2D = new osg::Texture2D; tex2D->setTextureSize(1024, 1024); tex2D->setInternalFormat(GL_RGBA); // Création d'une caméra qui effectuera son rendu dans la texture osg::ref_ptr<osg::Camera> rttCamera = createRTTCamera(osg::Camera::COLOR_BUFFER, tex2D.get()); // On indique la partie du graphe que la caméra devra rendre, ici toute la scène : rttCamera->addChild(scene); // Création d'une caméra permettant d'afficher un HUD qui couvrira tout l'écran osg::ref_ptr<osg::Camera> hudCamera = createHUDCamera(); osg::Geode* screenQuad = createScreenQuad(); hudCamera->addChild(screenQuad); osg::StateSet* stateset = screenQuad->getOrCreateStateSet(); stateset->setTextureAttributeAndModes(0, tex2D.get()); // VOUS METTREZ ICI LE CODE DE LA QUESTION 7 // Création d'une nouvelle racine du graphe, à laquelle on rattache la caméra // de rendu dans une texture, la caméra du HUD et la racine du graphe de la scène osg::ref_ptr<osg::Group> root = new osg::Group; root->addChild(rttCamera.get()); root->addChild(hudCamera.get()); root->addChild(scene); // Indique au viewer la scène à affich trackCone->setTrackNode(geodeCone); trackCone->setTrackerMode(osgGA::NodeTrackerManipulator::NODE_CENTER); trackBoite->setTrackNode(geodeBoite); trackBoite->setTrackerMode(osgGA::NodeTrackerManipulator::NODE_CENTER); trackSphere->setTrackNode(geodeSphere); trackSphere->setTrackerMode(osgGA::NodeTrackerManipulator::NODE_CENTER); transformAregne->setUpdateCallback(new Deplacement); viewer.setSceneData(scene); osg::ref_ptr<GestionEvenements> gestionnaire = new GestionEvenements(); viewer.addEventHandler(gestionnaire.get()); return viewer.run(); }
bool HeightFieldCache::getOrCreateHeightField(const MapFrame& frame, const TileKey& key, //bool cummulative, const osg::HeightField* parent_hf, osg::ref_ptr<osg::HeightField>& out_hf, bool& out_isFallback, ElevationSamplePolicy samplePolicy, ElevationInterpolation interp, ProgressCallback* progress ) { // default out_isFallback = false; // check the quick cache. HFKey cachekey; cachekey._key = key; cachekey._revision = frame.getRevision(); cachekey._samplePolicy = samplePolicy; if (progress) progress->stats()["hfcache_try_count"] += 1; bool hit = false; LRUCache<HFKey,HFValue>::Record rec; if ( _cache.get(cachekey, rec) ) { out_hf = rec.value()._hf.get(); out_isFallback = rec.value()._isFallback; if (progress) { progress->stats()["hfcache_hit_count"] += 1; progress->stats()["hfcache_hit_rate"] = progress->stats()["hfcache_hit_count"]/progress->stats()["hfcache_try_count"]; } return true; } // Find the parent tile and start with its heightfield. if ( parent_hf ) { TileKey parentKey = key.createParentKey(); out_hf = HeightFieldUtils::createSubSample( parent_hf, parentKey.getExtent(), key.getExtent(), interp ); if ( !out_hf.valid() && ((int)key.getLOD())-1 > _firstLOD ) { // This most likely means that a parent tile expired while we were building the child. // No harm done in that case as this tile will soo be discarded as well. OE_DEBUG << "MP HFC: Unable to find tile " << key.str() << " in the live tile registry" << std::endl; return false; } } if ( !out_hf.valid() ) { //TODO. // This sets the elevation tile size; query size for all tiles. out_hf = HeightFieldUtils::createReferenceHeightField( key.getExtent(), _tileSize, _tileSize, true ); } bool populated = frame.populateHeightField( out_hf, key, true, // convertToHAE samplePolicy, progress ); // Treat Plate Carre specially by scaling the height values. (There is no need // to do this with an empty heightfield) const MapInfo& mapInfo = frame.getMapInfo(); if ( mapInfo.isPlateCarre() ) { HeightFieldUtils::scaleHeightFieldToDegrees( out_hf.get() ); } // cache it. HFValue cacheval; cacheval._hf = out_hf.get(); cacheval._isFallback = !populated; _cache.insert( cachekey, cacheval ); out_isFallback = !populated; return true; }
void SpecialMatrix::MatrixViewer::exchangeNodes( osg::ref_ptr<Data::Node> srcNode, osg::ref_ptr<Data::Node> desNode ) { if ( srcNode->Data::AbsNode::getName().contains( 'x' ) && desNode->Data::AbsNode::getName().contains( 'y' ) ) { return; } if ( srcNode->Data::AbsNode::getName().contains( 'y' ) && desNode->Data::AbsNode::getName().contains( 'x' ) ) { return; } int separator = Util::ApplicationConfig::get()->getValue( "Viewer.Display.MatrixNodeSeparator" ).toInt(); osg::ref_ptr<Data::Node> tempNode, foundNode; osg::Vec3f diffVector, finalPosVector; osg::Vec2f iNodeOldPos, iNodeNewPos; qlonglong foundNodeId; int srcNodePos, desNodePos, diff; if ( desNodePos < srcNodePos ) { tempNode = desNode; desNode = srcNode; srcNode = tempNode; } diff = desNodePos - srcNodePos; //srcNode, desNode are axisNodes if ( srcNode->Data::AbsNode::getName().contains( 'x' ) ) { srcNodePos = connections->getXAxisNodes()->indexOf( srcNode->getId() )+1; desNodePos = connections->getXAxisNodes()->indexOf( desNode->getId() )+1; connections->getXAxisNodes()->swap( srcNodePos, desNodePos ); diffVector = osg::Vec3f( static_cast<float>( diff*separator ), 0.0f, 0.0f ); } else { srcNodePos = connections->getYAxisNodes()->indexOf( srcNode->getId() )+1; desNodePos = connections->getYAxisNodes()->indexOf( desNode->getId() )+1; connections->getYAxisNodes()->swap( srcNodePos, desNodePos ); diffVector = osg::Vec3f( 0.0f, static_cast<float>( diff*separator ), 0.0f ); } //Src +diff QList<qlonglong>* connToSrcNodes = connections->getConnectedNodes()->value( srcNode->getId() ); for ( int i=0; i<connToSrcNodes->size(); ++i ) { //get the nodes connected to scrNode tempNode = matrixGraph->findNodeById( connToSrcNodes->indexOf( i ) ); //get the old position of the iNode, and delete from the positionArray iNodeOldPos.set( tempNode->getTargetPosition().x()/separator, tempNode->getTargetPosition().y()/separator ); connections->setNodePositionsArrayField( iNodeOldPos.x(), iNodeOldPos.y(), 0 ); //get the new position finalPosVector = tempNode->getTargetPosition() + diffVector; iNodeNewPos.set( static_cast<int>( finalPosVector.x()/separator ), static_cast<int>( finalPosVector.y()/separator ) ); //CHECK AVAIBILITY foundNodeId = connections->getNodePositionsArrayField( iNodeNewPos.x(), iNodeNewPos.y() ); if ( foundNodeId ) { foundNode = matrixGraph->findNodeById( foundNodeId ); osg::Vec2f foundNodePos = fileParser->getAvailablePosition( connections, iNodeNewPos.x(), iNodeNewPos.y() ); foundNode->setTargetPosition( osg::Vec3f( static_cast<float>( foundNodePos.x()*separator ), static_cast<float>( foundNodePos.y()*separator ), 0.0f ) ); connections->setNodePositionsArrayField( foundNodePos.x(), foundNodePos.y(), foundNodeId ); } tempNode->setTargetPosition( finalPosVector ); tempNode->setRestrictedTargetPosition( tempNode->getTargetPosition() ); connections->setNodePositionsArrayField( iNodeNewPos.x(), iNodeNewPos.y(), tempNode->getId() ); } srcNode->setTargetPosition( srcNode->getTargetPosition() + diffVector ); srcNode->setRestrictedTargetPosition( srcNode->getTargetPosition() ); if ( srcNode->Data::AbsNode::getName().contains( 'x' ) ) { connections->setNodePositionsArrayField( desNodePos, 0, srcNode->getId() ); } else { connections->setNodePositionsArrayField( 0, desNodePos, srcNode->getId() ); } //Des -diff QList<qlonglong>* connToDesNodes = connections->getConnectedNodes()->value( desNode->getId() ); for ( int i=0; i<connToDesNodes->size(); ++i ) { //get the nodes connected to scrNode tempNode = matrixGraph->findNodeById( connToDesNodes->indexOf( i ) ); //get the old position of the iNode, and delete from the positionArray iNodeOldPos.set( tempNode->getTargetPosition().x()/separator, tempNode->getTargetPosition().y()/separator ); connections->setNodePositionsArrayField( iNodeOldPos.x(), iNodeOldPos.y(), 0 ); //get the new position finalPosVector = tempNode->getTargetPosition() - diffVector; iNodeNewPos.set( static_cast<int>( finalPosVector.x()/separator ), static_cast<float>( finalPosVector.y()/separator ) ); //CHECK AVAIBILITY foundNodeId = connections->getNodePositionsArrayField( iNodeNewPos.x(), iNodeNewPos.y() ); if ( foundNodeId ) { foundNode = matrixGraph->findNodeById( foundNodeId ); osg::Vec2f foundNodePos = fileParser->getAvailablePosition( connections, iNodeNewPos.x(), iNodeNewPos.y() ); foundNode->setTargetPosition( osg::Vec3f( static_cast<float>( foundNodePos.x()*separator ), static_cast<float>( foundNodePos.y()*separator ), 0.0f ) ); connections->setNodePositionsArrayField( foundNodePos.x(), foundNodePos.y(), foundNodeId ); } tempNode->setTargetPosition( finalPosVector ); tempNode->setRestrictedTargetPosition( tempNode->getTargetPosition() ); connections->setNodePositionsArrayField( iNodeNewPos.x(), iNodeNewPos.y(), tempNode->getId() ); } desNode->setTargetPosition( desNode->getTargetPosition() - diffVector ); desNode->setRestrictedTargetPosition( desNode->getTargetPosition() ); if ( desNode->Data::AbsNode::getName().contains( 'x' ) ) { connections->setNodePositionsArrayField( srcNodePos, 0, desNode->getId() ); } else { connections->setNodePositionsArrayField( 0, srcNodePos, desNode->getId() ); } }
// - CreateHUD ----------------------------------------------------------------- osg::ref_ptr<osg::Projection> CreateHUD(int width, int height) { // Create the text nodes to be displayed on the HUD osg::ref_ptr<osg::Geode> hudGeometry(new osg::Geode()); TextMouseOver = new osgText::Text(); TextMouseOver->setDataVariance(osg::Object::DYNAMIC); TextMouseOver->setText("Mouse over nothing!"); TextMouseOver->setFont("Data/bluehigl.ttf"); TextMouseOver->setPosition(osg::Vec3 (10.0f, 10.0f, 0.0f)); TextMouseOver->setCharacterSize(25.0); hudGeometry->addDrawable(TextMouseOver); TextMouseWheelEvent = new osgText::Text(); TextMouseWheelEvent->setDataVariance(osg::Object::DYNAMIC); TextMouseWheelEvent->setText("Waiting for mouse wheel event"); TextMouseWheelEvent->setFont("Data/bluehigl.ttf"); TextMouseWheelEvent->setPosition(osg::Vec3 (10.0f, 40.0f, 0.0f)); TextMouseWheelEvent->setCharacterSize(25.0); hudGeometry->addDrawable(TextMouseWheelEvent); TextKeyboardEvent = new osgText::Text(); TextKeyboardEvent->setDataVariance(osg::Object::DYNAMIC); TextKeyboardEvent->setText("Waiting for keyboard event"); TextKeyboardEvent->setFont("Data/bluehigl.ttf"); TextKeyboardEvent->setPosition(osg::Vec3 (10.0f, 70.0f, 0.0f)); TextKeyboardEvent->setCharacterSize(25.0); hudGeometry->addDrawable(TextKeyboardEvent); TextMouseWheelFocusPolicy = new osgText::Text(); TextMouseWheelFocusPolicy->setDataVariance(osg::Object::DYNAMIC); TextMouseWheelFocusPolicy->setText( "Mouse wheel focus policy: mouse down sets focus"); TextMouseWheelFocusPolicy->setFont("Data/bluehigl.ttf"); TextMouseWheelFocusPolicy->setPosition(osg::Vec3(10.0f, 100.0f, 0.0f)); TextMouseWheelFocusPolicy->setCharacterSize(25.0); hudGeometry->addDrawable(TextMouseWheelFocusPolicy); TextKeyboardFocusPolicy = new osgText::Text(); TextKeyboardFocusPolicy->setDataVariance(osg::Object::DYNAMIC); TextKeyboardFocusPolicy->setText( "Keyboard focus policy: mouse over sets focus"); TextKeyboardFocusPolicy->setFont("Data/bluehigl.ttf"); TextKeyboardFocusPolicy->setPosition(osg::Vec3 (10.0f, 130.0f, 0.0f)); TextKeyboardFocusPolicy->setCharacterSize(25.0); hudGeometry->addDrawable(TextKeyboardFocusPolicy); // Create the HUD per se osg::ref_ptr<osg::StateSet> stateSet = hudGeometry->getOrCreateStateSet(); stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF); stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF); stateSet->setRenderBinDetails(11, "RenderBin"); osg::ref_ptr<osg::MatrixTransform> modelviewAbs(new osg::MatrixTransform); modelviewAbs->setReferenceFrame(osg::Transform::ABSOLUTE_RF); modelviewAbs->setMatrix(osg::Matrix::identity()); modelviewAbs->addChild(hudGeometry); osg::ref_ptr<osg::Projection> projection(new osg::Projection()); projection->setMatrix(osg::Matrix::ortho2D(0, width, 0, height)); projection->addChild(modelviewAbs); return projection; }
static RenderBinPrototypeList* renderBinPrototypeList() { static osg::ref_ptr<RenderBinPrototypeList> s_renderBinPrototypeList = new RenderBinPrototypeList; return s_renderBinPrototypeList.get(); }
void HandleMouseLeave(OSGUIsh::HandlerParams& params) { TextMouseOver->setText("Mouse over nothing!"); }
void Storage::fillVertexBuffers (int lodLevel, float size, const osg::Vec2f& center, osg::ref_ptr<osg::Vec3Array> positions, osg::ref_ptr<osg::Vec3Array> normals, osg::ref_ptr<osg::Vec4Array> colours) { // LOD level n means every 2^n-th vertex is kept size_t increment = 1 << lodLevel; osg::Vec2f origin = center - osg::Vec2f(size/2.f, size/2.f); assert(origin.x() == (int) origin.x()); assert(origin.y() == (int) origin.y()); int startX = static_cast<int>(origin.x()); int startY = static_cast<int>(origin.y()); size_t numVerts = static_cast<size_t>(size*(ESM::Land::LAND_SIZE - 1) / increment + 1); positions->resize(numVerts*numVerts); normals->resize(numVerts*numVerts); colours->resize(numVerts*numVerts); osg::Vec3f normal; osg::Vec4f color; float vertY = 0; float vertX = 0; float vertY_ = 0; // of current cell corner for (int cellY = startY; cellY < startY + std::ceil(size); ++cellY) { float vertX_ = 0; // of current cell corner for (int cellX = startX; cellX < startX + std::ceil(size); ++cellX) { ESM::Land* land = getLand(cellX, cellY); if (land && !(land->mDataTypes&ESM::Land::DATA_VHGT)) land = NULL; int rowStart = 0; int colStart = 0; // Skip the first row / column unless we're at a chunk edge, // since this row / column is already contained in a previous cell if (colStart == 0 && vertY_ != 0) colStart += increment; if (rowStart == 0 && vertX_ != 0) rowStart += increment; vertY = vertY_; for (int col=colStart; col<ESM::Land::LAND_SIZE; col += increment) { vertX = vertX_; for (int row=rowStart; row<ESM::Land::LAND_SIZE; row += increment) { float height = -2048; if (land) height = land->mLandData->mHeights[col*ESM::Land::LAND_SIZE + row]; (*positions)[static_cast<unsigned int>(vertX*numVerts + vertY)] = osg::Vec3f((vertX / float(numVerts - 1) - 0.5f) * size * 8192, (vertY / float(numVerts - 1) - 0.5f) * size * 8192, height); if (land && land->mDataTypes&ESM::Land::DATA_VNML) { normal.x() = land->mLandData->mNormals[col*ESM::Land::LAND_SIZE*3+row*3]; normal.y() = land->mLandData->mNormals[col*ESM::Land::LAND_SIZE*3+row*3+1]; normal.z() = land->mLandData->mNormals[col*ESM::Land::LAND_SIZE*3+row*3+2]; normal.normalize(); } else normal = osg::Vec3f(0,0,1); // Normals apparently don't connect seamlessly between cells if (col == ESM::Land::LAND_SIZE-1 || row == ESM::Land::LAND_SIZE-1) fixNormal(normal, cellX, cellY, col, row); // some corner normals appear to be complete garbage (z < 0) if ((row == 0 || row == ESM::Land::LAND_SIZE-1) && (col == 0 || col == ESM::Land::LAND_SIZE-1)) averageNormal(normal, cellX, cellY, col, row); assert(normal.z() > 0); (*normals)[static_cast<unsigned int>(vertX*numVerts + vertY)] = normal; if (land && land->mDataTypes&ESM::Land::DATA_VCLR) { color.r() = land->mLandData->mColours[col*ESM::Land::LAND_SIZE*3+row*3] / 255.f; color.g() = land->mLandData->mColours[col*ESM::Land::LAND_SIZE*3+row*3+1] / 255.f; color.b() = land->mLandData->mColours[col*ESM::Land::LAND_SIZE*3+row*3+2] / 255.f; } else { color.r() = 1; color.g() = 1; color.b() = 1; } // Unlike normals, colors mostly connect seamlessly between cells, but not always... if (col == ESM::Land::LAND_SIZE-1 || row == ESM::Land::LAND_SIZE-1) fixColour(color, cellX, cellY, col, row); color.a() = 1; (*colours)[static_cast<unsigned int>(vertX*numVerts + vertY)] = color; ++vertX; } ++vertY; } vertX_ = vertX; } vertY_ = vertY; assert(vertX_ == numVerts); // Ensure we covered whole area } assert(vertY_ == numVerts); // Ensure we covered whole area }
void HandleKeyUp (OSGUIsh::HandlerParams& params) { TextKeyboardEvent->setText(params.node->getName() + ": key up: " + static_cast<char>(params.event.getKey())); }
static NoesisSystemManager* instance() { static osg::ref_ptr<NoesisSystemManager> s_instance = new NoesisSystemManager; return s_instance.get(); }
void SlideEventHandler::scaleImage(float s) { _texmatLeft->setMatrix(_texmatLeft->getMatrix()*osg::Matrix::translate(-0.5f,-0.5f,0.0f)*osg::Matrix::scale(s,s,1.0f)*osg::Matrix::translate(0.5f,0.5f,0.0f)); _texmatRight->setMatrix(_texmatRight->getMatrix()*osg::Matrix::translate(-0.5f,-0.5f,0.0f)*osg::Matrix::scale(s,s,1.0f)*osg::Matrix::translate(0.5f,0.5f,0.0f)); }
bool Geometry::buffer(double distance, osg::ref_ptr<Geometry>& output, const BufferParameters& params ) const { #ifdef OSGEARTH_HAVE_GEOS GEOSContext gc; geom::Geometry* inGeom = gc.importGeometry( this ); if ( inGeom ) { buffer::BufferParameters::EndCapStyle geosEndCap = params._capStyle == BufferParameters::CAP_ROUND ? buffer::BufferParameters::CAP_ROUND : params._capStyle == BufferParameters::CAP_SQUARE ? buffer::BufferParameters::CAP_SQUARE : params._capStyle == BufferParameters::CAP_FLAT ? buffer::BufferParameters::CAP_FLAT : buffer::BufferParameters::CAP_SQUARE; buffer::BufferParameters::JoinStyle geosJoinStyle = params._joinStyle == BufferParameters::JOIN_ROUND ? buffer::BufferParameters::JOIN_ROUND : params._joinStyle == BufferParameters::JOIN_MITRE ? buffer::BufferParameters::JOIN_MITRE : params._joinStyle == BufferParameters::JOIN_BEVEL ? buffer::BufferParameters::JOIN_BEVEL : buffer::BufferParameters::JOIN_ROUND; //JB: Referencing buffer::BufferParameters::DEFAULT_QUADRANT_SEGMENTS causes link errors b/c it is defined as a static in the header of BufferParameters.h and not defined in the cpp anywhere. // This seems to only effect the Linux build, Windows works fine int geosQuadSegs = params._cornerSegs > 0 ? params._cornerSegs : 8; //buffer::BufferParameters::DEFAULT_QUADRANT_SEGMENTS; geom::Geometry* outGeom = NULL; buffer::BufferParameters geosBufferParams; geosBufferParams.setQuadrantSegments( geosQuadSegs ); geosBufferParams.setEndCapStyle( geosEndCap ); geosBufferParams.setJoinStyle( geosJoinStyle ); buffer::BufferBuilder bufBuilder( geosBufferParams ); try { if (params._singleSided) { outGeom = bufBuilder.bufferLineSingleSided(inGeom, distance, params._leftSide); } else { outGeom = bufBuilder.buffer(inGeom, distance); } } catch(const geos::util::GEOSException& ex) { OE_NOTICE << LC << "buffer(GEOS): " << (ex.what()? ex.what() : " no error message") << std::endl; outGeom = 0L; } bool sharedFactory = inGeom && outGeom && inGeom->getFactory() == outGeom->getFactory(); if ( outGeom ) { output = gc.exportGeometry( outGeom ); gc.disposeGeometry( outGeom ); } gc.disposeGeometry( inGeom ); } return output.valid(); #else // OSGEARTH_HAVE_GEOS OE_WARN << LC << "Buffer failed - GEOS not available" << std::endl; return false; #endif // OSGEARTH_HAVE_GEOS }
void SlideEventHandler::initTexMatrices() { _texmatLeft->setMatrix(osg::Matrix::translate(_initSeperationX,_initSeperationY,0.0f)); _texmatRight->setMatrix(osg::Matrix::translate(-_initSeperationX,-_initSeperationY,0.0f)); }
void ComputeNode::initComputingSetup() { _computeProgram = new osg::Program; _computeProgram->setComputeGroups((NUM_ELEMENTS_X / WORK_GROUP_SIZE) <= 1 ? 1 : (NUM_ELEMENTS_X / WORK_GROUP_SIZE), (NUM_ELEMENTS_Y / WORK_GROUP_SIZE) <= 1 ? 1 : (NUM_ELEMENTS_Y / WORK_GROUP_SIZE), 1); _computeShader = osg::Shader::readShaderFile(osg::Shader::COMPUTE, _computeShaderSourcePath); _computeProgram->addShader(_computeShader.get()); setDataVariance(osg::Object::DYNAMIC); osg::StateSet* statesetComputation = getOrCreateStateSet(); statesetComputation->setAttributeAndModes(_computeProgram.get()); statesetComputation->addUniform(new osg::Uniform("numCols", (int)NUM_ELEMENTS_X)); statesetComputation->addUniform(new osg::Uniform("numRows", (int)NUM_ELEMENTS_Y)); statesetComputation->setMode(GL_LIGHTING, osg::StateAttribute::OFF); //blocksize int numParticles = NUM_ELEMENTS_X * NUM_ELEMENTS_Y; const unsigned blockSize = numParticles * __numChannels * __numDataValuesPerChannel* sizeof(GLfloat); //init all the particle data array int idx = 0; _data = new GLfloat[NUM_ELEMENTS_X * NUM_ELEMENTS_Y * __numChannels * __numDataValuesPerChannel]; _dataArray = new FloatArray; //init the data array somehow, this way all is stored in one BufferObject. maybe better using multiple buffers instead? not sure what is faster and better for threading for (int d = 0; d < __numDataValuesPerChannel; ++d) { for (int i = 0; i < NUM_ELEMENTS_X; ++i) { for (int j = 0; j < NUM_ELEMENTS_Y; ++j) { for (int k = 0; k < __numChannels; ++k) { switch (k) { case (RED_CHANNEL) : { if ((d == POSITION_NOW_OFFSET) || (d == POSITION_OLD_OFFSET) || (d == POSITION_INIT_OFFSET))//position { *_data = random(0.25, 0.75); } if ((d == VELOCITY_NOW_OFFSET) || (d == VELOCITY_OLD_OFFSET) || (d == VELOCITY_INIT_OFFSET))//velocity { *_data = random(-2.4, 2.4); } if (d == ACCELERATION_OFFSET) //acceleration { *_data = random(-3.0, 3.0); } if (d == PROPERTIES_OFFSET) //property particle mass (compute shader is computing sphere mass from radius instead) { *_data = random(0.2, 15.0); } break; } case (GREEN_CHANNEL) : { if ((d == POSITION_NOW_OFFSET) || (d == POSITION_OLD_OFFSET) || (d == POSITION_INIT_OFFSET))//position { *_data = random(0.25, 0.75); } if ((d == VELOCITY_NOW_OFFSET) || (d == VELOCITY_OLD_OFFSET) || (d == VELOCITY_INIT_OFFSET))//velocity { *_data = random(-2.4, 2.4); } if (d == ACCELERATION_OFFSET)//acceleration { *_data = random(-3.0, 3.0); } if (d == PROPERTIES_OFFSET) //property particle radius { *_data = random(0.07, 0.219); } break; } case (BLUE_CHANNEL) : { if ((d == POSITION_NOW_OFFSET) || (d == POSITION_OLD_OFFSET) || (d == POSITION_INIT_OFFSET))//position { *_data = random(0.25, 0.75); } if ((d == VELOCITY_NOW_OFFSET) || (d == VELOCITY_OLD_OFFSET) || (d == VELOCITY_INIT_OFFSET))//velocity { *_data = random(-2.4, 2.4); } if (d == ACCELERATION_OFFSET)//acceleration { *_data = random(-3.0, 3.0); } if (d == PROPERTIES_OFFSET) //place for some other property { *_data = random(0.0, 0.0); } break; } case (ALPHA_CHANNEL) : { if ((d == POSITION_NOW_OFFSET) || (d == POSITION_OLD_OFFSET) || (d == POSITION_INIT_OFFSET))//position { *_data = random(1.0, 1.0); } if ((d == VELOCITY_NOW_OFFSET) || (d == VELOCITY_OLD_OFFSET) || (d == VELOCITY_INIT_OFFSET))//velocity { *_data = random(-2.4, 2.4); } if (d == ACCELERATION_OFFSET) //acceleration { //*_data = random(1.0, 1.0); *_data = random(0.0, 0.0); } if (d == PROPERTIES_OFFSET) //place for some other property { *_data = random(0.3, 0.3); } break; } } _dataArray->push_back(*_data); _data++; idx++; } } } } _ssbo = new osg::ShaderStorageBufferObject; _dataArray->setBufferObject(_ssbo.get()); _ssbb = new osg::ShaderStorageBufferBinding(0, _dataArray.get(), 0, blockSize); statesetComputation->setAttributeAndModes(_ssbb.get(), osg::StateAttribute::ON); //option, do something useful with data or test the transfer speed //_ssbb->setUpdateCallback(new ShaderStorageBufferCallback); //adding a quad , visualizing data in buffer addDataMonitor(osg::Vec3(0, -1, 0), osg::Vec3(SUB_PLACEMENT_OFFSET_HORIZONTAL * 0, -SUB_PLACEMENT_OFFSET_VERTICAL * -2.0, SUB_PLACEMENT_OFFSET_HORIZONTAL * 0), 1.0, RGB_CHANNEL, POSITION_NOW_OFFSET, "X,Y,Z - PositionNow", -1.0, 1.0); //the coord from default dataset addHelperGeometry(); addComputationResultsRenderTree(); }