osgEarth示例分析——osgearth_los

前言

osgearth_los示例,创建了模型动画路径、透视的用法。透视的顾名思义:两个点连线,从A到B,视线不被遮挡,则绘制绿色,视线被遮挡的部分,则设置为红色。此示例,加载earth文件时,需要加载地形文件。

执行命令:osgearth_losd.exe earth_image\world.earth

效果

圆形内的飞机,整个圆形,如果被遮挡,则绘制红色,不被遮挡,则绘制绿色。直线连接的两个飞机,从左下角的飞机点向右上角的飞机点看去,当被遮挡后,则后面的线都绘制红色。最下面的两个扫描圆形也是如此。

 代码分析

#include <osg/Notify>
#include <osgGA/StateSetManipulator>
#include <osgGA/GUIEventHandler>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgEarth/MapNode>
#include <osgEarth/XmlUtils>
#include <osgEarthUtil/EarthManipulator>
#include <osgEarthUtil/AutoClipPlaneHandler>
#include <osgEarthUtil/LinearLineOfSight>
#include <osgEarthUtil/RadialLineOfSight>
#include <osg/io_utils>
#include <osg/MatrixTransform>
#include <osg/Depth>
#include <osgEarth/TerrainTileNode>
#include <osgEarth/FileUtils>

using namespace osgEarth;
using namespace osgEarth::Util;

// 运动路径
osg::AnimationPath* createAnimationPath(const GeoPoint& pos, const SpatialReference* mapSRS, float radius, double looptime)
{
    // set up the animation path 
    osg::AnimationPath* animationPath = new osg::AnimationPath;// 设置动画路径对象
    animationPath->setLoopMode(osg::AnimationPath::LOOP);// 循环播放模式
    
    int numSamples = 40;// 采样点数

    double delta = osg::PI * 2.0 / (double)numSamples;

    //Get the center point in geocentric 获取大地测量坐标系下的中心点
    GeoPoint mapPos = pos.transform(mapSRS);
    osg::Vec3d centerWorld;
    mapPos.toWorld( centerWorld );

	// 是否为投影坐标系
    bool isProjected = mapSRS->isProjected();

	// 设置向上向量
    osg::Vec3d up = isProjected ? osg::Vec3d(0,0,1) : centerWorld;
    up.normalize();

    //Get the "side" vector 获取side向量
    osg::Vec3d side = isProjected ? osg::Vec3d(1,0,0) : up ^ osg::Vec3d(0,0,1);

	// 时间间隔
    double time=0.0f;
    double time_delta = looptime/(double)numSamples;

	// 第一个位置、第一个旋转矩阵
    osg::Vec3d firstPosition;
    osg::Quat firstRotation;

    for (unsigned int i = 0; i < (unsigned int)numSamples; i++)
    {
        double angle = delta * (double)i;
        osg::Quat quat(angle, up );
        osg::Vec3d spoke = quat * (side * radius);
        osg::Vec3d end = centerWorld + spoke;                

        osg::Quat makeUp;
        makeUp.makeRotate(osg::Vec3d(0,0,1), up);

        osg::Quat rot = makeUp;
        animationPath->insert(time,osg::AnimationPath::ControlPoint(end,rot));// 插入时间和控制点
        if (i == 0)
        {
            firstPosition = end;
            firstRotation = rot;
        }
        time += time_delta;            
    }
   
    animationPath->insert(time, osg::AnimationPath::ControlPoint(firstPosition, firstRotation));// 插入最后一个点

    return animationPath;    // 返回路径动画
}

// 调用 创建路径动画方法,且将路径动画对象放入 位置矩阵,并为 位置矩阵 设置更新回调
osg::Node* createPlane(osg::Node* node, const GeoPoint& pos, const SpatialReference* mapSRS, double radius, double time)
{
    osg::MatrixTransform* positioner = new osg::MatrixTransform;
    positioner->addChild( node );
    osg::AnimationPath* animationPath = createAnimationPath(pos, mapSRS, radius, time);
    positioner->setUpdateCallback( new osg::AnimationPathCallback(animationPath, 0.0, 1.0));
    return positioner;
}

// 存储ExtentNode访问器??
class CacheExtentNodeVisitor : public osg::NodeVisitor
{
public:
    CacheExtentNodeVisitor(GeoExtent& extent):
      osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN ),
          _extent(extent)
      {
      }

      void apply(osg::Node& node)
      {
          TerrainTileNode* tile = dynamic_cast<TerrainTileNode*>(&node);
          if (tile && tile->getKey().valid())
          {              
              if (tile->getKey().getExtent().intersects(_extent) && tile->getKey().getLevelOfDetail() < 11)
              {
                  // Set this tile to not expire.
                  tile->setMinimumExpirationTime(DBL_MAX);
                  OE_NOTICE << "Preloading children for " << tile->getKey().str() << std::endl;
                  tile->loadChildren();
              }
          }          
          traverse(node);
      }

      GeoExtent _extent;
};


int
main(int argc, char** argv)
{
    osg::ArgumentParser arguments(&argc,argv);
    osgViewer::Viewer viewer(arguments);

    // load the .earth file from the command line.
    osg::ref_ptr<osg::Node> earthNode = osgDB::readNodeFiles( arguments );
    if (!earthNode.valid())
    {
        OE_NOTICE << "Unable to load earth model" << std::endl;
        return 1;
    }

    osg::Group* root = new osg::Group();

    osgEarth::MapNode * mapNode = osgEarth::MapNode::findMapNode( earthNode.get() );
    if (!mapNode)
    {
        OE_NOTICE << "Could not find MapNode " << std::endl;
        return 1;
    }

    osgEarth::Util::EarthManipulator* manip = new EarthManipulator();
    viewer.setCameraManipulator( manip );
    
    root->addChild( earthNode );    
    //viewer.getCamera()->addCullCallback( new AutoClipPlaneCullCallback(mapNode));

    osg::Group* losGroup = new osg::Group();
    losGroup->getOrCreateStateSet()->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);// 渲染方式:透明
    losGroup->getOrCreateStateSet()->setAttributeAndModes(new osg::Depth(osg::Depth::ALWAYS, 0, 1, false));
    root->addChild(losGroup);

    // so we can speak lat/long:
    const SpatialReference* mapSRS = mapNode->getMapSRS();
    const SpatialReference* geoSRS = mapSRS->getGeographicSRS();// 地理坐标系

    //Create a point to point LineOfSightNode.
	// 创建 可用于显示点对点视线计算的节点los
    LinearLineOfSightNode* los = new LinearLineOfSightNode(
        mapNode, 
        GeoPoint(geoSRS, -121.665, 46.0878, 1258.00, ALTMODE_ABSOLUTE),
        GeoPoint(geoSRS, -121.488, 46.2054, 3620.11, ALTMODE_ABSOLUTE) );

    losGroup->addChild( los );
    
    //Create an editor for the point to point line of sight that allows you to drag the beginning and end points around.
    //This is just one way that you could manipulator the LineOfSightNode.
	// 为los添加编辑器
    LinearLineOfSightEditor* p2peditor = new LinearLineOfSightEditor( los );
    root->addChild( p2peditor );

    //Create a relative point to point LineOfSightNode.
	// 再创建一个比los低一些的 relativeLOS
    LinearLineOfSightNode* relativeLOS = new LinearLineOfSightNode( 
        mapNode, 
        GeoPoint(geoSRS, -121.2, 46.1, 10, ALTMODE_RELATIVE),
        GeoPoint(geoSRS, -121.488, 46.2054, 10, ALTMODE_RELATIVE) );

    losGroup->addChild( relativeLOS );

	// 为 relativeLOS 添加编辑器
    LinearLineOfSightEditor* relEditor = new LinearLineOfSightEditor( relativeLOS );
    root->addChild( relEditor );

    //Create a RadialLineOfSightNode that allows you to do a 360 degree line of sight analysis.
	// 可用于显示径向视线计算的节点 radial
	// radial 允许进行360度视线分析。
    RadialLineOfSightNode* radial = new RadialLineOfSightNode( mapNode );
    radial->setCenter( GeoPoint(geoSRS, -121.515, 46.054, 847.604, ALTMODE_ABSOLUTE) );
    radial->setRadius( 2000 );
    radial->setNumSpokes( 100 );    // 设置径向视线计算中的轮辐数。
    losGroup->addChild( radial );
	// 为 radial 添加编辑器
    RadialLineOfSightEditor* radialEditor = new RadialLineOfSightEditor( radial );
    losGroup->addChild( radialEditor );

    //Create a relative RadialLineOfSightNode that allows you to do a 360 degree line of sight analysis.
    RadialLineOfSightNode* radialRelative = new RadialLineOfSightNode( mapNode );
    radialRelative->setCenter( GeoPoint(geoSRS, -121.2, 46.054, 10, ALTMODE_RELATIVE) );
    radialRelative->setRadius( 3000 );
    radialRelative->setNumSpokes(60);
    losGroup->addChild( radialRelative );
    RadialLineOfSightEditor* radialRelEditor = new RadialLineOfSightEditor( radialRelative );
    losGroup->addChild( radialRelEditor );

    //Load a plane model.  添加一个飞机模型 cessna赛斯纳,飞行器公司
    osg::ref_ptr< osg::Node >  plane = osgDB::readRefNodeFile("../data/cessna.osgb.50,50,50.scale");

    //Create 2 moving planes 创建两个移动飞机
    osg::Node* plane1 = createPlane(plane.get(), GeoPoint(geoSRS, -121.656, 46.0935, 4133.06, ALTMODE_ABSOLUTE), mapSRS, 5000, 40);
    osg::Node* plane2 = createPlane(plane.get(), GeoPoint(geoSRS, -121.321, 46.2589, 1390.09, ALTMODE_ABSOLUTE), mapSRS, 3000, 25);
    root->addChild( plane1 );
    root->addChild( plane2 );

    //Create a LineOfSightNode that will use a LineOfSightTether callback to monitor
    //the two plane's positions and recompute the LOS when they move
    LinearLineOfSightNode* tetheredLOS = new LinearLineOfSightNode( mapNode);
    losGroup->addChild( tetheredLOS );
    tetheredLOS->setUpdateCallback( new LineOfSightTether( plane1, plane2 ) );

    //Create another plane and attach a RadialLineOfSightNode to it using the RadialLineOfSightTether
    osg::Node* plane3 = createPlane(plane.get(), GeoPoint(geoSRS, -121.463, 46.3548, 1348.71, ALTMODE_ABSOLUTE), mapSRS, 10000, 5);
    losGroup->addChild( plane3 );
    RadialLineOfSightNode* tetheredRadial = new RadialLineOfSightNode( mapNode );
    tetheredRadial->setRadius( 5000 );

    //This RadialLineOfSightNode is going to be filled, so set some alpha values for the colors so it's partially transparent
    tetheredRadial->setFill( true );
    tetheredRadial->setGoodColor( osg::Vec4(0,1,0,0.3) );
    tetheredRadial->setBadColor( osg::Vec4(1,0,0,0.3) );
    tetheredRadial->setNumSpokes( 100 );
    losGroup->addChild( tetheredRadial );
    tetheredRadial->setUpdateCallback( new RadialLineOfSightTether( plane3 ) );

	// 设置视角信息
    osgEarth::Viewpoint vp;
    vp.name() = "Mt Ranier";
    vp.focalPoint()->set(geoSRS, -121.488, 46.2054, 0, ALTMODE_ABSOLUTE);
    vp.pitch() = -50.0;
    vp.range() = 100000;

    manip->setHomeViewpoint( vp );// 设置home视角

    viewer.setSceneData( root );    

    // add some stock OSG handlers:
    viewer.addEventHandler(new osgViewer::StatsHandler());
    viewer.addEventHandler(new osgViewer::WindowSizeHandler());
    viewer.addEventHandler(new osgViewer::ThreadingHandler());
    viewer.addEventHandler(new osgViewer::LODScaleHandler());
    viewer.addEventHandler(new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()));

    /*
    TerrainTileNodeVisitor v;
    root->accept(v);
    */
	// 下面的节点遍历代码,导致程序容易崩溃,暂时没看出这段代码有什么用,所以先注释掉

   // GeoPoint center(geoSRS, -121.656, 46.0935, 4133.06, ALTMODE_ABSOLUTE);

    //GeoExtent extent(geoSRS, center.x() - 0.5, center.y() - 0.5, center.x() + 0.5, center.y() + 0.5);
    //CacheExtentNodeVisitor v(extent);

    //root->accept(v);

    while (!viewer.done())
    {        
        viewer.frame();
    }
    return 0;
}

  • 0
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
osgEarth 的 121 个案例详解 osgEarth 的 121 个案例详解 ...........................................................................................................1 1. aeqd.earth.................................................................................................................................4 2. annotation.earth .......................................................................................................................5 3. annotation_dateline.earth........................................................................................................6 4. annotation_dateline_projected.earth ......................................................................................8 5. annotation_flat.earth................................................................................................................8 6. arcgisonline.earth .....................................................................................................................9 7. bing.earth................................................................................................................................10 8. boston.earth............................................................................................................................11 9. boston_buildings.earth ...........................................................................................................12 10. boston_projected.earth ..................................................................................................13 11. boston_tfs.earth..............................................................................................................14 12. boston-gpu.earth ............................................................................................................15 13. bumpmap.earth ..............................................................................................................16 14. clouds.earth ....................................................................................................................17 15. colorramp.earth ..............................................................................................................18 16. contourmap.earth ...........................................................................................................19 17. datum_override.earth.....................................................................................................20 18. day_night_mp.earth........................................................................................................21 19. day_night_rex.earth........................................................................................................21 20. detail_texture.earth ........................................................................................................21 21. errors.earth .....................................................................................................................22 22. fade_elevation.earth.......................................................................................................22 23. feature_clip_plane.earth.................................................................................................23 24. feature_country_boundaries.earth.................................................................................24 25. feature_custom_filters.earth ..........................................................................................25 26. feature_draped_lines.earth ............................................................................................26 27. feature_draped_polygons.earth .....................................................................................27 28. feature_elevation.earth ..................................................................................................28 29. feature_extrude.earth.....................................................................................................29 30. feature_geom.earth ........................................................................................................30 31. feature_gpx.earth............................................................................................................31 32. feature_inline_geometry.earth.......................................................................................32 33. feature_labels.earth........................................................................................................33 34. feature_labels_script.earth.............................................................................................35 35. feature_levels_and_selectors.earth................................................................................35 36. feature_model_scatter.earth ..........................................................................................36 37. feature_models.earth .....................................................................................................37 38. feature_occlusion_culling.earth......................................................................................38osgEarth 编辑器 SXEarth www.sxsim.com 2 39. feature_offset_polygons.earth .......................................................................................38 40. feature_overlay.earth......................................................................................................39 41. feature_poles.earth.........................................................................................................40 42. feature_population_cylinders.earth ...............................................................................40 43. feature_raster.earth ........................................................................................................41 44. feature_rasterize.earth ...................................................................................................41 45. feature_rasterize_2.earth ...............................................................................................42 46. feature_scripted_styling.earth........................................................................................43 47. feature_scripted_styling_2.earth....................................................................................43 48. feature_scripted_styling_3.earth....................................................................................43 49. feature_style_selector.earth ...........................................................................................44 50. feature_tfs.earth .............................................................................................................45 51. feature_tfs_scripting.earth .............................................................................................46 52. feature_wfs.earth............................................................................................................47 53. fractal_elevation.earth....................................................................................................47 54. gdal_multiple_files.earth ................................................................................................47 55. gdal_tiff.earth..................................................................................................................48 56. geomshader.earth ...........................................................................................................49 57. glsl.earth..........................................................................................................................50 58. glsl_filter.earth ................................................................................................................51 59. graticules.earth ...............................................................................................................52 60. hires-inset.earth..............................................................................................................53 61. intersect_filter.earth .......................................................................................................54 62. land_cover_mixed.earth .................................................................................................55 63. layer_opacity.earth .........................................................................................................55 64. ldb.earth..........................................................................................................................56 65. mapbox.earth..................................................................................................................56 66. mask.earth ......................................................................................................................57 67. mb_tiles.earth.................................................................................................................58 68. mercator_to_plate_carre.earth ......................................................................................59 69. mgrs_graticule.earth.......................................................................................................60 70. min_max_level.earth ......................................................................................................60 71. min_max_range.earth.....................................................................................................61 72. min_max_range_rex.earth..............................................................................................62 73. min_max_resolutions.earth............................................................................................62 74. multiple_heightfields.earth.............................................................................................64 75. night.earth.......................................................................................................................65 76. nodata.earth ...................................................................................................................65 77. noise.earth ......................................................................................................................68 78. normalmap.earth ............................................................................................................68 79. ocean.earth .....................................................................................................................69 80. ocean_no_elevation.earth ..............................................................................................69 81. openstreetmap.earth......................................................................................................69 82. openstreetmap_buildings.earth .....................................................................................70osgEarth 编辑器 SXEarth www.sxsim.com 3 83. openstreetmap_flat.earth...............................................................................................70 84. openstreetmap_full.earth...............................................................................................70 85. openweathermap_clouds.earth......................................................................................71 86. openweathermap_precipitation.earth ...........................................................................71 87. openweathermap_pressure.earth ..................................................................................71 88. photosphere1.earth ........................................................................................................71 89. photosphere2.earth ........................................................................................................72 90. readymap.earth...............................................................................................................73 91. readymap_flat.earth .......................................................................................................73 92. readymap_include.earth.................................................................................................74 93. readymap_template.earth..............................................................................................74 94. readymap-elevation-only.earth.......................................................................................74 95. readymap-osm.earth ......................................................................................................75 96. readymap-priority.earth..................................................................................................75 97. readymap-rex.earth ........................................................................................................75 98. roads.earth......................................................................................................................76 99. roads-flattened.earth......................................................................................................76 100. roads-test.earth...............................................................................................................76 101. scene_clamping.earth.....................................................................................................76 102. silverlining.earth..............................................................................................................78 103. simple_model.earth........................................................................................................78 104. skyview1.earth ................................................................................................................79 105. skyview2.earth ................................................................................................................80 106. splat.earth .......................................................................................................................81 107. splat-blended-with-imagery.earth ..................................................................................81 108. splat-with-mask-layer.earth.............................................................................................81 109. splat-with-multiple-zones.earth......................................................................................82 110. splat-with-rasterized-land-cover.earth............................................................................82 111. stamen_toner.earth ........................................................................................................82 112. stamen_watercolor.earth................................................................................................82 113. state_plane.earth............................................................................................................82 114. tess_screen_space.earth.................................................................................................82 115. tess-coastlines.earth .......................................................................................................82 116. tess-terrain.earth ............................................................................................................83 117. triton.earth......................................................................................................................83 118. triton_drop_shader.earth................................................................................................83 119. utm.earth ........................................................................................................................83 120. utm_graticule.earth ........................................................................................................83 121. vertical_datum.earth ......................................................................................................83 122. wms_nexrad.earth ..........................................................................................................84 123. wms-t_nexrad_animated.earth ......................................................................................84 124. 编辑问题总结....................................................................................错误!未定义书签。
以下是在 Visual Studio 2022 中使用 osgEarth示例: 1. 安装 osgEarth 首先需要在你的系统中安装 osgEarth。可以从官网下载安装包进行安装,也可以使用 CMake 进行源码编译安装。 2. 创建一个 osgEarth 应用程序 在 Visual Studio 2022 中创建一个新的 C++ 控制台应用程序项目。然后,将 osgEarth 的 include 和 library 路径添加到项目中: - 右键单击项目,选择“属性”。 - 在“VC++ 目录”中添加包含路径和库路径。 - 在“链接器 -> 输入”中添加 osgEarth 的库文件。 3. 创建一个 osgEarth 地图节点 在应用程序中创建一个 osgEarth 地图节点,并将其添加到场景图中: ```cpp #include <osgEarth/MapNode> #include <osgEarthUtil/EarthManipulator> int main(int argc, char** argv) { // 初始化 osgEarthosgEarth::initialize(); // 创建一个 osgEarth 地图节点 osg::ref_ptr<osgEarth::MapNode> mapNode = osgEarth::MapNode::create(osgEarth::MapNodeOptions()); // 创建一个 osgEarth 视图并添加地图节点 osg::ref_ptr<osgViewer::View> view = new osgViewer::View; view->setSceneData(mapNode); // 设置地球操纵器 osg::ref_ptr<osgEarth::Util::EarthManipulator> manipulator = new osgEarth::Util::EarthManipulator; view->setCameraManipulator(manipulator); // 显示视图 osgViewer::Viewer viewer; viewer.addView(view); return viewer.run(); } ``` 以上代码创建了一个 osgEarth 地图节点,并使用 EarthManipulator 对其进行控制。注意要在程序结束前调用 osgEarth::shutdown(),以释放资源。 4. 运行应用程序 点击“生成”按钮编译应用程序,并运行应用程序。如果一切正常,应该可以看到一个 osgEarth 地球视图。 以上是在 Visual Studio 2022 中使用 osgEarth 的简单示例。根据需要,还可以使用 osgEarth 的其他功能来创建更复杂的地图应用程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值