• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ osg::ref_ptr类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中osg::ref_ptr的典型用法代码示例。如果您正苦于以下问题:C++ ref_ptr类的具体用法?C++ ref_ptr怎么用?C++ ref_ptr使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了ref_ptr类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: StateSet

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;
//.........这里部分代码省略.........
开发者ID:rhabacker,项目名称:osgearth,代码行数:101,代码来源:ShaderGenerator.cpp


示例2: createImage


//.........这里部分代码省略.........
        // 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;
    }
开发者ID:Sylla,项目名称:osgearth,代码行数:101,代码来源:BingTileSource.cpp


示例3: getGlobalFadeText

GlobalFadeText* getGlobalFadeText()
{
    static osg::ref_ptr<GlobalFadeText> s_globalFadeText = new GlobalFadeText;
    return s_globalFadeText.get();
}
开发者ID:LaurensVoerman,项目名称:OpenSceneGraph,代码行数:5,代码来源:FadeText.cpp


示例4: AddModelNode

// Add model to scene
void ViewerQT::AddModelNode(osg::ref_ptr<osg::Node> mnode)
{
    m_rpSceneGroupRoot->addChild(mnode.get());
}
开发者ID:onism,项目名称:GTea,代码行数:5,代码来源:AdapterWidget.cpp


示例5: main

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();
//.........这里部分代码省略.........
开发者ID:yueying,项目名称:osg,代码行数:101,代码来源:osgmanipulator.cpp


示例6: instance

 static FlexUpdater* instance()
 {
     static osg::ref_ptr<FlexUpdater> s_instance = new FlexUpdater;
     return s_instance.get();
 }
开发者ID:whztt07,项目名称:test_osg,代码行数:5,代码来源:FlexDrawable.cpp


示例7: catch

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
}
开发者ID:3dcl,项目名称:osgearth,代码行数:72,代码来源:Geometry.cpp


示例8: main

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!
//.........这里部分代码省略.........
开发者ID:BackupTheBerlios,项目名称:yag2002-svn,代码行数:101,代码来源:vrc_playeranim.cpp


示例9: main

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());
//.........这里部分代码省略.........
开发者ID:ClementCvl,项目名称:CppMasterRace_50yIUT,代码行数:101,代码来源:main.cpp


示例10:

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;
}
开发者ID:Geo12,项目名称:osgearth,代码行数:92,代码来源:HeightFieldCache.cpp


示例11:

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' ) ) {
//.........这里部分代码省略.........
开发者ID:kapecp,项目名称:3dsoftviz,代码行数:101,代码来源:MatrixViewer.cpp


示例12: CreateHUD

// - 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;
}
开发者ID:lmbarros,项目名称:OSGUIsh,代码行数:66,代码来源:FocusPolicies.cpp


示例13: renderBinPrototypeList

static RenderBinPrototypeList* renderBinPrototypeList()
{
    static osg::ref_ptr<RenderBinPrototypeList> s_renderBinPrototypeList = new  RenderBinPrototypeList;
    return s_renderBinPrototypeList.get();
}
开发者ID:seafengl,项目名称:osg-by-google,代码行数:5,代码来源:RenderBin.cpp


示例14: fillVertexBuffers

    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);

//.........这里部分代码省略.........
开发者ID:ace13,项目名称:openmw,代码行数:101,代码来源:storage.cpp


示例15: instance

该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ osgdb::Input类代码示例发布时间:2022-05-31
下一篇:
C++ osg::observer_ptr类代码示例发布时间:2022-05-31
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap