osgEarth示例分析——osgearth_tracks

前言

osgearth_tracks示例,演示了所有图标沿着路径进行移动(路径是不可见的)。

执行效果

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

右下角的控制面板功能:

Declutter

是否开启 【清理器】 功能。

即当两个图标靠近时,其中一个会逐渐变小并消失;

当两个图标远离时,那个变小的图标会逐渐变大并出现。

Show locations是否显示坐标信息,即图标下方黄色文本。
Sim loop duration

设置图标云顶一个周期的时间。

由于距离是一定的,周期越大,则运行速度越慢。

Min scale

图标变小时,最小的缩放值。

此值设置越小,图标变小的终极状态也会越小。

Min alpha图标变小时,透明度的变化。
Activate time(s)

图标从最小状态,变化到最大状态的时间。

此值设置太小,则图标会一下子变大。

Deactivate time(s)

图标从正常变小,到终极最小状态的时间。

此值设置太小,则图标会一下子变小。

【注】最后两个值,有时候观察也不是太明显。

代码分析

此示例中,涉及到一些新的类和方法。下面简单进行分析。

1、控制面板功能的重要类

osgEarth::ScreenSpaceLayoutOptions 通过选项控制annotation清除的引擎类。比如上面表格中说的:scale、alpha、activate、deactivate等内容的控制。

osgEarth::ScreenSpaceLayout::setOptions ( ScreenSpaceLayout::getOptions() ) 控制activate、 deactivate、 enable(是否开启)等内容。

以上两个类是同时使用的。

2、坐标系

在此显示状态时,坐标系并非是我们熟知的经纬度,而是 osgEarth::Util::s_format(MGRSFormatter::PRECISION_10000M)

3、轨迹模拟器

通过osg的方式,实现的。struct TrackSim : public osg::Referenced,重写 update() 方法。struct TrackSimUpdate : public osg::Operation,重写 operator() 方法。

4、绘制标签和图标的方式

typedef std::map<std::string, TrackNodeField> TrackNodeFieldSchema schema;

schema[FIELD_NAME] = TrackNodeField(TextSymbol* nameSymbol, false);// 通过键值对构造

osgEarth::Annotation::TrackNode * track = new TrackNode(pos, image.get(), schema);

osgEarth::Annotation::TrackNodeField 

5、控制面板的ui界面,本节仅有的新内容,是通过仅设置一个方法,就能为多个滑块添加事件。

6、

    // attach the simulator to the viewer. 将仿真器和视景器关联起来
    viewer.addUpdateOperation( new TrackSimUpdate(trackSims) );
    viewer.setRunFrameScheme( viewer.CONTINUOUS );

完整代码

#include <osgEarth/MapNode>
#include <osgEarth/Random>
#include <osgEarth/StringUtils>
#include <osgEarth/ImageUtils>
#include <osgEarth/GeoMath>
#include <osgEarth/Units>
#include <osgEarth/StringUtils>
#include <osgEarth/ScreenSpaceLayout>
#include <osgEarthUtil/ExampleResources>
#include <osgEarthUtil/EarthManipulator>
#include <osgEarthUtil/MGRSFormatter>
#include <osgEarthUtil/Controls>
#include <osgEarthAnnotation/TrackNode>
#include <osgEarthSymbology/Color>

#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgGA/StateSetManipulator>

using namespace osgEarth;
using namespace osgEarth::Util;
using namespace osgEarth::Util::Controls;
using namespace osgEarth::Annotation;
using namespace osgEarth::Symbology;

#define LC "[osgearth_tracks] "

/**
 * Demonstrates use of the TrackNode to display entity track symbols.
 */

// field names for the track labelsL
#define FIELD_NAME     "name"
#define FIELD_POSITION "position"
#define FIELD_NUMBER   "number"

// icon to use, and size in pixels
#define ICON_URL       "m2525_air.png"
#define ICON_SIZE      40

// format coordinates as MGRS 坐标系格式MGRS
static MGRSFormatter s_format(MGRSFormatter::PRECISION_10000M);

// globals for this demo
bool                g_showCoords        = true;
optional<float>     g_duration          = 60.0;
unsigned            g_numTracks         = 500;
// 用于控制 清除引擎(图标和其他内容变小消失) 的选项。
ScreenSpaceLayoutOptions g_dcOptions;


/** Prints an error message */
int
usage( const std::string& message )
{
    OE_WARN << LC << message << std::endl;
    return -1;
}


/** A little track simulator that goes a simple great circle interpolation */
// 一个小小的轨迹模拟器,可以进行简单的大圆插值。
struct TrackSim : public osg::Referenced
{
    TrackNode* _track;
    GeoPoint _start, _end;

    void update( double t )
    {
        osg::Vec3d pos;

        GeoPoint geo = _start.interpolate(_end, t);
        geo.alt() = 10000.0; // 高度默认

        // update the position label.
        _track->setPosition(geo);

        if ( g_showCoords )// 此参数通过checkbox控制是否需要显示
        {
            _track->setFieldValue( FIELD_POSITION, s_format(geo) );// s_format 转化坐标格式
        }
        else
            _track->setFieldValue( FIELD_POSITION, "" );
    }
};
typedef std::list< osg::ref_ptr<TrackSim> > TrackSims;


/** Update operation that runs the simulators. */
// 运行的模拟器的更新操作
struct TrackSimUpdate : public osg::Operation
{
    TrackSimUpdate(TrackSims& sims) : osg::Operation( "tasksim", true ), _sims(sims) { }

    void operator()( osg::Object* obj ) {
        osg::View* view = dynamic_cast<osg::View*>(obj);
        double t = fmod(view->getFrameStamp()->getSimulationTime(), (double)g_duration.get()) / (double)g_duration.get();
        for( TrackSims::iterator i = _sims.begin(); i != _sims.end(); ++i )
            i->get()->update( t );// 更新每一个TrackSim
    }

    TrackSims& _sims;
};


/**
 * Creates a field schema that we'll later use as a labeling template for
 * TrackNode instances.
 */
// 创建一个字段模式,稍后将用作TrackNode实例的标签模板。
// typedef std::map<std::string, TrackNodeField> TrackNodeFieldSchema;
// TrackNodeField:定义与TrackNode关联的标签字段。TrackNode可以有零个或多个“字段”,每个字段都是与节点图标一起呈现的文本标签。
void
createFieldSchema( TrackNodeFieldSchema& schema )
{
    const float R = 2.0f;

	// 三个字段,分别显示名称、坐标、当前编号,分别位于图标的上、下、左侧。
	// 关于位置的设定,->pixelOffset()与->alignment() 的属性设置,需要放在一起看,才能更明白。
    // draw the track name above the icon:
    TextSymbol* nameSymbol = new TextSymbol();
    nameSymbol->pixelOffset()->set( 0, R+ICON_SIZE/2 );// 文本偏移
    nameSymbol->alignment() = TextSymbol::ALIGN_CENTER_BOTTOM;// 文本位置
    nameSymbol->halo()->color() = Color::Black;
    nameSymbol->size() = nameSymbol->size()->eval() + 2.0f;
    schema[FIELD_NAME] = TrackNodeField(nameSymbol, false); // false => static label (won't change after set)

    // draw the track coordinates below the icon:
    TextSymbol* posSymbol = new TextSymbol();
    posSymbol->pixelOffset()->set( 0, -R-ICON_SIZE/2 );
    posSymbol->alignment() = TextSymbol::ALIGN_CENTER_TOP;
    posSymbol->fill()->color() = Color::Yellow;
    posSymbol->size() = posSymbol->size()->eval() - 2.0f;
    schema[FIELD_POSITION] = TrackNodeField(posSymbol, true); // true => may change at runtime,位置改变

    // draw some other field to the left:
    TextSymbol* numberSymbol = new TextSymbol();
    numberSymbol->pixelOffset()->set( -R-ICON_SIZE/2, 0 );
    numberSymbol->alignment() = TextSymbol::ALIGN_RIGHT_CENTER;
    schema[FIELD_NUMBER] = TrackNodeField(numberSymbol, false);
}


/** Builds a bunch of tracks. */
// 创建一堆轨道
void
createTrackNodes(const SpatialReference* mapSRS, osg::Group* parent, const TrackNodeFieldSchema& schema, TrackSims& sims )
{
    // load an icon to use:
    osg::ref_ptr<osg::Image> srcImage = osgDB::readRefImageFile( ICON_URL );
    osg::ref_ptr<osg::Image> image;
	// 输入文件,格式化后,变为输出文件image
    ImageUtils::resizeImage( srcImage.get(), ICON_SIZE, ICON_SIZE, image );

    // make some tracks, choosing a random simulation for each.
    Random prng;// 随机数
	// 获取地理坐标系
    const SpatialReference* geoSRS = mapSRS->getGeographicSRS();

	// g_numTracks = 500
    for( unsigned i=0; i<g_numTracks; ++i )
    {
		// prng.next():a double in the range [0..1]
        double lon0 = -180.0 + prng.next() * 360.0;
        double lat0 = -80.0 + prng.next() * 160.0;

        GeoPoint pos(geoSRS, lon0, lat0);

        TrackNode* track = new TrackNode(pos, image.get(), schema);

        track->setFieldValue( FIELD_NAME,     Stringify() << "Track:" << i );
        track->setFieldValue( FIELD_POSITION, Stringify() << s_format(pos) );// 转化坐标格式
        track->setFieldValue( FIELD_NUMBER,   Stringify() << (1 + prng.next(9)) );

        // add a priority
        track->setPriority( float(i) );

        parent->addChild( track );

        // add a simulator for this guy
        double lon1 = -180.0 + prng.next() * 360.0;
        double lat1 = -80.0 + prng.next() * 160.0;
        TrackSim* sim = new TrackSim();// 创建轨道模拟器
        sim->_track = track;  
        sim->_start.set(mapSRS, lon0, lat0, 0.0, ALTMODE_ABSOLUTE);
        sim->_end.set(mapSRS, lon1, lat1, 0.0, ALTMODE_ABSOLUTE);
        sims.push_back( sim );
    }
}


/** creates some UI controls for adjusting the decluttering parameters. */
// 创建ui面板
Container*
createControls( osgViewer::View* view )
{
    //ControlCanvas* canvas = ControlCanvas::getOrCreate(view);
    
    // title bar 垂直box
    VBox* vbox = new VBox(Control::ALIGN_NONE, Control::ALIGN_BOTTOM, 2, 1 );
    vbox->setBackColor( Color(Color::Black, 0.5) );
	// 添加一个label控件
    vbox->addControl( new LabelControl("osgEarth Tracks Demo", Color::Yellow) );
    
    // checkbox that toggles decluttering of tracks
	// 通过复选框,切换 是否开启 清理功能(也就是当两个图标移动靠近时,会有一个逐渐变小以至于隐藏,避免图标覆盖遮挡)
    struct ToggleDecluttering : public ControlEventHandler {
        void onValueChanged( Control* c, bool on ) {
            ScreenSpaceLayout::setDeclutteringEnabled( on );
        }
    };
    HBox* dcToggle = vbox->addControl( new HBox() );
    dcToggle->addControl( new CheckBoxControl(true, new ToggleDecluttering()) );
    dcToggle->addControl( new LabelControl("Declutter") );

    // checkbox that toggles the coordinate display
	// 切换是否显示图标下方的坐标信息
    struct ToggleCoords : public ControlEventHandler {
        void onValueChanged( Control* c, bool on ) {
            g_showCoords = on;// 是否显示坐标系
        }
    };
    HBox* coordsToggle = vbox->addControl( new HBox() );
    coordsToggle->addControl( new CheckBoxControl(true, new ToggleCoords()) );
    coordsToggle->addControl( new LabelControl("Show locations") );

    // grid for the slider controls so they look nice
	// 添加网格,然后在网格中绘制滑块,看起来更美观
    Grid* grid = vbox->addControl( new Grid() );
    grid->setHorizFill( true );
    grid->setChildHorizAlign( Control::ALIGN_LEFT );
    grid->setChildSpacing( 6 );// 子控件的间距

    unsigned r=0;

    // event handler for changing decluttering options
    struct ChangeFloatOption : public ControlEventHandler {
        optional<float>& _param;
        LabelControl* _label;
        ChangeFloatOption( optional<float>& param, LabelControl* label ) : _param(param), _label(label) { }
        void onValueChanged( Control* c, float value ) {
            _param = value;
            _label->setText( Stringify() << std::fixed << std::setprecision(1) << value );// 修改滑块值,此值会显示在label上
            ScreenSpaceLayout::setOptions( g_dcOptions );// 通过 g_dcOptions 参数设置引擎
        }
    };

	// 设置循环一圈的时间,时间越小,速度越快
    grid->setControl( 0, r, new LabelControl("Sim loop duration:") );
    LabelControl* speedLabel = grid->setControl( 2, r, new LabelControl(Stringify() << std::fixed << std::setprecision(1) << *g_duration) );
    HSliderControl* speedSlider = grid->setControl( 1, r, new HSliderControl( 
        600.0, 30.0, *g_duration, new ChangeFloatOption(g_duration, speedLabel) ) );// 控制 g_duration
    speedSlider->setHorizFill( true, 200 );

	// 控制最小值,即两个标签靠近时,有一个标签逐渐变小,以至于变到最小的值
    grid->setControl( 0, ++r, new LabelControl("Min scale:") );
    LabelControl* minAnimationScaleLabel = grid->setControl( 2, r, new LabelControl(Stringify() << std::fixed << std::setprecision(1) << *g_dcOptions.minAnimationScale()) );
    grid->setControl( 1, r, new HSliderControl( 
        0.0, 1.0, *g_dcOptions.minAnimationScale(), new ChangeFloatOption(g_dcOptions.minAnimationScale(), minAnimationScaleLabel) ) );

	// 更改透明度
    grid->setControl( 0, ++r, new LabelControl("Min alpha:") );
    LabelControl* alphaLabel = grid->setControl( 2, r, new LabelControl(Stringify() << std::fixed << std::setprecision(1) << *g_dcOptions.minAnimationAlpha()) );
    grid->setControl( 1, r, new HSliderControl( 
        0.0, 1.0, *g_dcOptions.minAnimationAlpha(), new ChangeFloatOption(g_dcOptions.minAnimationAlpha(), alphaLabel) ) );

	// 激活时间
    grid->setControl( 0, ++r, new LabelControl("Activate time (s):") );
    LabelControl* actLabel = grid->setControl( 2, r, new LabelControl(Stringify() << std::fixed << std::setprecision(1) << *g_dcOptions.inAnimationTime()) );
    grid->setControl( 1, r, new HSliderControl( 
        0.0, 2.0, *g_dcOptions.inAnimationTime(), new ChangeFloatOption(g_dcOptions.inAnimationTime(), actLabel) ) );

	// 停止时间
    grid->setControl( 0, ++r, new LabelControl("Deactivate time (s):") );
    LabelControl* deactLabel = grid->setControl( 2, r, new LabelControl(Stringify() << std::fixed << std::setprecision(1) << *g_dcOptions.outAnimationTime()) );
    grid->setControl( 1, r, new HSliderControl( 
        0.0, 2.0, *g_dcOptions.outAnimationTime(), new ChangeFloatOption(g_dcOptions.outAnimationTime(), deactLabel) ) );

    return vbox;
}


/**
 * Main application.
 * Creates some simulated track data and runs the simulation.
 */
int
main(int argc, char** argv)
{
    osg::ArgumentParser arguments(&argc,argv);

    // initialize a viewer.
    osgViewer::Viewer viewer( arguments );
    viewer.setCameraManipulator( new EarthManipulator );

    // load a map from an earth file.读取earth文件,并且创建界面控制面板
    osg::Node* earth = MapNodeHelper().load(arguments, &viewer, createControls(&viewer));

    MapNode* mapNode = MapNode::findMapNode(earth);
    if ( !mapNode )
        return usage("Missing required .earth file" );

    // count on the cmd line? 从控制台输入个数,默认500个
    arguments.read("--count", g_numTracks);
    
    viewer.setSceneData( earth );

    // build a track field schema.
	// 创建一个map列表 ,typedef std::map<std::string, osgEarth::Annotation::TrackNodeField> TrackNodeFieldSchema;
    TrackNodeFieldSchema schema;
	// 初始化 schema 对象
    createFieldSchema( schema );

    // create some track nodes.创建一些跟踪节点
    TrackSims trackSims;
    osg::Group* tracks = new osg::Group();
    createTrackNodes( mapNode->getMapSRS(), tracks, schema, trackSims );
    mapNode->addChild( tracks );

    // Set up the automatic decluttering. setEnabled() activates decluttering for
    // all drawables under that state set. We are also activating priority-based
    // sorting, which looks at the AnnotationData::priority field for each drawable.
    // (By default, objects are sorted by disatnce-to-camera.) Finally, we customize 
    // a couple of the decluttering options to get the animation effects we want.
    g_dcOptions = ScreenSpaceLayout::getOptions();
    g_dcOptions.inAnimationTime()  = 1.0f;
    g_dcOptions.outAnimationTime() = 1.0f;
    g_dcOptions.sortByPriority()   = true;
    ScreenSpaceLayout::setOptions( g_dcOptions );

    // attach the simulator to the viewer. 将仿真器和视景器关联起来
    viewer.addUpdateOperation( new TrackSimUpdate(trackSims) );
    viewer.setRunFrameScheme( viewer.CONTINUOUS );
    
    viewer.getCamera()->setSmallFeatureCullingPixelSize(-1.0f);
    viewer.run();
}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 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. 编辑问题总结....................................................................................错误!未定义书签。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值