geometryv.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311
  1. /*
  2. * Copyright 2019-2019 Attila Kocsis. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. #include "common.h"
  6. #include <bgfx/bgfx.h>
  7. #include <bx/commandline.h>
  8. #include <bx/easing.h>
  9. #include <bx/file.h>
  10. #include <bx/math.h>
  11. #include <bx/os.h>
  12. #include <bx/settings.h>
  13. #include <entry/entry.h>
  14. #include <entry/input.h>
  15. #include <entry/cmd.h>
  16. #include <entry/dialog.h>
  17. #include <imgui/imgui.h>
  18. #include <debugdraw/debugdraw.h>
  19. #include <bgfx_utils.h>
  20. #include <tinystl/allocator.h>
  21. #include <tinystl/vector.h>
  22. namespace stl = tinystl;
  23. #include <string>
  24. #include <algorithm>
  25. #include <bgfx/embedded_shader.h>
  26. #include "vs_mesh.bin.h"
  27. #include "fs_mesh.bin.h"
  28. #define SCENE_VIEW_ID 0
  29. #define BGFX_GEOMETRYV_VERSION_MAJOR 1
  30. #define BGFX_GEOMETRYV_VERSION_MINOR 0
  31. static const bgfx::EmbeddedShader s_embeddedShaders[] =
  32. {
  33. BGFX_EMBEDDED_SHADER(vs_mesh),
  34. BGFX_EMBEDDED_SHADER(fs_mesh),
  35. BGFX_EMBEDDED_SHADER_END()
  36. };
  37. static const char* s_attribShortNames[] =
  38. {
  39. "P", // Position
  40. "N", // Normal
  41. "T", // Tangent
  42. "B", // Bitangent
  43. "C0", // Color0
  44. "C1", // Color1
  45. "C2", // Color2
  46. "C3", // Color3
  47. "I", // Indices
  48. "W", // Weight
  49. "TC0", // TexCoord0
  50. "TC1", // TexCoord1
  51. "TC2", // TexCoord2
  52. "TC3", // TexCoord3
  53. "TC4", // TexCoord4
  54. "TC5", // TexCoord5
  55. "TC6", // TexCoord6
  56. "TC7", // TexCoord7
  57. };
  58. BX_STATIC_ASSERT(BX_COUNTOF(s_attribShortNames) == bgfx::Attrib::Count);
  59. static const char* s_supportedExt[] =
  60. {
  61. "bin",
  62. };
  63. struct Binding
  64. {
  65. enum Enum
  66. {
  67. App,
  68. View,
  69. Help,
  70. About,
  71. Count
  72. };
  73. };
  74. static const InputBinding s_bindingApp[] =
  75. {
  76. { entry::Key::KeyQ, entry::Modifier::None, 1, NULL, "exit" },
  77. { entry::Key::KeyF, entry::Modifier::None, 1, NULL, "graphics fullscreen" },
  78. INPUT_BINDING_END
  79. };
  80. const char* s_resetCmd =
  81. "view dolly\n"
  82. "view orbit\n"
  83. ;
  84. static const InputBinding s_bindingView[] =
  85. {
  86. { entry::Key::Esc, entry::Modifier::None, 1, NULL, "exit" },
  87. { entry::Key::Key1, entry::Modifier::None, 1, NULL, "view dolly" },
  88. { entry::Key::Key0, entry::Modifier::None, 1, NULL, s_resetCmd },
  89. { entry::Key::Plus, entry::Modifier::None, 1, NULL, "view dolly +0.1" },
  90. { entry::Key::Minus, entry::Modifier::None, 1, NULL, "view dolly -0.1" },
  91. { entry::Key::KeyW, entry::Modifier::None, 1, NULL, "view orbit y -0.1" },
  92. { entry::Key::KeyS, entry::Modifier::None, 1, NULL, "view orbit y +0.1" },
  93. { entry::Key::KeyA, entry::Modifier::None, 1, NULL, "view orbit x +0.1" },
  94. { entry::Key::KeyD, entry::Modifier::None, 1, NULL, "view orbit x -0.1" },
  95. { entry::Key::Up, entry::Modifier::None, 1, NULL, "view file-up" },
  96. { entry::Key::Down, entry::Modifier::None, 1, NULL, "view file-down" },
  97. { entry::Key::KeyI, entry::Modifier::None, 1, NULL, "view info" },
  98. { entry::Key::KeyH, entry::Modifier::None, 1, NULL, "view help" },
  99. { entry::Key::Return, entry::Modifier::None, 1, NULL, "view files" },
  100. { entry::Key::Space, entry::Modifier::None, 1, NULL, "view geo\n" },
  101. INPUT_BINDING_END
  102. };
  103. static const InputBinding s_bindingHelp[] =
  104. {
  105. { entry::Key::Esc, entry::Modifier::None, 1, NULL, "view help" },
  106. { entry::Key::KeyH, entry::Modifier::None, 1, NULL, "view help" },
  107. INPUT_BINDING_END
  108. };
  109. static const InputBinding s_bindingAbout[] =
  110. {
  111. { entry::Key::Esc, entry::Modifier::None, 1, NULL, "view about" },
  112. INPUT_BINDING_END
  113. };
  114. static const char* s_bindingName[] =
  115. {
  116. "App",
  117. "View",
  118. "Help",
  119. "About",
  120. };
  121. BX_STATIC_ASSERT(Binding::Count == BX_COUNTOF(s_bindingName) );
  122. static const InputBinding* s_binding[] =
  123. {
  124. s_bindingApp,
  125. s_bindingView,
  126. s_bindingHelp,
  127. s_bindingAbout,
  128. };
  129. BX_STATIC_ASSERT(Binding::Count == BX_COUNTOF(s_binding) );
  130. static const char* s_filter = ""
  131. "Bgfx geometry (bin) | *.bin\n"
  132. ;
  133. struct Camera
  134. {
  135. Camera()
  136. {
  137. init(bx::Vec3(0.0f,0.0f,0.0f), 2.0f, 0.01f, 100.0f);
  138. }
  139. void init(const bx::Vec3& _center, float _distance, float _near, float _far)
  140. {
  141. m_target.curr = _center;
  142. m_target.dest = _center;
  143. m_pos.curr = _center;
  144. m_pos.curr.z += _distance;
  145. m_pos.dest = _center;
  146. m_pos.dest.z += _distance;
  147. m_orbit[0] = 0.0f;
  148. m_orbit[1] = 0.0f;
  149. m_near = _near;
  150. m_far = _far;
  151. }
  152. void mtxLookAt(float* _outViewMtx)
  153. {
  154. bx::mtxLookAt(_outViewMtx, m_pos.curr, m_target.curr);
  155. }
  156. void orbit(float _dx, float _dy)
  157. {
  158. m_orbit[0] += _dx;
  159. m_orbit[1] += _dy;
  160. }
  161. void distance(float _z)
  162. {
  163. _z = bx::clamp(_z, m_near, m_far);
  164. bx::Vec3 toTarget = bx::sub(m_target.dest, m_pos.dest);
  165. bx::Vec3 toTargetNorm = bx::normalize(toTarget);
  166. m_pos.dest = bx::mad(toTargetNorm, -_z, m_target.dest);
  167. }
  168. void dolly(float _dz)
  169. {
  170. const bx::Vec3 toTarget = bx::sub(m_target.dest, m_pos.dest);
  171. const float toTargetLen = bx::length(toTarget);
  172. const float invToTargetLen = 1.0f / (toTargetLen + bx::kFloatMin);
  173. const bx::Vec3 toTargetNorm = bx::mul(toTarget, invToTargetLen);
  174. float delta = toTargetLen * _dz;
  175. float newLen = toTargetLen - delta;
  176. if ( (m_near < newLen || _dz < 0.0f)
  177. && (newLen < m_far || _dz > 0.0f) )
  178. {
  179. m_pos.dest = bx::mad(toTargetNorm, delta, m_pos.dest);
  180. }
  181. }
  182. void consumeOrbit(float _amount)
  183. {
  184. float consume[2];
  185. consume[0] = m_orbit[0] * _amount;
  186. consume[1] = m_orbit[1] * _amount;
  187. m_orbit[0] -= consume[0];
  188. m_orbit[1] -= consume[1];
  189. const bx::Vec3 toPos = bx::sub(m_pos.curr, m_target.curr);
  190. const float toPosLen = bx::length(toPos);
  191. const float invToPosLen = 1.0f / (toPosLen + bx::kFloatMin);
  192. const bx::Vec3 toPosNorm = bx::mul(toPos, invToPosLen);
  193. float ll[2];
  194. bx::toLatLong(&ll[0], &ll[1], toPosNorm);
  195. ll[0] += consume[0];
  196. ll[1] -= consume[1];
  197. ll[1] = bx::clamp(ll[1], 0.02f, 0.98f);
  198. const bx::Vec3 tmp = bx::fromLatLong(ll[0], ll[1]);
  199. const bx::Vec3 diff = bx::mul(bx::sub(tmp, toPosNorm), toPosLen);
  200. m_pos.curr = bx::add(m_pos.curr, diff);
  201. m_pos.dest = bx::add(m_pos.dest, diff);
  202. }
  203. void update(float _dt)
  204. {
  205. const float amount = bx::min(_dt / 0.12f, 1.0f);
  206. consumeOrbit(amount);
  207. m_target.curr = bx::lerp(m_target.curr, m_target.dest, amount);
  208. m_pos.curr = bx::lerp(m_pos.curr, m_pos.dest, amount);
  209. }
  210. struct Interp3f
  211. {
  212. bx::Vec3 curr;
  213. bx::Vec3 dest;
  214. };
  215. Interp3f m_target;
  216. Interp3f m_pos;
  217. float m_orbit[2];
  218. float m_near, m_far;
  219. };
  220. struct Mouse
  221. {
  222. Mouse()
  223. {
  224. m_dx = 0.0f;
  225. m_dy = 0.0f;
  226. m_prevMx = 0.0f;
  227. m_prevMx = 0.0f;
  228. m_scroll = 0;
  229. m_scrollPrev = 0;
  230. }
  231. void update(float _mx, float _my, int32_t _mz, uint32_t _width, uint32_t _height)
  232. {
  233. const float widthf = float(int32_t(_width));
  234. const float heightf = float(int32_t(_height));
  235. // Delta movement.
  236. m_dx = float(_mx - m_prevMx)/widthf;
  237. m_dy = float(_my - m_prevMy)/heightf;
  238. m_prevMx = _mx;
  239. m_prevMy = _my;
  240. // Scroll.
  241. m_scroll = _mz - m_scrollPrev;
  242. m_scrollPrev = _mz;
  243. }
  244. float m_dx; // Screen space.
  245. float m_dy;
  246. float m_prevMx;
  247. float m_prevMy;
  248. int32_t m_scroll;
  249. int32_t m_scrollPrev;
  250. };
  251. struct View
  252. {
  253. View()
  254. : m_fileIndex(0)
  255. , m_width(1280)
  256. , m_height(720)
  257. , m_help(false)
  258. , m_about(false)
  259. , m_info(false)
  260. , m_files(false)
  261. , m_axes(false)
  262. , m_meshCenter(0.0f,0.0f,0.0f)
  263. , m_meshRadius(1.0f)
  264. , m_idleTimer(0.0f)
  265. {
  266. load();
  267. }
  268. ~View()
  269. {
  270. }
  271. int32_t cmd(int32_t _argc, char const* const* _argv)
  272. {
  273. if (_argc >= 2)
  274. {
  275. if (0 == bx::strCmp(_argv[1], "file-up") )
  276. {
  277. m_fileIndex = bx::uint32_satsub(m_fileIndex, 1);
  278. }
  279. else if (0 == bx::strCmp(_argv[1], "file-down") )
  280. {
  281. uint32_t numFiles = bx::uint32_satsub(uint32_t(m_fileList.size() ), 1);
  282. ++m_fileIndex;
  283. m_fileIndex = bx::uint32_min(m_fileIndex, numFiles);
  284. }
  285. else if (0 == bx::strCmp(_argv[1], "help") )
  286. {
  287. m_help ^= true;
  288. }
  289. else if (0 == bx::strCmp(_argv[1], "about") )
  290. {
  291. m_about ^= true;
  292. }
  293. else if (0 == bx::strCmp(_argv[1], "save") )
  294. {
  295. save();
  296. }
  297. else if (0 == bx::strCmp(_argv[1], "info") )
  298. {
  299. m_info ^= true;
  300. }
  301. else if (0 == bx::strCmp(_argv[1], "files") )
  302. {
  303. m_files ^= true;
  304. }
  305. else if (0 == bx::strCmp(_argv[1], "dolly") )
  306. {
  307. if (_argc >= 3)
  308. {
  309. float dolly;
  310. bx::fromString(&dolly, _argv[2]);
  311. if (_argv[2][0] == '+'
  312. || _argv[2][0] == '-')
  313. {
  314. m_camera.dolly(dolly);
  315. m_idleTimer = 0.0f;
  316. }
  317. }
  318. else
  319. {
  320. m_camera.distance(m_meshRadius * 2.0f);
  321. }
  322. }
  323. else if (0 == bx::strCmp(_argv[1], "orbit") )
  324. {
  325. if (_argc >= 4)
  326. {
  327. int axis = (_argv[2][0] == 'x' ? 0 : 1);
  328. float orbit[2] = { 0.0f, 0.0f};
  329. bx::fromString(&orbit[axis], _argv[3]);
  330. m_camera.orbit(orbit[0], orbit[1]);
  331. m_idleTimer = 0.0f;
  332. }
  333. else
  334. {
  335. m_camera.m_target.dest = m_meshCenter;
  336. m_camera.m_pos.dest = m_meshCenter;
  337. m_camera.m_pos.dest.z -= m_meshRadius * 2.0f;
  338. m_camera.m_orbit[0] = 0.0f;
  339. m_camera.m_orbit[1] = 0.0f;
  340. }
  341. }
  342. else if (0 == bx::strCmp(_argv[1], "axes") )
  343. {
  344. m_axes ^= true;
  345. }
  346. }
  347. return 0;
  348. }
  349. static bool sortNameAscending(const std::string& _lhs, const std::string& _rhs)
  350. {
  351. return 0 > bx::strCmpV(_lhs.c_str(), _rhs.c_str() );
  352. }
  353. void updateFileList(const bx::FilePath& _filePath)
  354. {
  355. bx::DirectoryReader dr;
  356. if (bx::open(&dr, _filePath) )
  357. {
  358. m_path = _filePath;
  359. }
  360. else if (bx::open(&dr, _filePath.getPath() ) )
  361. {
  362. m_path = _filePath.getPath();
  363. }
  364. else
  365. {
  366. DBG("File path `%s` not found.", _filePath.getCPtr() );
  367. return;
  368. }
  369. bx::Error err;
  370. m_fileList.clear();
  371. while (err.isOk() )
  372. {
  373. bx::FileInfo fi;
  374. bx::read(&dr, fi, &err);
  375. if (err.isOk()
  376. && bx::FileType::File == fi.type)
  377. {
  378. bx::StringView ext = fi.filePath.getExt();
  379. if (!ext.isEmpty() )
  380. {
  381. ext.set(ext.getPtr()+1, ext.getTerm() );
  382. bool supported = false;
  383. for (uint32_t ii = 0; ii < BX_COUNTOF(s_supportedExt); ++ii)
  384. {
  385. const bx::StringView supportedExt(s_supportedExt[ii]);
  386. if (0 == bx::strCmpI(bx::max(ext.getPtr(), ext.getTerm() - supportedExt.getLength() ), supportedExt) )
  387. {
  388. supported = true;
  389. break;
  390. }
  391. }
  392. if (supported)
  393. {
  394. const bx::StringView fileName = fi.filePath.getFileName();
  395. m_fileList.push_back(std::string(fileName.getPtr(), fileName.getTerm() ) );
  396. }
  397. }
  398. }
  399. }
  400. bx::close(&dr);
  401. std::sort(m_fileList.begin(), m_fileList.end(), sortNameAscending);
  402. m_fileIndex = 0;
  403. uint32_t idx = 0;
  404. const bx::StringView fileName = _filePath.getFileName();
  405. for (FileList::const_iterator it = m_fileList.begin(); it != m_fileList.end(); ++it, ++idx)
  406. {
  407. if (0 == bx::strCmpI(it->c_str(), fileName) )
  408. {
  409. // If it is case-insensitive match then might be correct one, but keep
  410. // searching.
  411. m_fileIndex = idx;
  412. if (0 == bx::strCmp(it->c_str(), fileName) )
  413. {
  414. // If it is exact match we're done.
  415. break;
  416. }
  417. }
  418. }
  419. }
  420. void load()
  421. {
  422. bx::FilePath filePath(bx::Dir::Home);
  423. filePath.join(".config/bgfx/geometryv.ini");
  424. bx::Settings settings(entry::getAllocator() );
  425. bx::FileReader reader;
  426. if (bx::open(&reader, filePath) )
  427. {
  428. bx::read(&reader, settings);
  429. bx::close(&reader);
  430. if (!bx::fromString(&m_width, settings.get("view/width") ) )
  431. {
  432. m_width = 1280;
  433. }
  434. if (!bx::fromString(&m_height, settings.get("view/height") ) )
  435. {
  436. m_height = 720;
  437. }
  438. }
  439. }
  440. void save()
  441. {
  442. bx::FilePath filePath(bx::Dir::Home);
  443. filePath.join(".config/bgfx/geometryv.ini");
  444. if (bx::makeAll(filePath.getPath() ) )
  445. {
  446. bx::Settings settings(entry::getAllocator() );
  447. char tmp[256];
  448. bx::toString(tmp, sizeof(tmp), m_width);
  449. settings.set("view/width", tmp);
  450. bx::toString(tmp, sizeof(tmp), m_height);
  451. settings.set("view/height", tmp);
  452. bx::FileWriter writer;
  453. if (bx::open(&writer, filePath) )
  454. {
  455. bx::write(&writer, settings);
  456. bx::close(&writer);
  457. }
  458. }
  459. }
  460. bx::FilePath m_path;
  461. typedef stl::vector<std::string> FileList;
  462. FileList m_fileList;
  463. uint32_t m_fileIndex;
  464. uint32_t m_width;
  465. uint32_t m_height;
  466. bool m_help;
  467. bool m_about;
  468. bool m_info;
  469. bool m_files;
  470. bool m_axes;
  471. Camera m_camera;
  472. Mouse m_mouse;
  473. bx::Vec3 m_meshCenter;
  474. float m_meshRadius;
  475. float m_idleTimer;
  476. };
  477. int cmdView(CmdContext* /*_context*/, void* _userData, int _argc, char const* const* _argv)
  478. {
  479. View* view = static_cast<View*>(_userData);
  480. return view->cmd(_argc, _argv);
  481. }
  482. template<bx::LerpFn lerpT, bx::EaseFn easeT>
  483. struct InterpolatorT
  484. {
  485. float from;
  486. float to;
  487. float duration;
  488. int64_t offset;
  489. InterpolatorT(float _value)
  490. {
  491. reset(_value);
  492. }
  493. void reset(float _value)
  494. {
  495. from = _value;
  496. to = _value;
  497. duration = 0.0;
  498. offset = bx::getHPCounter();
  499. }
  500. void set(float _value, float _duration)
  501. {
  502. if (_value != to)
  503. {
  504. from = getValue();
  505. to = _value;
  506. duration = _duration;
  507. offset = bx::getHPCounter();
  508. }
  509. }
  510. float getValue()
  511. {
  512. if (isActive() )
  513. {
  514. const double freq = double(bx::getHPFrequency() );
  515. int64_t now = bx::getHPCounter();
  516. float time = (float)(double(now - offset) / freq);
  517. float lerp = bx::clamp(time, 0.0f, duration) / duration;
  518. return lerpT(from, to, easeT(lerp) );
  519. }
  520. return to;
  521. }
  522. bool isActive() const
  523. {
  524. const double freq = double(bx::getHPFrequency() );
  525. int64_t now = bx::getHPCounter();
  526. float time = (float)(double(now - offset) / freq);
  527. float lerp = bx::clamp(time, 0.0f, duration) / duration;
  528. return lerp < 1.0f;
  529. }
  530. };
  531. typedef InterpolatorT<bx::lerp, bx::easeInOutQuad> Interpolator;
  532. void keyBindingHelp(const char* _bindings, const char* _description)
  533. {
  534. ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "%s", _bindings);
  535. ImGui::SameLine(140);
  536. ImGui::Text("%s", _description);
  537. }
  538. void help(const char* _error = NULL)
  539. {
  540. if (NULL != _error)
  541. {
  542. bx::printf("Error:\n%s\n\n", _error);
  543. }
  544. bx::printf(
  545. "geometryv, bgfx geometry viewer tool, version %d.%d.%d.\n"
  546. "Copyright 2019-2019 Attila Kocsis. All rights reserved.\n"
  547. "License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause\n\n"
  548. , BGFX_GEOMETRYV_VERSION_MAJOR
  549. , BGFX_GEOMETRYV_VERSION_MINOR
  550. , BGFX_API_VERSION
  551. );
  552. bx::printf(
  553. "Usage: geometryv <file path>\n"
  554. "\n"
  555. "Supported input file types:\n"
  556. );
  557. for (uint32_t ii = 0; ii < BX_COUNTOF(s_supportedExt); ++ii)
  558. {
  559. bx::printf(" *.%s\n", s_supportedExt[ii]);
  560. }
  561. bx::printf(
  562. "\n"
  563. "Options:\n"
  564. " -h, --help Help.\n"
  565. " -v, --version Version information only.\n"
  566. "\n"
  567. "For additional information, see https://github.com/bkaradzic/bgfx\n"
  568. );
  569. }
  570. int _main_(int _argc, char** _argv)
  571. {
  572. bx::CommandLine cmdLine(_argc, _argv);
  573. if (cmdLine.hasArg('v', "version") )
  574. {
  575. bx::printf(
  576. "geometryv, bgfx geometry viewer tool, version %d.%d.%d.\n"
  577. , BGFX_GEOMETRYV_VERSION_MAJOR
  578. , BGFX_GEOMETRYV_VERSION_MINOR
  579. , BGFX_API_VERSION
  580. );
  581. return bx::kExitSuccess;
  582. }
  583. if (cmdLine.hasArg('h', "help") )
  584. {
  585. help();
  586. return bx::kExitFailure;
  587. }
  588. uint32_t debug = BGFX_DEBUG_TEXT;
  589. inputAddBindings(s_bindingName[Binding::App], s_binding[Binding::App]);
  590. inputAddBindings(s_bindingName[Binding::View], s_binding[Binding::View]);
  591. View view;
  592. cmdAdd("view", cmdView, &view);
  593. entry::setWindowFlags(entry::WindowHandle{0}, ENTRY_WINDOW_FLAG_ASPECT_RATIO, false);
  594. entry::setWindowSize(entry::WindowHandle{0}, view.m_width, view.m_height);
  595. bgfx::Init init;
  596. init.resolution.width = view.m_width;
  597. init.resolution.width = view.m_height;
  598. init.resolution.reset = 0
  599. | BGFX_RESET_VSYNC
  600. | BGFX_RESET_MSAA_X16
  601. ;
  602. bgfx::init(init);
  603. // Set view 0 clear state.
  604. bgfx::setViewClear(SCENE_VIEW_ID
  605. , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
  606. , 0x000000ff
  607. , 1.0f
  608. , 0
  609. );
  610. imguiCreate();
  611. ddInit();
  612. const bgfx::Caps* caps = bgfx::getCaps();
  613. bgfx::RendererType::Enum type = caps->rendererType;
  614. bgfx::ShaderHandle vsMesh = bgfx::createEmbeddedShader(s_embeddedShaders, type, "vs_mesh");
  615. bgfx::ShaderHandle fsMesh = bgfx::createEmbeddedShader(s_embeddedShaders, type, "fs_mesh");
  616. bgfx::ProgramHandle meshProgram = bgfx::createProgram(
  617. vsMesh
  618. , fsMesh
  619. , true
  620. );
  621. float speed = 0.37f;
  622. float time = 0.0f;
  623. Interpolator menuFade(5.0f);
  624. auto anyActive = [&]() -> bool
  625. {
  626. return false
  627. || ImGui::MouseOverArea()
  628. || menuFade.isActive()
  629. ;
  630. };
  631. const char* filePath = _argc < 2 ? "" : _argv[1];
  632. std::string path = filePath;
  633. {
  634. bx::FilePath fp(filePath);
  635. view.updateFileList(fp);
  636. }
  637. int exitcode = bx::kExitSuccess;
  638. Mesh* mesh = NULL;
  639. {
  640. uint32_t fileIndex = 0;
  641. entry::WindowState windowState;
  642. while (!entry::processWindowEvents(windowState, debug, init.resolution.reset) )
  643. {
  644. const entry::MouseState& mouseState = windowState.m_mouse;
  645. view.m_width = windowState.m_width;
  646. view.m_height = windowState.m_height;
  647. if (!windowState.m_dropFile.isEmpty() )
  648. {
  649. view.updateFileList(windowState.m_dropFile);
  650. windowState.m_dropFile.clear();
  651. }
  652. imguiBeginFrame(mouseState.m_mx
  653. , mouseState.m_my
  654. , (mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0)
  655. | (mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)
  656. | (mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  657. , mouseState.m_mz
  658. , uint16_t(view.m_width)
  659. , uint16_t(view.m_height)
  660. );
  661. bool modalWindow = view.m_help || view.m_about;
  662. bool overArea = false
  663. || ImGui::GetMousePos().y <= ImGui::GetTextLineHeightWithSpacing()
  664. || ImGui::MouseOverArea()
  665. ;
  666. overArea &= !modalWindow;
  667. if (overArea)
  668. {
  669. menuFade.set(5.0f, 0.25f);
  670. }
  671. else if (modalWindow)
  672. {
  673. menuFade.reset(0.0f);
  674. }
  675. else
  676. {
  677. menuFade.set(0.0f, 2.0f);
  678. }
  679. ImGui::PushStyleVar(ImGuiStyleVar_Alpha, bx::clamp(menuFade.getValue(), 0.0f, 1.0f) );
  680. ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0.0f);
  681. if (ImGui::BeginMainMenuBar() )
  682. {
  683. if (ImGui::BeginMenu("File"))
  684. {
  685. if (ImGui::MenuItem("Open File") )
  686. {
  687. bx::FilePath tmp = view.m_path;
  688. if (openFileSelectionDialog(
  689. tmp
  690. , FileSelectionDialogType::Open
  691. , "geometryv: Open File"
  692. , s_filter
  693. ) )
  694. {
  695. view.updateFileList(tmp);
  696. }
  697. }
  698. if (ImGui::MenuItem("Show File List", NULL, view.m_files) )
  699. {
  700. cmdExec("view files");
  701. }
  702. ImGui::Separator();
  703. if (ImGui::MenuItem("Exit") )
  704. {
  705. cmdExec("exit");
  706. }
  707. ImGui::EndMenu();
  708. }
  709. if (ImGui::BeginMenu("View") )
  710. {
  711. if (ImGui::MenuItem("Info", NULL, view.m_info) )
  712. {
  713. cmdExec("view info");
  714. }
  715. if (ImGui::MenuItem("Reset") )
  716. {
  717. cmdExec(s_resetCmd);
  718. }
  719. ImGui::Separator();
  720. bool axes = view.m_axes;
  721. if (ImGui::MenuItem("XYZ Axes", NULL, &axes) )
  722. {
  723. cmdExec("view axes");
  724. }
  725. ImGui::Separator();
  726. if (ImGui::MenuItem("Save Options") )
  727. {
  728. cmdExec("view save");
  729. }
  730. ImGui::EndMenu();
  731. }
  732. if (ImGui::BeginMenu("Help") )
  733. {
  734. if (ImGui::MenuItem("View Help") )
  735. {
  736. cmdExec("view help");
  737. }
  738. ImGui::Separator();
  739. if (ImGui::MenuItem("About") )
  740. {
  741. cmdExec("view about");
  742. }
  743. ImGui::EndMenu();
  744. }
  745. if (0 != view.m_fileList.size() )
  746. {
  747. ImGui::Separator();
  748. ImGui::TextColored(
  749. ImVec4(0.0f, 1.0f, 1.0f, 1.0f)
  750. , "%s"
  751. , view.m_fileList[view.m_fileIndex].c_str()
  752. );
  753. }
  754. ImGui::EndMainMenuBar();
  755. }
  756. ImGui::PopStyleVar(2);
  757. static bool help = false;
  758. static bool about = false;
  759. view.m_mouse.update(float(mouseState.m_mx), float(mouseState.m_my), mouseState.m_mz, view.m_width, view.m_height);
  760. if (!overArea)
  761. {
  762. if (mouseState.m_buttons[entry::MouseButton::Left])
  763. {
  764. view.m_idleTimer = 0.0f;
  765. view.m_camera.orbit(view.m_mouse.m_dx, view.m_mouse.m_dy);
  766. }
  767. else if (mouseState.m_buttons[entry::MouseButton::Right])
  768. {
  769. view.m_idleTimer = 0.0f;
  770. view.m_camera.dolly(view.m_mouse.m_dx + view.m_mouse.m_dy);
  771. }
  772. else if (0 != view.m_mouse.m_scroll)
  773. {
  774. view.m_idleTimer = 0.0f;
  775. view.m_camera.dolly(float(view.m_mouse.m_scroll)*0.1f);
  776. }
  777. }
  778. if (help != view.m_help)
  779. {
  780. if (!help)
  781. {
  782. ImGui::OpenPopup("Help");
  783. inputRemoveBindings(s_bindingName[Binding::View]);
  784. inputAddBindings(s_bindingName[Binding::Help], s_binding[Binding::Help]);
  785. }
  786. else
  787. {
  788. inputRemoveBindings(s_bindingName[Binding::Help]);
  789. inputAddBindings(s_bindingName[Binding::View], s_binding[Binding::View]);
  790. }
  791. help = view.m_help;
  792. }
  793. if (about != view.m_about)
  794. {
  795. if (!about)
  796. {
  797. ImGui::OpenPopup("About");
  798. inputRemoveBindings(s_bindingName[Binding::View]);
  799. inputAddBindings(s_bindingName[Binding::About], s_binding[Binding::About]);
  800. }
  801. else
  802. {
  803. inputRemoveBindings(s_bindingName[Binding::About]);
  804. inputAddBindings(s_bindingName[Binding::View], s_binding[Binding::View]);
  805. }
  806. about = view.m_about;
  807. }
  808. if (view.m_info)
  809. {
  810. ImGui::SetNextWindowSize(
  811. ImVec2(450.0f, 320.0f)
  812. , ImGuiCond_FirstUseEver
  813. );
  814. if (ImGui::Begin("Info", &view.m_info) )
  815. {
  816. if (ImGui::BeginChild("##info", ImVec2(0.0f, 0.0f) ) )
  817. {
  818. if (NULL == mesh)
  819. {
  820. ImGui::Text("Geometry is not loaded.");
  821. }
  822. else
  823. {
  824. char layout[128] = {0};
  825. for(int32_t attrib = bgfx::Attrib::Position; attrib < bgfx::Attrib::Count; attrib++)
  826. {
  827. if ( mesh->m_layout.has(bgfx::Attrib::Enum(attrib)) )
  828. bx::strCat(layout, sizeof(layout), s_attribShortNames[attrib]);
  829. }
  830. ImGui::Text("Name: %s %s", view.m_fileList[view.m_fileIndex].c_str(), layout);
  831. ImGui::Indent();
  832. for (GroupArray::const_iterator itGroup = mesh->m_groups.begin(), itGroupEnd = mesh->m_groups.end(); itGroup != itGroupEnd; ++itGroup)
  833. {
  834. ImGui::Text("Group v %d i %d c %.2f %.2f %.2f r %.2f", itGroup->m_numVertices, itGroup->m_numIndices,
  835. itGroup->m_sphere.center.x, itGroup->m_sphere.center.y, itGroup->m_sphere.center.z,
  836. itGroup->m_sphere.radius);
  837. ImGui::Indent();
  838. for (PrimitiveArray::const_iterator itPrim = itGroup->m_prims.begin(), itPrimEnd = itGroup->m_prims.end(); itPrim != itPrimEnd; ++itPrim)
  839. {
  840. ImGui::Text("Primitive v %d i %d c %.2f %.2f %.2f r %.2f", itPrim->m_numVertices, itPrim->m_numIndices,
  841. itPrim->m_sphere.center.x, itPrim->m_sphere.center.y, itPrim->m_sphere.center.z,
  842. itPrim->m_sphere.radius);
  843. }
  844. ImGui::Unindent();
  845. }
  846. ImGui::Unindent();
  847. ImGui::Separator();
  848. }
  849. ImGui::EndChild();
  850. }
  851. }
  852. ImGui::End();
  853. }
  854. if (view.m_files)
  855. {
  856. char temp[bx::kMaxFilePath];
  857. bx::snprintf(temp, BX_COUNTOF(temp), "%s##File", view.m_path.getCPtr() );
  858. ImGui::SetNextWindowSize(
  859. ImVec2(400.0f, 400.0f)
  860. , ImGuiCond_FirstUseEver
  861. );
  862. if (ImGui::Begin(temp, &view.m_files) )
  863. {
  864. if (ImGui::BeginChild("##file_list", ImVec2(0.0f, 0.0f) ) )
  865. {
  866. ImGui::PushFont(ImGui::Font::Mono);
  867. const float itemHeight = ImGui::GetTextLineHeightWithSpacing();
  868. const float listHeight =
  869. bx::max(1.0f, bx::floor(ImGui::GetWindowHeight()/itemHeight) )
  870. * itemHeight
  871. ;
  872. ImGui::PushItemWidth(-1);
  873. if (ImGui::ListBoxHeader("##empty", ImVec2(0.0f, listHeight) ) )
  874. {
  875. const int32_t itemCount = int32_t(view.m_fileList.size() );
  876. int32_t start, end;
  877. ImGui::CalcListClipping(itemCount, itemHeight, &start, &end);
  878. const int32_t index = int32_t(view.m_fileIndex);
  879. if (index <= start)
  880. {
  881. ImGui::SetScrollY(ImGui::GetScrollY() - (start-index+1)*itemHeight);
  882. }
  883. else if (index >= end)
  884. {
  885. ImGui::SetScrollY(ImGui::GetScrollY() + (index-end+1)*itemHeight);
  886. }
  887. ImGuiListClipper clipper;
  888. clipper.Begin(itemCount, itemHeight);
  889. while (clipper.Step() )
  890. {
  891. for (int32_t pos = clipper.DisplayStart; pos < clipper.DisplayEnd; ++pos)
  892. {
  893. ImGui::PushID(pos);
  894. bool isSelected = uint32_t(pos) == view.m_fileIndex;
  895. if (ImGui::Selectable(view.m_fileList[pos].c_str(), &isSelected) )
  896. {
  897. view.m_fileIndex = pos;
  898. }
  899. ImGui::PopID();
  900. }
  901. }
  902. clipper.End();
  903. ImGui::ListBoxFooter();
  904. }
  905. ImGui::PopFont();
  906. ImGui::EndChild();
  907. }
  908. }
  909. ImGui::End();
  910. }
  911. if (ImGui::BeginPopupModal("About", &view.m_about, ImGuiWindowFlags_AlwaysAutoResize) )
  912. {
  913. ImGui::SetWindowFontScale(1.0f);
  914. ImGui::Text(
  915. "geometryv, bgfx geometry viewer tool " ICON_KI_WRENCH ", version %d.%d.%d.\n"
  916. "Copyright 2019-2019 Attila Kocsis. All rights reserved.\n"
  917. "License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause\n"
  918. , BGFX_GEOMETRYV_VERSION_MAJOR
  919. , BGFX_GEOMETRYV_VERSION_MINOR
  920. , BGFX_API_VERSION
  921. );
  922. ImGui::Dummy(ImVec2(0.0f, 0.0f) );
  923. ImGui::SameLine(ImGui::GetWindowWidth() - 136.0f);
  924. if (ImGui::Button("Close", ImVec2(128.0f, 0.0f) )
  925. || !view.m_about)
  926. {
  927. view.m_about = false;
  928. ImGui::CloseCurrentPopup();
  929. }
  930. ImGui::EndPopup();
  931. }
  932. if (ImGui::BeginPopupModal("Help", &view.m_help, ImGuiWindowFlags_AlwaysAutoResize) )
  933. {
  934. ImGui::SetWindowFontScale(1.0f);
  935. ImGui::Text("Key bindings:\n\n");
  936. ImGui::PushFont(ImGui::Font::Mono);
  937. keyBindingHelp("ESC", "Exit.");
  938. keyBindingHelp("h", "Toggle help screen.");
  939. keyBindingHelp("i", "Toggle info screen.");
  940. keyBindingHelp("f", "Toggle full-screen.");
  941. ImGui::NextLine();
  942. keyBindingHelp("LMB+drag", "Orbit.");
  943. keyBindingHelp("W/A/S/D", "Orbit.");
  944. keyBindingHelp("RMB+drag or MW", "Dolly.");
  945. keyBindingHelp("=/-", "Dolly.");
  946. keyBindingHelp("0", "Reset.");
  947. keyBindingHelp("1", "Fit to window.");
  948. ImGui::NextLine();
  949. keyBindingHelp("up", "Previous geometry.");
  950. keyBindingHelp("down", "Next geometry.");
  951. ImGui::NextLine();
  952. ImGui::NextLine();
  953. ImGui::PopFont();
  954. ImGui::Dummy(ImVec2(0.0f, 0.0f) );
  955. ImGui::SameLine(ImGui::GetWindowWidth() - 136.0f);
  956. if (ImGui::Button("Close", ImVec2(128.0f, 0.0f) )
  957. || !view.m_help)
  958. {
  959. view.m_help = false;
  960. ImGui::CloseCurrentPopup();
  961. }
  962. ImGui::EndPopup();
  963. }
  964. imguiEndFrame();
  965. if ( (NULL == mesh || view.m_fileIndex != fileIndex)
  966. && 0 != view.m_fileList.size() )
  967. {
  968. if (NULL != mesh )
  969. {
  970. meshUnload(mesh);
  971. }
  972. fileIndex = view.m_fileIndex;
  973. bx::FilePath fp = view.m_path;
  974. fp.join(view.m_fileList[view.m_fileIndex].c_str() );
  975. mesh = meshLoad(fp.getCPtr());
  976. std::string title;
  977. if (NULL != mesh )
  978. {
  979. uint32_t numPrimitives = 0;
  980. uint32_t numVertices = 0;
  981. uint32_t numIndices = 0;
  982. Aabb boundingBox = {};
  983. for (GroupArray::const_iterator it = mesh->m_groups.begin(), itEnd = mesh->m_groups.end(); it != itEnd; ++it)
  984. {
  985. if ( it == mesh->m_groups.begin())
  986. {
  987. boundingBox = it->m_aabb;
  988. }
  989. else
  990. {
  991. aabbExpand(boundingBox, it->m_aabb.min);
  992. aabbExpand(boundingBox, it->m_aabb.max);
  993. }
  994. numPrimitives += (uint32_t)it->m_prims.size();
  995. numVertices += (uint32_t)it->m_numVertices;
  996. numIndices += (uint32_t)it->m_numIndices;
  997. }
  998. bx::stringPrintf(
  999. title
  1000. , "%s (g %d, p %d, v %d, i %d)"
  1001. , fp.getCPtr()
  1002. , mesh->m_groups.size()
  1003. , numPrimitives
  1004. , numVertices
  1005. , numIndices
  1006. );
  1007. view.m_meshCenter = getCenter(boundingBox);
  1008. view.m_meshRadius = bx::length(getExtents(boundingBox));
  1009. view.m_camera.init( view.m_meshCenter, view.m_meshRadius * 2.0f, 0.01f, view.m_meshRadius * 10.0f);
  1010. }
  1011. else
  1012. {
  1013. bx::stringPrintf(title, "Failed to load %s!", filePath);
  1014. }
  1015. entry::WindowHandle handle = { 0 };
  1016. entry::setWindowTitle(handle, title.c_str() );
  1017. }
  1018. int64_t now = bx::getHPCounter();
  1019. static int64_t last = now;
  1020. const int64_t frameTime = now - last;
  1021. last = now;
  1022. const double freq = double(bx::getHPFrequency() );
  1023. const float deltaTime = float(frameTime/freq);
  1024. time += (float)(frameTime*speed/freq);
  1025. // Update camera.
  1026. float viewMatrix[16];
  1027. view.m_camera.update(deltaTime);
  1028. view.m_camera.mtxLookAt(viewMatrix);
  1029. float projMatrix[16];
  1030. const float aspect = float(view.m_width)/float(view.m_height);
  1031. bx::mtxProj(projMatrix, 60.0f, aspect, 0.01f, 1000.0f, caps->homogeneousDepth);
  1032. bgfx::setViewTransform(SCENE_VIEW_ID, viewMatrix, projMatrix);
  1033. bgfx::setViewRect(SCENE_VIEW_ID, 0, 0, uint16_t(view.m_width), uint16_t(view.m_height) );
  1034. bgfx::touch(SCENE_VIEW_ID);
  1035. if ( view.m_axes )
  1036. {
  1037. DebugDrawEncoder dde;
  1038. dde.begin(SCENE_VIEW_ID);
  1039. dde.drawAxis(0.0f, 0.0f, 0.0f);
  1040. dde.drawGrid(Axis::Y, {0.0f, 0.0f, 0.0f});
  1041. dde.end();
  1042. }
  1043. bgfx::dbgTextClear();
  1044. float orientation[16];
  1045. bx::mtxIdentity(orientation);
  1046. bgfx::setTransform(orientation);
  1047. float mtx[16];
  1048. bx::mtxIdentity(mtx);
  1049. if (NULL != mesh)
  1050. {
  1051. meshSubmit(mesh
  1052. , SCENE_VIEW_ID
  1053. , meshProgram
  1054. , mtx);
  1055. }
  1056. bgfx::frame();
  1057. // Slow down when nothing is animating...
  1058. if (view.m_idleTimer > 2.0f
  1059. && !anyActive() )
  1060. {
  1061. bx::sleep(100);
  1062. }
  1063. view.m_idleTimer += deltaTime;
  1064. }
  1065. }
  1066. if (NULL != mesh )
  1067. {
  1068. meshUnload(mesh);
  1069. }
  1070. bgfx::destroy(meshProgram);
  1071. ddShutdown();
  1072. imguiDestroy();
  1073. bgfx::shutdown();
  1074. return exitcode;
  1075. }