example.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161
  1. #include <igl/draw_skeleton_3d.h>
  2. #include <igl/draw_skeleton_vector_graphics.h>
  3. #include <igl/two_axis_valuator_fixed_up.h>
  4. #include <igl/read_triangle_mesh.h>
  5. #include <igl/readTGF.h>
  6. #include <igl/writeOBJ.h>
  7. #include <igl/writeOFF.h>
  8. #include <igl/report_gl_error.h>
  9. #include <igl/draw_mesh.h>
  10. #include <igl/draw_floor.h>
  11. #include <igl/pathinfo.h>
  12. #include <igl/list_to_matrix.h>
  13. #include <igl/quat_to_mat.h>
  14. #include <igl/per_face_normals.h>
  15. #include <igl/material_colors.h>
  16. #include <igl/trackball.h>
  17. #include <igl/snap_to_canonical_view_quat.h>
  18. #include <igl/snap_to_fixed_up.h>
  19. #include <igl/REDRUM.h>
  20. #include <igl/Camera.h>
  21. #include <igl/ReAntTweakBar.h>
  22. #include <igl/get_seconds.h>
  23. #include <igl/forward_kinematics.h>
  24. #include <igl/boundary_conditions.h>
  25. #include <igl/normalize_row_sums.h>
  26. #include <igl/lbs_matrix.h>
  27. #include <igl/sort_triangles.h>
  28. #include <igl/slice.h>
  29. #include <igl/project.h>
  30. #include <igl/unproject.h>
  31. #include <igl/embree/EmbreeIntersector.h>
  32. #include <igl/embree/unproject_in_mesh.h>
  33. #include <igl/matlab_format.h>
  34. #include <igl/remove_unreferenced.h>
  35. #include <igl/adjacency_list.h>
  36. #include <igl/adjacency_matrix.h>
  37. #include <igl/right_axis.h>
  38. #include <igl/colon.h>
  39. #include <igl/unique.h>
  40. #include <igl/REDRUM.h>
  41. #include <igl/writeTGF.h>
  42. #include <igl/file_exists.h>
  43. #include <igl/centroid.h>
  44. #include <Eigen/Core>
  45. #include <Eigen/Geometry>
  46. #ifdef __APPLE__
  47. #include <GLUT/glut.h>
  48. #include <Carbon/Carbon.h>
  49. #else
  50. #include <GL/glut.h>
  51. #endif
  52. #include <string>
  53. #include <vector>
  54. #include <queue>
  55. #include <stack>
  56. #include <iostream>
  57. enum SkelStyleType
  58. {
  59. SKEL_STYLE_TYPE_3D = 0,
  60. SKEL_STYLE_TYPE_VECTOR_GRAPHICS = 1,
  61. NUM_SKEL_STYLE_TYPE = 2
  62. }skel_style;
  63. Eigen::MatrixXd V,N,sorted_N;
  64. Eigen::Vector3d Vmid,Vcen;
  65. double bbd = 1.0;
  66. Eigen::MatrixXi F,sorted_F;
  67. Eigen::VectorXi P;
  68. igl::Camera camera;
  69. struct State
  70. {
  71. Eigen::MatrixXd C;
  72. Eigen::MatrixXi BE;
  73. Eigen::VectorXi sel;
  74. } s;
  75. bool wireframe = false;
  76. bool skeleton_on_top = false;
  77. double alpha = 0.5;
  78. // See README for descriptions
  79. enum RotationType
  80. {
  81. ROTATION_TYPE_IGL_TRACKBALL = 0,
  82. ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP = 1,
  83. NUM_ROTATION_TYPES = 2,
  84. } rotation_type = ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP;
  85. std::stack<State> undo_stack;
  86. std::stack<State> redo_stack;
  87. bool is_rotating = false;
  88. bool is_dragging = false;
  89. bool new_leaf_on_drag = false;
  90. bool new_root_on_drag = false;
  91. int down_x,down_y;
  92. Eigen::MatrixXd down_C;
  93. igl::Camera down_camera;
  94. std::string output_filename;
  95. bool is_animating = false;
  96. double animation_start_time = 0;
  97. double ANIMATION_DURATION = 0.5;
  98. Eigen::Quaterniond animation_from_quat;
  99. Eigen::Quaterniond animation_to_quat;
  100. int width,height;
  101. Eigen::Vector4f light_pos(-0.1,-0.1,0.9,0);
  102. #define REBAR_NAME "temp.rbr"
  103. igl::ReTwBar rebar;
  104. igl::EmbreeIntersector ei;
  105. void push_undo()
  106. {
  107. undo_stack.push(s);
  108. // Clear
  109. redo_stack = std::stack<State>();
  110. }
  111. // No-op setter, does nothing
  112. void TW_CALL no_op(const void * /*value*/, void * /*clientData*/)
  113. {
  114. }
  115. void TW_CALL set_rotation_type(const void * value, void * clientData)
  116. {
  117. using namespace Eigen;
  118. using namespace std;
  119. using namespace igl;
  120. const RotationType old_rotation_type = rotation_type;
  121. rotation_type = *(const RotationType *)(value);
  122. if(rotation_type == ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP &&
  123. old_rotation_type != ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP)
  124. {
  125. push_undo();
  126. animation_from_quat = camera.m_rotation_conj;
  127. snap_to_fixed_up(animation_from_quat,animation_to_quat);
  128. // start animation
  129. animation_start_time = get_seconds();
  130. is_animating = true;
  131. }
  132. }
  133. void TW_CALL get_rotation_type(void * value, void *clientData)
  134. {
  135. RotationType * rt = (RotationType *)(value);
  136. *rt = rotation_type;
  137. }
  138. void reshape(int width, int height)
  139. {
  140. ::width = width;
  141. ::height = height;
  142. glViewport(0,0,width,height);
  143. // Send the new window size to AntTweakBar
  144. TwWindowSize(width, height);
  145. camera.m_aspect = (double)width/(double)height;
  146. }
  147. void push_scene()
  148. {
  149. using namespace igl;
  150. using namespace std;
  151. glMatrixMode(GL_PROJECTION);
  152. glPushMatrix();
  153. glLoadIdentity();
  154. gluPerspective(camera.m_angle,camera.m_aspect,camera.m_near,camera.m_far);
  155. glMatrixMode(GL_MODELVIEW);
  156. glPushMatrix();
  157. glLoadIdentity();
  158. gluLookAt(
  159. camera.eye()(0), camera.eye()(1), camera.eye()(2),
  160. camera.at()(0), camera.at()(1), camera.at()(2),
  161. camera.up()(0), camera.up()(1), camera.up()(2));
  162. }
  163. void push_object()
  164. {
  165. using namespace igl;
  166. glPushMatrix();
  167. glScaled(2./bbd,2./bbd,2./bbd);
  168. glTranslated(-Vmid(0),-Vmid(1),-Vmid(2));
  169. }
  170. void pop_object()
  171. {
  172. glPopMatrix();
  173. }
  174. void pop_scene()
  175. {
  176. glMatrixMode(GL_PROJECTION);
  177. glPopMatrix();
  178. glMatrixMode(GL_MODELVIEW);
  179. glPopMatrix();
  180. }
  181. // Set up double-sided lights
  182. void lights()
  183. {
  184. using namespace std;
  185. using namespace Eigen;
  186. glEnable(GL_LIGHTING);
  187. glLightModelf(GL_LIGHT_MODEL_TWO_SIDE,GL_TRUE);
  188. glEnable(GL_LIGHT0);
  189. glEnable(GL_LIGHT1);
  190. float WHITE[4] = {0.8,0.8,0.8,1.};
  191. float GREY[4] = {0.4,0.4,0.4,1.};
  192. float BLACK[4] = {0.,0.,0.,1.};
  193. Vector4f pos = light_pos;
  194. glLightfv(GL_LIGHT0,GL_AMBIENT,GREY);
  195. glLightfv(GL_LIGHT0,GL_DIFFUSE,WHITE);
  196. glLightfv(GL_LIGHT0,GL_SPECULAR,BLACK);
  197. glLightfv(GL_LIGHT0,GL_POSITION,pos.data());
  198. pos(0) *= -1;
  199. pos(1) *= -1;
  200. pos(2) *= -1;
  201. glLightfv(GL_LIGHT1,GL_AMBIENT,GREY);
  202. glLightfv(GL_LIGHT1,GL_DIFFUSE,WHITE);
  203. glLightfv(GL_LIGHT1,GL_SPECULAR,BLACK);
  204. glLightfv(GL_LIGHT1,GL_POSITION,pos.data());
  205. }
  206. void sort()
  207. {
  208. using namespace std;
  209. using namespace Eigen;
  210. using namespace igl;
  211. push_scene();
  212. push_object();
  213. VectorXi I;
  214. sort_triangles(V,F,sorted_F,I);
  215. slice(N,I,1,sorted_N);
  216. pop_object();
  217. pop_scene();
  218. }
  219. void display()
  220. {
  221. using namespace igl;
  222. using namespace std;
  223. using namespace Eigen;
  224. const float back[4] = {0.75, 0.75, 0.75,0};
  225. glClearColor(back[0],back[1],back[2],0);
  226. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  227. static bool first = true;
  228. if(first)
  229. {
  230. sort();
  231. first = false;
  232. }
  233. if(is_animating)
  234. {
  235. double t = (get_seconds() - animation_start_time)/ANIMATION_DURATION;
  236. if(t > 1)
  237. {
  238. t = 1;
  239. is_animating = false;
  240. }
  241. Quaterniond q = animation_from_quat.slerp(t,animation_to_quat).normalized();
  242. camera.orbit(q.conjugate());
  243. }
  244. glEnable(GL_DEPTH_TEST);
  245. glDepthFunc(GL_LEQUAL);
  246. glEnable(GL_NORMALIZE);
  247. glEnable(GL_BLEND);
  248. glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  249. lights();
  250. push_scene();
  251. // Draw a nice floor
  252. glEnable(GL_DEPTH_TEST);
  253. glPushMatrix();
  254. const double floor_offset =
  255. -2./bbd*(V.col(1).maxCoeff()-Vmid(1));
  256. glTranslated(0,floor_offset,0);
  257. const float GREY[4] = {0.5,0.5,0.6,1.0};
  258. const float DARK_GREY[4] = {0.2,0.2,0.3,1.0};
  259. glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
  260. glEnable(GL_CULL_FACE);
  261. glCullFace(GL_BACK);
  262. draw_floor(GREY,DARK_GREY);
  263. glDisable(GL_CULL_FACE);
  264. glPopMatrix();
  265. push_object();
  266. const auto & draw_skeleton = []()
  267. {
  268. switch(skel_style)
  269. {
  270. default:
  271. case SKEL_STYLE_TYPE_3D:
  272. {
  273. MatrixXf colors = MAYA_VIOLET.transpose().replicate(s.BE.rows(),1);
  274. for(int si=0;si<s.sel.size();si++)
  275. {
  276. for(int b=0;b<s.BE.rows();b++)
  277. {
  278. if(s.BE(b,0) == s.sel(si) || s.BE(b,1) == s.sel(si))
  279. {
  280. colors.row(b) = MAYA_SEA_GREEN;
  281. }
  282. }
  283. }
  284. draw_skeleton_3d(s.C,s.BE,MatrixXd(),colors);
  285. break;
  286. }
  287. case SKEL_STYLE_TYPE_VECTOR_GRAPHICS:
  288. draw_skeleton_vector_graphics(s.C,s.BE);
  289. break;
  290. }
  291. };
  292. if(!skeleton_on_top)
  293. {
  294. draw_skeleton();
  295. }
  296. // Set material properties
  297. glDisable(GL_COLOR_MATERIAL);
  298. glMaterialfv(GL_FRONT, GL_AMBIENT,
  299. Vector4f(GOLD_AMBIENT[0],GOLD_AMBIENT[1],GOLD_AMBIENT[2],alpha).data());
  300. glMaterialfv(GL_FRONT, GL_DIFFUSE,
  301. Vector4f(GOLD_DIFFUSE[0],GOLD_DIFFUSE[1],GOLD_DIFFUSE[2],alpha).data());
  302. glMaterialfv(GL_FRONT, GL_SPECULAR,
  303. Vector4f(GOLD_SPECULAR[0],GOLD_SPECULAR[1],GOLD_SPECULAR[2],alpha).data());
  304. glMaterialf (GL_FRONT, GL_SHININESS, 128);
  305. glMaterialfv(GL_BACK, GL_AMBIENT,
  306. Vector4f(SILVER_AMBIENT[0],SILVER_AMBIENT[1],SILVER_AMBIENT[2],alpha).data());
  307. glMaterialfv(GL_BACK, GL_DIFFUSE,
  308. Vector4f(FAST_GREEN_DIFFUSE[0],FAST_GREEN_DIFFUSE[1],FAST_GREEN_DIFFUSE[2],alpha).data());
  309. glMaterialfv(GL_BACK, GL_SPECULAR,
  310. Vector4f(SILVER_SPECULAR[0],SILVER_SPECULAR[1],SILVER_SPECULAR[2],alpha).data());
  311. glMaterialf (GL_BACK, GL_SHININESS, 128);
  312. if(wireframe)
  313. {
  314. glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
  315. }
  316. glLineWidth(1.0);
  317. draw_mesh(V,sorted_F,sorted_N);
  318. glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
  319. if(skeleton_on_top)
  320. {
  321. glDisable(GL_DEPTH_TEST);
  322. draw_skeleton();
  323. }
  324. pop_object();
  325. pop_scene();
  326. report_gl_error();
  327. TwDraw();
  328. glutSwapBuffers();
  329. if(is_animating)
  330. {
  331. glutPostRedisplay();
  332. }
  333. }
  334. void mouse_wheel(int wheel, int direction, int mouse_x, int mouse_y)
  335. {
  336. using namespace std;
  337. using namespace igl;
  338. using namespace Eigen;
  339. GLint viewport[4];
  340. glGetIntegerv(GL_VIEWPORT,viewport);
  341. if(wheel == 0 && TwMouseMotion(mouse_x, viewport[3] - mouse_y))
  342. {
  343. static double mouse_scroll_y = 0;
  344. const double delta_y = 0.125*direction;
  345. mouse_scroll_y += delta_y;
  346. TwMouseWheel(mouse_scroll_y);
  347. return;
  348. }
  349. push_undo();
  350. if(wheel==0)
  351. {
  352. // factor of zoom change
  353. double s = (1.-0.01*direction);
  354. //// FOV zoom: just widen angle. This is hardly ever appropriate.
  355. //camera.m_angle *= s;
  356. //camera.m_angle = min(max(camera.m_angle,1),89);
  357. camera.push_away(s);
  358. }else
  359. {
  360. // Dolly zoom:
  361. camera.dolly_zoom((double)direction*1.0);
  362. }
  363. glutPostRedisplay();
  364. }
  365. Eigen::VectorXi selection(const std::vector<bool> & mask)
  366. {
  367. const int count = std::count(mask.begin(),mask.end(),true);
  368. Eigen::VectorXi sel(count);
  369. int s = 0;
  370. for(int c = 0;c<(int)mask.size();c++)
  371. {
  372. if(mask[c])
  373. {
  374. sel(s) = c;
  375. s++;
  376. }
  377. }
  378. return sel;
  379. }
  380. std::vector<bool> selection_mask(const Eigen::VectorXi & sel, const int n)
  381. {
  382. std::vector<bool> mask(n,false);
  383. for(int si = 0;si<sel.size();si++)
  384. {
  385. const int i = sel(si);
  386. mask[i] = true;
  387. }
  388. return mask;
  389. }
  390. bool ss_select(
  391. const double mouse_x,
  392. const double mouse_y,
  393. const Eigen::MatrixXd & C,
  394. const bool accum,
  395. Eigen::VectorXi & sel)
  396. {
  397. using namespace igl;
  398. using namespace Eigen;
  399. using namespace std;
  400. //// zap old list
  401. //if(!accum)
  402. //{
  403. // sel.resize(0,1);
  404. //}
  405. vector<bool> old_mask = selection_mask(s.sel,s.C.rows());
  406. vector<bool> mask(old_mask.size(),false);
  407. double min_dist = 1e25;
  408. bool sel_changed = false;
  409. bool found = false;
  410. for(int c = 0;c<C.rows();c++)
  411. {
  412. const RowVector3d & Cc = C.row(c);
  413. const auto Pc = project(Cc);
  414. const double SELECTION_DIST = 18;//pixels
  415. const double dist = (Pc.head(2)-RowVector2d(mouse_x,height-mouse_y)).norm();
  416. if(dist < SELECTION_DIST && (accum || dist < min_dist))
  417. {
  418. mask[c] = true;
  419. min_dist = dist;
  420. found = true;
  421. sel_changed |= mask[c] != old_mask[c];
  422. }
  423. }
  424. for(int c = 0;c<C.rows();c++)
  425. {
  426. if(accum)
  427. {
  428. mask[c] = mask[c] ^ old_mask[c];
  429. }else
  430. {
  431. if(!sel_changed)
  432. {
  433. mask[c] = mask[c] || old_mask[c];
  434. }
  435. }
  436. }
  437. sel = selection(mask);
  438. return found;
  439. }
  440. void mouse(int glutButton, int glutState, int mouse_x, int mouse_y)
  441. {
  442. using namespace std;
  443. using namespace Eigen;
  444. using namespace igl;
  445. bool tw_using = TwEventMouseButtonGLUT(glutButton,glutState,mouse_x,mouse_y);
  446. const int mod = (glutButton <=2 ? glutGetModifiers() : 0);
  447. const bool option_down = mod & GLUT_ACTIVE_ALT;
  448. const bool shift_down = mod & GLUT_ACTIVE_SHIFT;
  449. const bool command_down = GLUT_ACTIVE_COMMAND & mod;
  450. switch(glutButton)
  451. {
  452. case GLUT_RIGHT_BUTTON:
  453. case GLUT_LEFT_BUTTON:
  454. {
  455. switch(glutState)
  456. {
  457. case 1:
  458. // up
  459. glutSetCursor(GLUT_CURSOR_INHERIT);
  460. if(is_rotating)
  461. {
  462. sort();
  463. }
  464. is_rotating = false;
  465. is_dragging = false;
  466. break;
  467. case 0:
  468. new_leaf_on_drag = false;
  469. new_root_on_drag = false;
  470. if(!tw_using)
  471. {
  472. down_x = mouse_x;
  473. down_y = mouse_y;
  474. if(option_down)
  475. {
  476. glutSetCursor(GLUT_CURSOR_CYCLE);
  477. // collect information for trackball
  478. is_rotating = true;
  479. down_camera = camera;
  480. }else
  481. {
  482. push_undo();
  483. push_scene();
  484. push_object();
  485. // Zap selection
  486. if(shift_down)
  487. {
  488. s.sel.resize(0,1);
  489. }
  490. if(ss_select(mouse_x,mouse_y,s.C,
  491. command_down && !shift_down,
  492. s.sel))
  493. {
  494. if(shift_down)
  495. {
  496. new_leaf_on_drag = true;
  497. }
  498. }else
  499. {
  500. new_root_on_drag = true;
  501. }
  502. is_dragging = !command_down;
  503. down_C = s.C;
  504. pop_object();
  505. pop_scene();
  506. }
  507. }
  508. break;
  509. }
  510. break;
  511. }
  512. // Scroll down
  513. case 3:
  514. {
  515. mouse_wheel(0,-1,mouse_x,mouse_y);
  516. break;
  517. }
  518. // Scroll up
  519. case 4:
  520. {
  521. mouse_wheel(0,1,mouse_x,mouse_y);
  522. break;
  523. }
  524. // Scroll left
  525. case 5:
  526. {
  527. mouse_wheel(1,-1,mouse_x,mouse_y);
  528. break;
  529. }
  530. // Scroll right
  531. case 6:
  532. {
  533. mouse_wheel(1,1,mouse_x,mouse_y);
  534. break;
  535. }
  536. }
  537. glutPostRedisplay();
  538. }
  539. void mouse_drag(int mouse_x, int mouse_y)
  540. {
  541. using namespace igl;
  542. using namespace std;
  543. using namespace Eigen;
  544. if(is_rotating)
  545. {
  546. glutSetCursor(GLUT_CURSOR_CYCLE);
  547. Quaterniond q;
  548. switch(rotation_type)
  549. {
  550. case ROTATION_TYPE_IGL_TRACKBALL:
  551. {
  552. // Rotate according to trackball
  553. igl::trackball<double>(
  554. width,
  555. height,
  556. 2.0,
  557. down_camera.m_rotation_conj.coeffs().data(),
  558. down_x,
  559. down_y,
  560. mouse_x,
  561. mouse_y,
  562. q.coeffs().data());
  563. break;
  564. }
  565. case ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP:
  566. {
  567. // Rotate according to two axis valuator with fixed up vector
  568. two_axis_valuator_fixed_up(
  569. width, height,
  570. 2.0,
  571. down_camera.m_rotation_conj,
  572. down_x, down_y, mouse_x, mouse_y,
  573. q);
  574. break;
  575. }
  576. default:
  577. break;
  578. }
  579. camera.orbit(q.conjugate());
  580. }
  581. if(is_dragging)
  582. {
  583. push_scene();
  584. push_object();
  585. if(new_leaf_on_drag)
  586. {
  587. assert(s.C.size() >= 1);
  588. // one new node
  589. s.C.conservativeResize(s.C.rows()+1,3);
  590. const int nc = s.C.rows();
  591. assert(s.sel.size() >= 1);
  592. s.C.row(nc-1) = s.C.row(s.sel(0));
  593. // one new bone
  594. s.BE.conservativeResize(s.BE.rows()+1,2);
  595. s.BE.row(s.BE.rows()-1) = RowVector2i(s.sel(0),nc-1);
  596. // select just last node
  597. s.sel.resize(1,1);
  598. s.sel(0) = nc-1;
  599. // reset down_C
  600. down_C = s.C;
  601. new_leaf_on_drag = false;
  602. }
  603. if(new_root_on_drag)
  604. {
  605. // two new nodes
  606. s.C.conservativeResize(s.C.rows()+2,3);
  607. const int nc = s.C.rows();
  608. Vector3d obj;
  609. int nhits = unproject_in_mesh(mouse_x,height-mouse_y,ei,obj);
  610. if(nhits == 0)
  611. {
  612. Vector3d pV_mid = project(Vcen);
  613. obj = unproject(Vector3d(mouse_x,height-mouse_y,pV_mid(2)));
  614. }
  615. s.C.row(nc-2) = obj;
  616. s.C.row(nc-1) = obj;
  617. // select last node
  618. s.sel.resize(1,1);
  619. s.sel(0) = nc-1;
  620. // one new bone
  621. s.BE.conservativeResize(s.BE.rows()+1,2);
  622. s.BE.row(s.BE.rows()-1) = RowVector2i(nc-2,nc-1);
  623. // reset down_C
  624. down_C = s.C;
  625. new_root_on_drag = false;
  626. }
  627. double z = 0;
  628. Vector3d obj,win;
  629. int nhits = unproject_in_mesh(mouse_x,height-mouse_y,ei,obj);
  630. project(obj,win);
  631. z = win(2);
  632. for(int si = 0;si<s.sel.size();si++)
  633. {
  634. const int c = s.sel(si);
  635. Vector3d pc = project((RowVector3d) down_C.row(c));
  636. pc(0) += mouse_x-down_x;
  637. pc(1) += (height-mouse_y)-(height-down_y);
  638. if(nhits > 0)
  639. {
  640. pc(2) = z;
  641. }
  642. s.C.row(c) = unproject(pc);
  643. }
  644. pop_object();
  645. pop_scene();
  646. }
  647. glutPostRedisplay();
  648. }
  649. void init_relative()
  650. {
  651. using namespace Eigen;
  652. using namespace igl;
  653. using namespace std;
  654. per_face_normals(V,F,N);
  655. const auto Vmax = V.colwise().maxCoeff();
  656. const auto Vmin = V.colwise().minCoeff();
  657. Vmid = 0.5*(Vmax + Vmin);
  658. centroid(V,F,Vcen);
  659. bbd = (Vmax-Vmin).norm();
  660. camera.push_away(2);
  661. }
  662. void undo()
  663. {
  664. using namespace std;
  665. if(!undo_stack.empty())
  666. {
  667. redo_stack.push(s);
  668. s = undo_stack.top();
  669. undo_stack.pop();
  670. }
  671. }
  672. void redo()
  673. {
  674. using namespace std;
  675. if(!redo_stack.empty())
  676. {
  677. undo_stack.push(s);
  678. s = redo_stack.top();
  679. redo_stack.pop();
  680. }
  681. }
  682. void symmetrize()
  683. {
  684. using namespace std;
  685. using namespace igl;
  686. using namespace Eigen;
  687. if(s.sel.size() == 0)
  688. {
  689. cout<<YELLOWGIN("Make a selection first.")<<endl;
  690. return;
  691. }
  692. push_undo();
  693. push_scene();
  694. push_object();
  695. Vector3d right;
  696. right_axis(right.data(),right.data()+1,right.data()+2);
  697. right.normalize();
  698. MatrixXd RC(s.C.rows(),s.C.cols());
  699. MatrixXd old_C = s.C;
  700. for(int c = 0;c<s.C.rows();c++)
  701. {
  702. const Vector3d Cc = s.C.row(c);
  703. const auto A = Cc-Vcen;
  704. const auto A1 = A.dot(right) * right;
  705. const auto A2 = A-A1;
  706. RC.row(c) = Vcen + A2 - A1;
  707. }
  708. vector<bool> mask = selection_mask(s.sel,s.C.rows());
  709. // stupid O(n²) matching
  710. for(int c = 0;c<s.C.rows();c++)
  711. {
  712. // not selected
  713. if(!mask[c])
  714. {
  715. continue;
  716. }
  717. const Vector3d Cc = s.C.row(c);
  718. int min_r = -1;
  719. double min_dist = 1e25;
  720. double max_dist = 0.1*bbd;
  721. for(int r= 0;r<RC.rows();r++)
  722. {
  723. const Vector3d RCr = RC.row(r);
  724. const double dist = (Cc-RCr).norm();
  725. if(
  726. dist<min_dist && // closest
  727. dist<max_dist && // not too far away
  728. (c==r || (Cc-Vcen).dot(right)*(RCr-Vcen).dot(right) > 0) // on same side
  729. )
  730. {
  731. min_dist = dist;
  732. min_r = r;
  733. }
  734. }
  735. if(min_r>=0)
  736. {
  737. if(mask[min_r])
  738. {
  739. s.C.row(c) = 0.5*(Cc.transpose()+RC.row(min_r));
  740. }else
  741. {
  742. s.C.row(c) = RC.row(min_r);
  743. }
  744. }
  745. }
  746. pop_object();
  747. pop_scene();
  748. }
  749. bool save()
  750. {
  751. using namespace std;
  752. using namespace igl;
  753. if(writeTGF(output_filename,s.C,s.BE))
  754. {
  755. cout<<GREENGIN("Current skeleton written to "+output_filename+".")<<endl;
  756. return true;
  757. }else
  758. {
  759. cout<<REDRUM("Writing to "+output_filename+" failed.")<<endl;
  760. return false;
  761. }
  762. }
  763. void key(unsigned char key, int mouse_x, int mouse_y)
  764. {
  765. using namespace std;
  766. using namespace igl;
  767. using namespace Eigen;
  768. int mod = glutGetModifiers();
  769. const bool command_down = GLUT_ACTIVE_COMMAND & mod;
  770. const bool shift_down = GLUT_ACTIVE_SHIFT & mod;
  771. switch(key)
  772. {
  773. // ESC
  774. case char(27):
  775. rebar.save(REBAR_NAME);
  776. // ^C
  777. case char(3):
  778. exit(0);
  779. case char(127):
  780. {
  781. push_undo();
  782. // delete
  783. MatrixXi new_BE(s.BE.rows(),s.BE.cols());
  784. int count = 0;
  785. for(int b=0;b<s.BE.rows();b++)
  786. {
  787. bool selected = false;
  788. for(int si=0;si<s.sel.size();si++)
  789. {
  790. if(s.BE(b,0) == s.sel(si) || s.BE(b,1) == s.sel(si))
  791. {
  792. selected = true;
  793. break;
  794. }
  795. }
  796. if(!selected)
  797. {
  798. new_BE.row(count) = s.BE.row(b);
  799. count++;
  800. }
  801. }
  802. new_BE.conservativeResize(count,new_BE.cols());
  803. const auto old_C = s.C;
  804. VectorXi I;
  805. remove_unreferenced(old_C,new_BE,s.C,s.BE,I);
  806. s.sel.resize(0,1);
  807. break;
  808. }
  809. case 'A':
  810. case 'a':
  811. {
  812. push_undo();
  813. s.sel = colon<int>(0,s.C.rows()-1);
  814. break;
  815. }
  816. case 'C':
  817. case 'c':
  818. {
  819. push_undo();
  820. // snap close vertices
  821. SparseMatrix<double> A;
  822. adjacency_matrix(s.BE,A);
  823. VectorXi J = colon<int>(0,s.C.rows()-1);
  824. // stupid O(n²) version
  825. for(int c = 0;c<s.C.rows();c++)
  826. {
  827. for(int d = c+1;d<s.C.rows();d++)
  828. {
  829. if(
  830. A.coeff(c,d) == 0 && // no edge
  831. (s.C.row(c)-s.C.row(d)).norm() < 0.02*bbd //close
  832. )
  833. {
  834. // c < d
  835. J(d) = c;
  836. }
  837. }
  838. }
  839. for(int e = 0;e<s.BE.rows();e++)
  840. {
  841. s.BE(e,0) = J(s.BE(e,0));
  842. s.BE(e,1) = J(s.BE(e,1));
  843. }
  844. const auto old_BE = s.BE;
  845. const auto old_C = s.C;
  846. VectorXi I;
  847. remove_unreferenced(old_C,old_BE,s.C,s.BE,I);
  848. for(int i = 0;i<s.sel.size();i++)
  849. {
  850. s.sel(i) = J(s.sel(i));
  851. }
  852. VectorXi _;
  853. igl::unique(s.sel,s.sel,_,_);
  854. break;
  855. }
  856. case 'D':
  857. case 'd':
  858. {
  859. push_undo();
  860. s.sel.resize(0,1);
  861. break;
  862. }
  863. case 'P':
  864. case 'p':
  865. {
  866. // add bone to parents (should really only be one)
  867. push_undo();
  868. vector<int> new_sel;
  869. const int old_nbe = s.BE.rows();
  870. for(int si=0;si<s.sel.size();si++)
  871. {
  872. for(int b=0;b<old_nbe;b++)
  873. {
  874. if(s.BE(b,1) == s.sel(si))
  875. {
  876. // one new node
  877. s.C.conservativeResize(s.C.rows()+1,3);
  878. const int nc = s.C.rows();
  879. s.C.row(nc-1) = 0.5*(s.C.row(s.BE(b,1)) + s.C.row(s.BE(b,0)));
  880. // one new bone
  881. s.BE.conservativeResize(s.BE.rows()+1,2);
  882. s.BE.row(s.BE.rows()-1) = RowVector2i(nc-1,s.BE(b,1));
  883. s.BE(b,1) = nc-1;
  884. // select last node
  885. new_sel.push_back(nc-1);
  886. }
  887. }
  888. }
  889. list_to_matrix(new_sel,s.sel);
  890. break;
  891. }
  892. case 'R':
  893. case 'r':
  894. {
  895. // re-root try at first selected
  896. if(s.sel.size() > 0)
  897. {
  898. push_undo();
  899. // only use first
  900. s.sel.conservativeResize(1,1);
  901. // Ideally this should only effect the connected component of s.sel(0)
  902. const auto & C = s.C;
  903. auto & BE = s.BE;
  904. vector<bool> seen(C.rows(),false);
  905. // adjacency list
  906. vector<vector< int> > A;
  907. adjacency_list(BE,A,false);
  908. int e = 0;
  909. queue<int> Q;
  910. Q.push(s.sel(0));
  911. seen[s.sel(0)] = true;
  912. while(!Q.empty())
  913. {
  914. const int c = Q.front();
  915. Q.pop();
  916. for(const auto & d : A[c])
  917. {
  918. if(!seen[d])
  919. {
  920. BE(e,0) = c;
  921. BE(e,1) = d;
  922. e++;
  923. Q.push(d);
  924. seen[d] = true;
  925. }
  926. }
  927. }
  928. // only keep tree
  929. BE.conservativeResize(e,BE.cols());
  930. }
  931. break;
  932. }
  933. case 'S':
  934. case 's':
  935. {
  936. save();
  937. break;
  938. }
  939. case 'U':
  940. case 'u':
  941. {
  942. push_scene();
  943. push_object();
  944. for(int c = 0;c<s.C.rows();c++)
  945. {
  946. Vector3d P = project((Vector3d)s.C.row(c));
  947. Vector3d obj;
  948. int nhits = unproject_in_mesh(P(0),P(1),ei,obj);
  949. if(nhits > 0)
  950. {
  951. s.C.row(c) = obj;
  952. }
  953. }
  954. pop_object();
  955. pop_scene();
  956. break;
  957. }
  958. case 'Y':
  959. case 'y':
  960. {
  961. symmetrize();
  962. break;
  963. }
  964. case 'z':
  965. case 'Z':
  966. is_rotating = false;
  967. is_dragging = false;
  968. if(command_down)
  969. {
  970. if(shift_down)
  971. {
  972. redo();
  973. }else
  974. {
  975. undo();
  976. }
  977. break;
  978. }else
  979. {
  980. push_undo();
  981. Quaterniond q;
  982. snap_to_canonical_view_quat(camera.m_rotation_conj,1.0,q);
  983. camera.orbit(q.conjugate());
  984. }
  985. break;
  986. default:
  987. if(!TwEventKeyboardGLUT(key,mouse_x,mouse_y))
  988. {
  989. cout<<"Unknown key command: "<<key<<" "<<int(key)<<endl;
  990. }
  991. }
  992. glutPostRedisplay();
  993. }
  994. int main(int argc, char * argv[])
  995. {
  996. using namespace std;
  997. using namespace Eigen;
  998. using namespace igl;
  999. string filename = "../shared/decimated-knight.obj";
  1000. string skel_filename = "";
  1001. output_filename = "";
  1002. switch(argc)
  1003. {
  1004. case 4:
  1005. output_filename = argv[3];
  1006. //fall through
  1007. case 3:
  1008. skel_filename = argv[2];
  1009. if(output_filename.size() == 0)
  1010. {
  1011. output_filename = skel_filename;
  1012. }
  1013. //fall through
  1014. case 2:
  1015. // Read and prepare mesh
  1016. filename = argv[1];
  1017. break;
  1018. default:
  1019. cerr<<"Usage:"<<endl<<" ./example input.obj [input/output.tgf]"<<endl;
  1020. cout<<endl<<"Opening default mesh..."<<endl;
  1021. }
  1022. // print key commands
  1023. cout<<"[Click] and [drag] Create bone (or select node) and reposition."<<endl;
  1024. cout<<"⇧ +[Click] and [drag] Select node (or create one) and _pull out_ new bone."<<endl;
  1025. cout<<"⌥ +[Click] and [drag] Rotate secene."<<endl;
  1026. cout<<"⌫ Delete selected node(s) and incident bones."<<endl;
  1027. cout<<"A,a Select all."<<endl;
  1028. cout<<"D,d Deselect all."<<endl;
  1029. cout<<"C,c Snap close nodes."<<endl;
  1030. cout<<"P,p Split \"parent\" bone(s) of selection by creating new node(s)."<<endl;
  1031. cout<<"R,r Breadth first search at selection to redirect skeleton into tree."<<endl;
  1032. cout<<"S,s Save current skeleton to output .tgf file."<<endl;
  1033. cout<<"U,u Project then unproject inside mesh (as if dragging each by ε)."<<endl;
  1034. cout<<"Y,Y Symmetrize selection over plane through object centroid and right vector."<<endl;
  1035. cout<<"Z,z Snap to canonical view."<<endl;
  1036. cout<<"⌘ Z Undo."<<endl;
  1037. cout<<"⇧ ⌘ Z Redo."<<endl;
  1038. cout<<"^C,ESC Exit (without saving)."<<endl;
  1039. string dir,_1,_2,name;
  1040. read_triangle_mesh(filename,V,F,dir,_1,_2,name);
  1041. if(output_filename.size() == 0)
  1042. {
  1043. output_filename = dir+"/"+name+".tgf";
  1044. }
  1045. if(file_exists(output_filename.c_str()))
  1046. {
  1047. cout<<YELLOWGIN("Output set to overwrite "<<output_filename)<<endl;
  1048. }else
  1049. {
  1050. cout<<BLUEGIN("Output set to "<<output_filename)<<endl;
  1051. }
  1052. if(skel_filename.length() > 0)
  1053. {
  1054. readTGF(skel_filename,s.C,s.BE);
  1055. }
  1056. init_relative();
  1057. ei.init(V.cast<float>(),F.cast<int>());
  1058. // Init glut
  1059. glutInit(&argc,argv);
  1060. if( !TwInit(TW_OPENGL, NULL) )
  1061. {
  1062. // A fatal error occured
  1063. fprintf(stderr, "AntTweakBar initialization failed: %s\n", TwGetLastError());
  1064. return 1;
  1065. }
  1066. // Create a tweak bar
  1067. rebar.TwNewBar("TweakBar");
  1068. rebar.TwAddVarRW("camera_rotation", TW_TYPE_QUAT4D,
  1069. camera.m_rotation_conj.coeffs().data(), "open readonly=true");
  1070. TwType RotationTypeTW = ReTwDefineEnumFromString("RotationType",
  1071. "igl_trackball,two-a...-fixed-up");
  1072. rebar.TwAddVarCB( "rotation_type", RotationTypeTW,
  1073. set_rotation_type,get_rotation_type,NULL,"keyIncr=] keyDecr=[");
  1074. rebar.TwAddVarRW("skeleton_on_top", TW_TYPE_BOOLCPP,&skeleton_on_top,"key=O");
  1075. rebar.TwAddVarRW("wireframe", TW_TYPE_BOOLCPP,&wireframe,"key=l");
  1076. TwType SkelStyleTypeTW = ReTwDefineEnumFromString("SkelStyleType",
  1077. "3d,vector-graphics");
  1078. rebar.TwAddVarRW("style",SkelStyleTypeTW,&skel_style,"");
  1079. rebar.TwAddVarRW("alpha",TW_TYPE_DOUBLE,&alpha,
  1080. "keyIncr=} keyDecr={ min=0 max=1 step=0.1");
  1081. rebar.load(REBAR_NAME);
  1082. // Init antweakbar
  1083. glutInitDisplayString( "rgba depth double samples>=8 ");
  1084. glutInitWindowSize(glutGet(GLUT_SCREEN_WIDTH)/2.0,glutGet(GLUT_SCREEN_HEIGHT)/2.0);
  1085. glutCreateWindow("skeleton-builder");
  1086. glutDisplayFunc(display);
  1087. glutReshapeFunc(reshape);
  1088. glutKeyboardFunc(key);
  1089. glutMouseFunc(mouse);
  1090. glutMotionFunc(mouse_drag);
  1091. glutPassiveMotionFunc((GLUTmousemotionfun)TwEventMouseMotionGLUT);
  1092. glutMainLoop();
  1093. return 0;
  1094. }