• osgEarth示例分析——osgearth_manip


    前言

    本示例主要演示osgEarth的事件处理的用法,内容比较多,这部分功能也很重要。

    输入命令依然采用china-simple.earth的示例,加上了模型,但是模型并没有看到,可能是因为模型没有放大太小的原因。在代码中设置了不加载模型的话,会绘制两个半圆。

    1. // 加载模型,但是看不到,估计是模型太小,需要放大
    2. osgearth_manipd.exe earth_image/china-simple.earth --model axes.osgt
    3. // 并没有加载模型
    4. osgearth_manipd.exe earth_image/china-simple.earth --model modelToLoad
    5. // 不加载模型,会默认创建一个半球,距离太远的话,半球也看不到
    6. osgearth_manipd.exe earth_image/china-simple.earth

    执行效果

    按下W键,开启坐标,也就是黄色的两条线,交点始终跟随 Thing 1 节点。

    按键说明

    左上角操作说明
    *左键按住左键拖动地球*u看不出来,没啥变化
    *中键按住中键可以旋转地球*o切换操作器,地球会有大小变化
    *右键按住右键前后移动,缩放地球*8视角绑定thing 1,也可以说跟踪
    *

    右键/左键

    双击

    越来越远/越来越近*9视角绑定thing 2,也可以说跟踪
    *滚轮滚动视角远近控制*t地球三种转动状态的切换
    *arrows

    shift+上/下/左/右键,

    好像没啥作用

    *b解除绑定 '8' ‘9’,,或者说解除跟踪
    *shift+左键看不出来,没啥变化*a看不出来,没啥变化
    *q看不出来,没啥变化
    *k看不出来,没啥变化
    *L看不出来,没啥变化
    *j定位到可以看见一组点的视点
    *W绘制两条线,交点始终定位在thing 1上,屏幕坐标系

    [注] 必须在英文下输入,如果没有注意,在中文状态下输入字符,地球会被卡住。此时只能退出重新运行程序。

    thing1 thing 2,这两个文本是移动的。

    代码分析

    1. #include
    2. #include
    3. #include
    4. #include
    5. #include
    6. #include
    7. #include
    8. #include
    9. #include
    10. #include
    11. #include
    12. #include
    13. #include
    14. #include
    15. #include
    16. #include
    17. #include
    18. #include
    19. #include
    20. #include
    21. #include
    22. #include
    23. #include
    24. #include
    25. using namespace osgEarth::Util;
    26. using namespace osgEarth::Util::Controls;
    27. using namespace osgEarth::Annotation;
    28. #define D2R (osg::PI/180.0)
    29. #define R2D (180.0/osg::PI)
    30. namespace
    31. {
    32. /**
    33. * Tether callback test.是否绑定
    34. */
    35. struct TetherCB : public EarthManipulator::TetherCallback
    36. {
    37. void operator()(osg::Node* node)
    38. {
    39. if ( node ) {
    40. OE_WARN << "Tether on\n";
    41. }
    42. else {
    43. OE_WARN << "Tether off\n";
    44. }
    45. }
    46. };
    47. /**
    48. * Builds our help menu UI.创建左上角的说明文档
    49. */
    50. Container* createHelp( osgViewer::View* view )
    51. {
    52. const char* text[] =
    53. {
    54. "left mouse :", "pan",
    55. "middle mouse :", "rotate",
    56. "right mouse :", "continuous zoom",
    57. "double-click :", "zoom to point",
    58. "scroll wheel :", "zoom in/out",
    59. "arrows :", "pan",
    60. //"1-6 :", "fly to preset viewpoints",
    61. "shift-left-mouse :", "locked pan",
    62. "u :", "toggle azimuth lock",
    63. "o :", "toggle perspective/ortho",
    64. "8 :", "Tether to thing 1",
    65. "9 :", "Tether to thing 2",
    66. "t :", "cycle tethermode",
    67. "b :", "break tether",
    68. "a :", "toggle viewpoint arcing",
    69. "q :", "toggle throwing",
    70. "k :", "toggle collision",
    71. "L :", "toggle log depth buffer"
    72. //"W :", "坐标系", // 源代码并没有这两个提示
    73. //"j :", "定位到指定点组的视点",
    74. };
    75. Grid* g = new Grid();// 创建网格
    76. unsigned i, c, r;
    77. std::cout << sizeof(text) << std::endl; // 存储所有指针占位多少
    78. std::cout << sizeof(text[0]) << std::endl; // 每个指针占位多少
    79. for( i=0; i<sizeof(text)/sizeof(text[0]); ++i )
    80. {
    81. c = i % 2;
    82. r = i / 2;
    83. g->setControl( c, r, new LabelControl(text[i]) );// 两列c,i行r,显示label控件
    84. }
    85. VBox* v = new VBox();
    86. v->addControl( g );// 将网格控件放入VBox控件中
    87. return v;
    88. }
    89. /**
    90. * Some preset viewpoints to show off the setViewpoint function.
    91. */
    92. static Viewpoint VPs[] = {
    93. Viewpoint( "Africa", 0.0, 0.0, 0.0, 0.0, -90.0, 10e6 ),
    94. Viewpoint( "California", -121.0, 34.0, 0.0, 0.0, -90.0, 6e6 ),
    95. Viewpoint( "Europe", 0.0, 45.0, 0.0, 0.0, -90.0, 4e6 ),
    96. Viewpoint( "Washington DC", -77.0, 38.0, 0.0, 0.0, -90.0, 1e6 ),
    97. Viewpoint( "Australia", 135.0, -20.0, 0.0, 0.0, -90.0, 2e6 ),
    98. Viewpoint( "Boston", -71.096936, 42.332771, 0, 0.0, -90, 1e5 )
    99. };
    100. /**
    101. * Handler that demonstrates the "viewpoint" functionality in
    102. * osgEarthUtil::EarthManipulator. Press a number key to fly to a viewpoint.
    103. */
    104. struct FlyToViewpointHandler : public osgGA::GUIEventHandler
    105. {
    106. FlyToViewpointHandler( EarthManipulator* manip ) : _manip(manip) { }
    107. bool handle( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa )
    108. {
    109. if ( ea.getEventType() == ea.KEYDOWN && ea.getKey() >= '1' && ea.getKey() <= '6' )
    110. {
    111. _manip->setViewpoint( VPs[ea.getKey()-'1'], 4.0 );// 根据设置好的位置,123456定位不同的地点
    112. aa.requestRedraw();
    113. }
    114. return false;
    115. }
    116. osg::observer_ptr _manip;
    117. };
    118. /**
    119. * Toggles the logarithmic depth buffer切换对数深度缓冲区
    120. */
    121. struct ToggleLDB : public osgGA::GUIEventHandler
    122. {
    123. ToggleLDB(char key) : _key(key), _installed(false) { }// key=L
    124. bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
    125. {
    126. if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key)
    127. {
    128. if ( !_installed )
    129. {
    130. _nfratio = aa.asView()->getCamera()->getNearFarRatio();// 获取到近/远率
    131. _ldb.install(aa.asView()->getCamera());
    132. aa.asView()->getCamera()->setNearFarRatio(0.00001);
    133. }
    134. else
    135. {
    136. _ldb.uninstall(aa.asView()->getCamera());
    137. aa.asView()->getCamera()->setNearFarRatio(_nfratio);
    138. }
    139. _installed = !_installed;// 每次切换
    140. return true;
    141. }
    142. return false;
    143. }
    144. void getUsage(osg::ApplicationUsage& usage) const
    145. {
    146. using namespace std;
    147. usage.addKeyboardMouseBinding(string(1, _key), string("Toggle LDB"));
    148. }
    149. char _key;
    150. float _nfratio;
    151. bool _installed;
    152. osgEarth::Util::LogarithmicDepthBuffer _ldb;
    153. };
    154. /**
    155. * Toggles screen space layout on the sismulated objects 切换模拟对象的屏幕空间布局
    156. */
    157. struct ToggleSSL : public osgGA::GUIEventHandler
    158. {
    159. ToggleSSL(osg::Group* g, char key) : _group(g), _key(key), _installed(false) { }// key=)
    160. bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
    161. {
    162. if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key)
    163. {
    164. _installed = !_installed;
    165. ScreenSpaceLayout::setDeclutteringEnabled(_installed);// 启动或禁用清理
    166. return true;
    167. }
    168. return false;
    169. }
    170. void getUsage(osg::ApplicationUsage& usage) const
    171. {
    172. using namespace std;
    173. usage.addKeyboardMouseBinding(string(1, _key), string("Toggle SSL"));
    174. }
    175. char _key;
    176. osg::Group* _group;
    177. bool _installed;
    178. };
    179. /**
    180. * Handler to toggle "azimuth locking", which locks the camera's relative Azimuth
    181. * while panning. For example, it can maintain "north-up" as you pan around. The
    182. * caveat is that when azimuth is locked you cannot cross the poles.
    183. */
    184. struct LockAzimuthHandler : public osgGA::GUIEventHandler // 锁定/解锁 方位角
    185. {
    186. LockAzimuthHandler(char key, EarthManipulator* manip) // 传入key = u
    187. : _key(key), _manip(manip) { }
    188. bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
    189. {
    190. if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key)
    191. {
    192. bool lockAzimuth = _manip->getSettings()->getLockAzimuthWhilePanning();
    193. std::cout << "按下 u" << std::endl;// 确实收到消息,但是在操作上并没有看到所定方位角
    194. _manip->getSettings()->setLockAzimuthWhilePanning(!lockAzimuth);// 设置为当前状态相反的状态
    195. aa.requestRedraw();
    196. return true;
    197. }
    198. return false;
    199. }
    200. void getUsage(osg::ApplicationUsage& usage) const
    201. {
    202. using namespace std;
    203. usage.addKeyboardMouseBinding(string(1, _key), string("Toggle azimuth locking"));
    204. }
    205. char _key;
    206. osg::ref_ptr _manip;
    207. };
    208. /**
    209. * Handler to toggle "viewpoint transition arcing", which causes the camera to "arc"
    210. * as it travels from one viewpoint to another.
    211. */
    212. struct ToggleArcViewpointTransitionsHandler : public osgGA::GUIEventHandler
    213. {
    214. ToggleArcViewpointTransitionsHandler(char key, EarthManipulator* manip)
    215. : _key(key), _manip(manip) { }// key=a
    216. bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
    217. {
    218. if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key)
    219. {
    220. bool arc = _manip->getSettings()->getArcViewpointTransitions();
    221. std::cout << "按下 a" << std::endl;// 确实收到消息,但是没看出什么变化
    222. _manip->getSettings()->setArcViewpointTransitions(!arc);
    223. aa.requestRedraw();
    224. return true;
    225. }
    226. return false;
    227. }
    228. void getUsage(osg::ApplicationUsage& usage) const
    229. {
    230. using namespace std;
    231. usage.addKeyboardMouseBinding(string(1, _key), string("Arc viewpoint transitions"));
    232. }
    233. char _key;
    234. osg::ref_ptr _manip;
    235. };
    236. /**
    237. * Toggles the throwing feature.切换投掷功能。
    238. */
    239. struct ToggleThrowingHandler : public osgGA::GUIEventHandler
    240. {
    241. ToggleThrowingHandler(char key, EarthManipulator* manip)
    242. : _key(key), _manip(manip)// key=q
    243. {
    244. }
    245. bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
    246. {
    247. if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key)
    248. {
    249. bool throwing = _manip->getSettings()->getThrowingEnabled();
    250. std::cout << "按下 q" << std::endl;// 确实收到消息,但是没看出什么变化
    251. _manip->getSettings()->setThrowingEnabled( !throwing );
    252. aa.requestRedraw();
    253. return true;
    254. }
    255. return false;
    256. }
    257. void getUsage(osg::ApplicationUsage& usage) const
    258. {
    259. using namespace std;
    260. usage.addKeyboardMouseBinding(string(1, _key), string("Toggle throwing"));
    261. }
    262. char _key;
    263. osg::ref_ptr _manip;
    264. };
    265. /**
    266. * Toggles the collision feature.切换碰撞功能。
    267. */
    268. struct ToggleCollisionHandler : public osgGA::GUIEventHandler
    269. {
    270. ToggleCollisionHandler(char key, EarthManipulator* manip)
    271. : _key(key), _manip(manip)// key=k
    272. {
    273. }
    274. bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
    275. {
    276. if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key)
    277. {
    278. bool value = _manip->getSettings()->getTerrainAvoidanceEnabled();
    279. std::cout << "按下 k" << std::endl;// 确实收到消息,但是没看出什么变化
    280. _manip->getSettings()->setTerrainAvoidanceEnabled( !value );
    281. aa.requestRedraw();
    282. return true;
    283. }
    284. return false;
    285. }
    286. void getUsage(osg::ApplicationUsage& usage) const
    287. {
    288. using namespace std;
    289. usage.addKeyboardMouseBinding(string(1, _key), string("Toggle terrain avoidance"));
    290. }
    291. char _key;
    292. osg::ref_ptr _manip;
    293. };
    294. /**
    295. * Breaks a tether.三种状态的切换
    296. */
    297. struct CycleTetherMode : public osgGA::GUIEventHandler
    298. {
    299. CycleTetherMode(char key, EarthManipulator* manip)
    300. : _key(key), _manip(manip) { }// key=t
    301. bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
    302. {
    303. if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key)
    304. {
    305. EarthManipulator::TetherMode mode = _manip->getSettings()->getTetherMode();
    306. if ( mode == _manip->TETHER_CENTER ) {
    307. _manip->getSettings()->setTetherMode( _manip->TETHER_CENTER_AND_HEADING );// 相机将跟随节点,仅跟随方向旋转
    308. OE_NOTICE << "Tether mode = TETHER_CENTER_AND_HEADING\n";
    309. }
    310. else if ( mode == _manip->TETHER_CENTER_AND_HEADING ) {
    311. _manip->getSettings()->setTetherMode( _manip->TETHER_CENTER_AND_ROTATION ); // 摄影机将跟随节点和节点所做的所有旋转
    312. OE_NOTICE << "Tether mode = TETHER_CENTER_AND_ROTATION\n";
    313. }
    314. else {
    315. _manip->getSettings()->setTetherMode( _manip->TETHER_CENTER );// 摄影机将跟随节点的中心。
    316. OE_NOTICE << "Tether mode = CENTER\n";
    317. }
    318. aa.requestRedraw();
    319. return true;
    320. }
    321. return false;
    322. }
    323. void getUsage(osg::ApplicationUsage& usage) const
    324. {
    325. using namespace std;
    326. usage.addKeyboardMouseBinding(string(1, _key), string("Cycle Tether Mode"));
    327. }
    328. char _key;
    329. osg::ref_ptr _manip;
    330. };
    331. /**
    332. * Breaks a tether.解绑
    333. */
    334. struct BreakTetherHandler : public osgGA::GUIEventHandler
    335. {
    336. BreakTetherHandler(char key, EarthManipulator* manip)
    337. : _key(key), _manip(manip) { }//key=b
    338. bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
    339. {
    340. if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key)
    341. {
    342. _manip->clearViewpoint();// 解除所有操作器绑定,恢复自由状态。thing1和 thing2 的状态改变明显
    343. aa.requestRedraw();
    344. return true;
    345. }
    346. return false;
    347. }
    348. void getUsage(osg::ApplicationUsage& usage) const
    349. {
    350. using namespace std;
    351. usage.addKeyboardMouseBinding(string(1, _key), string("Break a tether"));
    352. }
    353. char _key;
    354. osg::ref_ptr _manip;
    355. };
    356. /**
    357. * Adjusts the position offset.调整位置偏移。
    358. */
    359. struct SetPositionOffset : public osgGA::GUIEventHandler
    360. {
    361. SetPositionOffset(EarthManipulator* manip)
    362. : _manip(manip) { }
    363. bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
    364. {
    365. if (ea.getEventType() == ea.KEYDOWN && (ea.getModKeyMask() & ea.MODKEY_SHIFT) )
    366. {
    367. Viewpoint oldvp = _manip->getViewpoint();
    368. double seconds = 0.5; // 时间秒。每次切换都需要0.5秒
    369. if ( ea.getKey() == ea.KEY_Left )// 左键
    370. {
    371. Viewpoint vp;
    372. vp.positionOffset() = oldvp.positionOffset().get() + osg::Vec3f(-1000,0,0);
    373. _manip->setViewpoint( vp, seconds );
    374. }
    375. else if ( ea.getKey() == ea.KEY_Right )// 右键
    376. {
    377. Viewpoint vp;
    378. vp.positionOffset() = oldvp.positionOffset().get() + osg::Vec3f(1000,0,0);
    379. _manip->setViewpoint( vp, seconds );
    380. }
    381. else if ( ea.getKey() == ea.KEY_Up )// 上键
    382. {
    383. Viewpoint vp;
    384. vp.positionOffset() = oldvp.positionOffset().get() + osg::Vec3f(0,0,1000);
    385. _manip->setViewpoint( vp, seconds );
    386. }
    387. else if ( ea.getKey() == ea.KEY_Down )// 下键
    388. {
    389. Viewpoint vp;
    390. vp.positionOffset() = oldvp.positionOffset().get() + osg::Vec3f(0,0,-1000);
    391. _manip->setViewpoint( vp, seconds );
    392. }
    393. aa.requestRedraw();
    394. return true;
    395. }
    396. return false;
    397. }
    398. osg::ref_ptr _manip;
    399. };
    400. /**
    401. * Toggles perspective/ortho projection matrix. 切换投影矩阵,透视投影矩阵和正射投影矩阵
    402. */
    403. struct ToggleProjMatrix : public osgGA::GUIEventHandler
    404. {
    405. ToggleProjMatrix(char key, EarthManipulator* manip)
    406. : _key(key), _manip(manip)// ley=o
    407. {
    408. }
    409. bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
    410. {
    411. if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key)
    412. {
    413. osg::Matrix proj = aa.asView()->getCamera()->getProjectionMatrix();
    414. if ( proj(3,3) == 0 )
    415. {
    416. OE_NOTICE << "Switching to orthographc.\n";
    417. proj.getPerspective(_vfov, _ar, _zn, _zf); // 获取值
    418. aa.asView()->getCamera()->setProjectionMatrixAsOrtho(-1, 1, -1, 1, _zn, _zf);// 正射投影矩阵
    419. }
    420. else
    421. {
    422. OE_NOTICE << "Switching to perspective.\n";
    423. aa.asView()->getCamera()->setProjectionMatrixAsPerspective(_vfov, _ar, _zn, _zf);// 透视矩阵
    424. }
    425. aa.requestRedraw();
    426. return true;
    427. }
    428. return false;
    429. }
    430. void getUsage(osg::ApplicationUsage& usage) const
    431. {
    432. using namespace std;
    433. usage.addKeyboardMouseBinding(string(1, _key), string("Toggle projection matrix type"));
    434. }
    435. char _key;
    436. osg::ref_ptr _manip;
    437. double _vfov, _ar, _zn, _zf;
    438. };
    439. // 定位到某组点的视点,一组点都可以看到
    440. struct FitViewToPoints : public osgGA::GUIEventHandler
    441. {
    442. std::vector _points;
    443. const SpatialReference* _mapSRS;
    444. FitViewToPoints(char key, EarthManipulator* manip, const SpatialReference* mapSRS)
    445. : _key(key), _manip(manip), _mapSRS(mapSRS)// key=j
    446. {
    447. // Set up a list of control points
    448. const SpatialReference* srs = SpatialReference::get("wgs84");
    449. _points.push_back(GeoPoint(srs, -120, 30, 0));
    450. _points.push_back(GeoPoint(srs, -100, 45, 0));
    451. }
    452. bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
    453. {
    454. if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key)
    455. {
    456. // fitter 创建适合摄影机视图平截头体的视点,以尽可能紧密地包围一组地理空间点。
    457. ViewFitter fitter(_mapSRS, aa.asView()->getCamera());
    458. fitter.setBuffer( 100000.0 );
    459. Viewpoint vp;
    460. if (fitter.createViewpoint(_points, vp))// 根据_points重新生成一个vp视点
    461. {
    462. _manip->setViewpoint(vp);// 定位到vp视点
    463. aa.requestRedraw();
    464. }
    465. return true;
    466. }
    467. return false;
    468. }
    469. void getUsage(osg::ApplicationUsage& usage) const
    470. {
    471. using namespace std;
    472. usage.addKeyboardMouseBinding(string(1, _key), string("FitViewToPoints"));
    473. }
    474. char _key;
    475. osg::ref_ptr _manip;
    476. };
    477. /**
    478. * A simple simulator that moves an object around the Earth. We use this to
    479. * demonstrate/test tethering.
    480. */
    481. // 一个简单的模拟器,可以使物体绕地球运动。用来演示跟踪thing
    482. struct Simulator : public osgGA::GUIEventHandler
    483. {
    484. Simulator( osg::Group* root, EarthManipulator* manip, MapNode* mapnode, osg::Node* model, const char* name, char key)
    485. : _manip(manip), _mapnode(mapnode), _model(model), _name(name), _key(key) // key=8 或 9
    486. {
    487. if ( !model )
    488. {
    489. // 模型不存在,则创建一个半球,半径和颜色
    490. _model = AnnotationUtils::createHemisphere(250.0, osg::Vec4(1,.7,.4,1));
    491. std::cout << "no model" << std::endl;
    492. }
    493. _geo = new GeoPositionNode();
    494. _geo->getPositionAttitudeTransform()->addChild(_model);
    495. Style style;
    496. TextSymbol* text = style.getOrCreate();
    497. text->size() = 32.0f;
    498. text->declutter() = false;
    499. text->pixelOffset()->set(50, 50);// 文本偏移像素点
    500. _label = new LabelNode(_name, style);// _name 即要显示的名称
    501. _label->setDynamic( true );// 因为文本移动,所以此处设置为true
    502. _label->setHorizonCulling(false);// 不需要裁剪
    503. _geo->getPositionAttitudeTransform()->addChild(_label);
    504. mapnode->addChild(_geo.get());
    505. }
    506. bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
    507. {
    508. if ( ea.getEventType() == ea.FRAME )// 此语段为标签添加了动画
    509. {
    510. double t0 = osg::Timer::instance()->time_s();// 儒略日时间
    511. double t = fmod( t0, 6000.0 ) / 6000.0;// t0%6000/6000, 将数字控制在[0,1)范围内
    512. GeoPoint p = _start.interpolate(_end, t);// 差值,在_end和t之间
    513. // GeoMath::bearing 以弧度计算从一个点到下一个点的初始方位
    514. double bearing = GeoMath::bearing(_start.y(), _start.x(), p.y(), p.x());
    515. float a = sin(t0*0.2);// a值没有被用
    516. float pitch = 0.0;
    517. _geo->setPosition(p);
    518. _geo->setLocalRotation(
    519. osg::Quat(pitch, osg::Vec3d(1, 0, 0)) *
    520. osg::Quat(bearing, osg::Vec3d(0, 0, -1)));
    521. }
    522. else if ( ea.getEventType() == ea.KEYDOWN )
    523. {
    524. if ( ea.getKey() == _key )// 8 或 9
    525. {
    526. Viewpoint vp = _manip->getViewpoint();
    527. //vp.setNode( _pat.get() );
    528. vp.setNode(_model);
    529. vp.range() = 25000.0;
    530. vp.pitch() = -45.0;
    531. _manip->setViewpoint(vp, 2.0);// 2秒内飞到指定位置
    532. }
    533. return true;
    534. }
    535. return false;
    536. }
    537. std::string _name;
    538. char _key;
    539. MapNode* _mapnode;
    540. EarthManipulator* _manip;
    541. GeoPoint _start, _end;
    542. LabelNode* _label;
    543. osg::Node* _model;
    544. float _heading;
    545. float _pitch;
    546. osg::ref_ptr _geo;
    547. };
    548. /**
    549. * Place an X at the sim entity position, in screen space.
    550. * The point of this is to test the EarthManipulator::UpdateCameraCallback
    551. * which provides a frame-synched camera matrix (post-update traversal)
    552. */
    553. // 创建一个十字坐标
    554. struct CalculateWindowCoords : public osgGA::GUIEventHandler
    555. {
    556. CalculateWindowCoords(char key, EarthManipulator* manip, Simulator* sim)
    557. : _key(key), _active(false), _sim(sim), _xform(0L)
    558. {
    559. //nop
    560. }
    561. void onUpdateCamera(const osg::Camera* cam)
    562. {
    563. if (_active)
    564. {
    565. if (!_xform)
    566. {
    567. osg::Geometry* geom = new osg::Geometry();
    568. osg::Vec3Array* verts = new osg::Vec3Array();
    569. verts->push_back(osg::Vec3(-10000, 0, 0));
    570. verts->push_back(osg::Vec3( 10000, 0, 0));
    571. verts->push_back(osg::Vec3( 0, -10000, 0));
    572. verts->push_back(osg::Vec3( 0, 10000, 0));
    573. verts->push_back(osg::Vec3( 0, 0, -10000));
    574. verts->push_back(osg::Vec3( 0, 0, 10000));
    575. geom->setVertexArray(verts);
    576. osg::Vec4Array* colors = new osg::Vec4Array();
    577. colors->push_back(osg::Vec4(1, 1, 0, 1));// 黄色线
    578. colors->setBinding(colors->BIND_OVERALL);
    579. geom->setColorArray(colors);
    580. geom->addPrimitiveSet(new osg::DrawArrays(GL_LINES, 0, 6));// 6个点,绘制3条线,但屏幕上仅能看出2条线,水平和垂直
    581. geom->setCullingActive(false);// 不裁剪
    582. geom->getOrCreateStateSet()->setAttributeAndModes(new osg::Depth(osg::Depth::ALWAYS, 0, 1, true), 1);//深度设置
    583. _xform = new osg::MatrixTransform();
    584. _xform->addChild(geom);
    585. osg::View* view = const_cast(cam->getView());
    586. ControlCanvas::getOrCreate(view)->addChild(_xform);
    587. }
    588. /// 坐标变换 V_clip=M_projection⋅M_view⋅M_model⋅V_local 裁剪坐标=透视矩阵*观察矩阵*模型矩阵*本地坐标——来自OpenGL
    589. GeoPoint p = _sim->_geo->getPosition();// 获取thing1的坐标点
    590. osg::Vec3d world;
    591. p.toWorld(world);// 转化为世界坐标
    592. osg::Matrix worldToWindow =
    593. cam->getViewMatrix() *
    594. cam->getProjectionMatrix() *
    595. cam->getViewport()->computeWindowMatrix();// 世界坐标转到窗口坐标
    596. osg::Vec3d win = world * worldToWindow;// 得到窗口坐标
    597. _xform->setMatrix(osg::Matrix::translate(win));
    598. }
    599. }
    600. bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
    601. {
    602. if (ea.getEventType() == ea.KEYDOWN && ea.getKey() == _key)
    603. {
    604. _active = !_active;
    605. aa.requestRedraw();
    606. return true;
    607. }
    608. return false;
    609. }
    610. void getUsage(osg::ApplicationUsage& usage) const
    611. {
    612. using namespace std;
    613. usage.addKeyboardMouseBinding(string(1, _key), string("Show Window Coords"));
    614. }
    615. osg::MatrixTransform* _xform;
    616. Simulator* _sim;
    617. bool _active;
    618. char _key;
    619. };
    620. // 更新相机回调
    621. struct CameraUpdater : public EarthManipulator::UpdateCameraCallback
    622. {
    623. CalculateWindowCoords* _calc;
    624. CameraUpdater(CalculateWindowCoords* calc) : _calc(calc) { }
    625. void onUpdateCamera(const osg::Camera* cam)
    626. {
    627. _calc->onUpdateCamera(cam);// 当物体运动时,需要让十字线跟随物体运动
    628. }
    629. };
    630. }
    631. int main(int argc, char** argv)
    632. {
    633. osg::ArgumentParser arguments(&argc,argv);
    634. if (arguments.read("--help") || argc==1)
    635. {
    636. OE_WARN << "Usage: " << argv[0] << " [earthFile] [--model modelToLoad]"
    637. << std::endl;
    638. return 0;
    639. }
    640. osgViewer::Viewer viewer(arguments);
    641. // install the programmable manipulator.安装操作器
    642. EarthManipulator* manip = new EarthManipulator();
    643. viewer.setCameraManipulator( manip );
    644. // UI: 创建帮助说明控件,在左上角的位置。当鼠标移动到控件上之后,是无法点击到地球上的,没有鼠标穿透功能。
    645. Container* help = createHelp(&viewer);
    646. // MapNodeHelper 显示帮助
    647. // load() 加载earth映射文件并处理所有内置示例命令行参数和XML外部变量(help)。
    648. osg::Node* earthNode = MapNodeHelper().load( arguments, &viewer, help );
    649. if (!earthNode)
    650. {
    651. OE_WARN << "Unable to load earth model." << std::endl;
    652. return -1;
    653. }
    654. osg::Group* root = new osg::Group();
    655. root->addChild( earthNode );
    656. // 获取mapNode
    657. osgEarth::MapNode* mapNode = osgEarth::MapNode::findMapNode( earthNode );
    658. // user model?
    659. // 加载模型,这里传入osg osgt格式的模型,并没有显示
    660. osg::ref_ptr model;
    661. std::string modelFile;
    662. if (arguments.read("--model", modelFile))
    663. model = osgDB::readRefNodeFile(modelFile + ".osgearth_shadergen");
    664. osg::Group* sims = new osg::Group();
    665. root->addChild( sims );
    666. const SpatialReference* wgs84 = SpatialReference::get("wgs84");// 坐标系
    667. // Simulator for tethering: 系留模拟器
    668. // thing 1 和 thing 2 会随着时间移动
    669. Simulator* sim1 = new Simulator(sims, manip, mapNode, model.get(), "Thing 1", '8');// 8:绑住第一个物体
    670. sim1->_name = "Thing 1";
    671. sim1->_start = GeoPoint(wgs84, 45.0, 55.0, 10000);// 开始坐标点
    672. sim1->_end = GeoPoint(wgs84, -45, -55.0, 10000); // 结束坐标点
    673. viewer.addEventHandler(sim1); // 加入到操作器
    674. Simulator* sim2 = new Simulator(sims, manip, mapNode, model.get(), "Thing 2", '9');// 9:绑住第二个物体
    675. sim2->_name = "Thing 2";
    676. sim2->_start = GeoPoint(wgs84, 45.0, 54.0, 10000);
    677. sim2->_end = GeoPoint(wgs84, -44.0, -54.0, 10000);
    678. viewer.addEventHandler(sim2);
    679. manip->getSettings()->getBreakTetherActions().push_back( EarthManipulator::ACTION_GOTO ); // 操作器动作,直接过去
    680. // Set the minimum distance to something larger than the default
    681. // 距离物体小于最小距离时,物体会变大
    682. manip->getSettings()->setMinMaxDistance(10.0, manip->getSettings()->getMaxDistance());
    683. // Sets the maximum focal point offsets (usually for tethering)
    684. manip->getSettings()->setMaxOffset(5000.0, 5000.0);
    685. // Pitch limits. 俯仰角范围
    686. manip->getSettings()->setMinMaxPitch(-90, 90);
    687. viewer.setSceneData( root );
    688. //为 鼠标左键按下、修改键、拖动鼠标的动作指定行为。
    689. manip->getSettings()->bindMouse(
    690. EarthManipulator::ACTION_EARTH_DRAG,
    691. osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON,
    692. osgGA::GUIEventAdapter::MODKEY_SHIFT );
    693. manip->getSettings()->bindMouseClick(
    694. EarthManipulator::ACTION_GOTO,
    695. osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON,
    696. osgGA::GUIEventAdapter::MODKEY_SHIFT);
    697. manip->getSettings()->setArcViewpointTransitions( true );
    698. // 设置tether连接和断裂时的动作回调
    699. manip->setTetherCallback( new TetherCB() );
    700. //viewer.addEventHandler(new FlyToViewpointHandler( manip ));
    701. // 添加 自定义的各个事件处理
    702. viewer.addEventHandler(new LockAzimuthHandler('u', manip));
    703. viewer.addEventHandler(new ToggleArcViewpointTransitionsHandler('a', manip));
    704. viewer.addEventHandler(new ToggleThrowingHandler('q', manip));
    705. viewer.addEventHandler(new ToggleCollisionHandler('k', manip));
    706. viewer.addEventHandler(new ToggleProjMatrix('o', manip));
    707. viewer.addEventHandler(new BreakTetherHandler('b', manip));
    708. viewer.addEventHandler(new CycleTetherMode('t', manip));
    709. viewer.addEventHandler(new SetPositionOffset(manip));// 设置偏移
    710. viewer.addEventHandler(new ToggleLDB('L'));
    711. viewer.addEventHandler(new ToggleSSL(sims, ')'));
    712. viewer.addEventHandler(new FitViewToPoints('j', manip, mapNode->getMapSRS()));
    713. // 根据 thing 1 的位置,更新相机
    714. CalculateWindowCoords* calc = new CalculateWindowCoords('W', manip, sim1);// 根据thing 1计算窗口坐标
    715. viewer.addEventHandler(calc);
    716. manip->setUpdateCameraCallback(new CameraUpdater(calc));// 相机回调
    717. viewer.getCamera()->setSmallFeatureCullingPixelSize(-1.0f);
    718. while(!viewer.done())
    719. {
    720. viewer.frame();
    721. // simulate slow frame rate
    722. //OpenThreads::Thread::microSleep(1000*1000);
    723. }
    724. return 0;
    725. }

  • 相关阅读:
    常用黄芪泡水喝,身体能得到什么?学会搭配,养生效果或会翻倍
    MAC 如何配置 PCL 库并在 VS Code 中使用
    C++的指针
    CANopen扫盲
    11.Mogodb数据库基本使用
    如何确定自己的armbian系统是不是ARM64架构
    Qt基于Qml向左边滑动删除列表项
    【uniapp+vue3+u-picker】获取中国省市区数据结构,省市区数据三级联动json文件完整版,已实现三级联动效果
    【操作系统】第三章 —— 如何管理物理内存
    pytest自动化测试两种执行环境切换的解决方案
  • 原文地址:https://blog.csdn.net/qq_34732729/article/details/128035808