example.cpp 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162
  1. #include <igl/draw_skeleton_vector_graphics.h>
  2. #include <igl/two_axis_valuator_fixed_up.h>
  3. #include <igl/read_triangle_mesh.h>
  4. #include <igl/readTGF.h>
  5. #include <igl/writeOBJ.h>
  6. #include <igl/writeOFF.h>
  7. #include <igl/report_gl_error.h>
  8. #include <igl/draw_mesh.h>
  9. #include <igl/draw_floor.h>
  10. #include <igl/pathinfo.h>
  11. #include <igl/list_to_matrix.h>
  12. #include <igl/quat_to_mat.h>
  13. #include <igl/per_face_normals.h>
  14. #include <igl/material_colors.h>
  15. #include <igl/trackball.h>
  16. #include <igl/snap_to_canonical_view_quat.h>
  17. #include <igl/snap_to_fixed_up.h>
  18. #include <igl/REDRUM.h>
  19. #include <igl/Camera.h>
  20. #include <igl/ReAntTweakBar.h>
  21. #include <igl/get_seconds.h>
  22. #include <igl/forward_kinematics.h>
  23. #include <igl/boundary_conditions.h>
  24. #include <igl/normalize_row_sums.h>
  25. #include <igl/lbs_matrix.h>
  26. #include <igl/sort_triangles.h>
  27. #include <igl/slice.h>
  28. #include <igl/project.h>
  29. #include <igl/unproject.h>
  30. #include <igl/embree/EmbreeIntersector.h>
  31. #include <igl/embree/unproject_in_mesh.h>
  32. #include <igl/matlab_format.h>
  33. #include <igl/remove_unreferenced.h>
  34. #include <igl/adjacency_list.h>
  35. #include <igl/adjacency_matrix.h>
  36. #include <igl/right_axis.h>
  37. #include <igl/colon.h>
  38. #include <igl/unique.h>
  39. #include <igl/REDRUM.h>
  40. #include <igl/writeTGF.h>
  41. #include <igl/file_exists.h>
  42. #include <igl/centroid.h>
  43. #include <igl/draw_skeleton_3d.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,bbd*0.5);
  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. cout<<"bbd: "<<bbd<<endl;
  661. camera.push_away(2);
  662. }
  663. void undo()
  664. {
  665. using namespace std;
  666. if(!undo_stack.empty())
  667. {
  668. redo_stack.push(s);
  669. s = undo_stack.top();
  670. undo_stack.pop();
  671. }
  672. }
  673. void redo()
  674. {
  675. using namespace std;
  676. if(!redo_stack.empty())
  677. {
  678. undo_stack.push(s);
  679. s = redo_stack.top();
  680. redo_stack.pop();
  681. }
  682. }
  683. void symmetrize()
  684. {
  685. using namespace std;
  686. using namespace igl;
  687. using namespace Eigen;
  688. if(s.sel.size() == 0)
  689. {
  690. cout<<YELLOWGIN("Make a selection first.")<<endl;
  691. return;
  692. }
  693. push_undo();
  694. push_scene();
  695. push_object();
  696. Vector3d right;
  697. right_axis(right.data(),right.data()+1,right.data()+2);
  698. right.normalize();
  699. MatrixXd RC(s.C.rows(),s.C.cols());
  700. MatrixXd old_C = s.C;
  701. for(int c = 0;c<s.C.rows();c++)
  702. {
  703. const Vector3d Cc = s.C.row(c);
  704. const auto A = Cc-Vcen;
  705. const auto A1 = A.dot(right) * right;
  706. const auto A2 = A-A1;
  707. RC.row(c) = Vcen + A2 - A1;
  708. }
  709. vector<bool> mask = selection_mask(s.sel,s.C.rows());
  710. // stupid O(n²) matching
  711. for(int c = 0;c<s.C.rows();c++)
  712. {
  713. // not selected
  714. if(!mask[c])
  715. {
  716. continue;
  717. }
  718. const Vector3d Cc = s.C.row(c);
  719. int min_r = -1;
  720. double min_dist = 1e25;
  721. double max_dist = 0.1*bbd;
  722. for(int r= 0;r<RC.rows();r++)
  723. {
  724. const Vector3d RCr = RC.row(r);
  725. const double dist = (Cc-RCr).norm();
  726. if(
  727. dist<min_dist && // closest
  728. dist<max_dist && // not too far away
  729. (c==r || (Cc-Vcen).dot(right)*(RCr-Vcen).dot(right) > 0) // on same side
  730. )
  731. {
  732. min_dist = dist;
  733. min_r = r;
  734. }
  735. }
  736. if(min_r>=0)
  737. {
  738. if(mask[min_r])
  739. {
  740. s.C.row(c) = 0.5*(Cc.transpose()+RC.row(min_r));
  741. }else
  742. {
  743. s.C.row(c) = RC.row(min_r);
  744. }
  745. }
  746. }
  747. pop_object();
  748. pop_scene();
  749. }
  750. bool save()
  751. {
  752. using namespace std;
  753. using namespace igl;
  754. if(writeTGF(output_filename,s.C,s.BE))
  755. {
  756. cout<<GREENGIN("Current skeleton written to "+output_filename+".")<<endl;
  757. return true;
  758. }else
  759. {
  760. cout<<REDRUM("Writing to "+output_filename+" failed.")<<endl;
  761. return false;
  762. }
  763. }
  764. void key(unsigned char key, int mouse_x, int mouse_y)
  765. {
  766. using namespace std;
  767. using namespace igl;
  768. using namespace Eigen;
  769. int mod = glutGetModifiers();
  770. const bool command_down = GLUT_ACTIVE_COMMAND & mod;
  771. const bool shift_down = GLUT_ACTIVE_SHIFT & mod;
  772. switch(key)
  773. {
  774. // ESC
  775. case char(27):
  776. rebar.save(REBAR_NAME);
  777. // ^C
  778. case char(3):
  779. exit(0);
  780. case char(127):
  781. {
  782. push_undo();
  783. // delete
  784. MatrixXi new_BE(s.BE.rows(),s.BE.cols());
  785. int count = 0;
  786. for(int b=0;b<s.BE.rows();b++)
  787. {
  788. bool selected = false;
  789. for(int si=0;si<s.sel.size();si++)
  790. {
  791. if(s.BE(b,0) == s.sel(si) || s.BE(b,1) == s.sel(si))
  792. {
  793. selected = true;
  794. break;
  795. }
  796. }
  797. if(!selected)
  798. {
  799. new_BE.row(count) = s.BE.row(b);
  800. count++;
  801. }
  802. }
  803. new_BE.conservativeResize(count,new_BE.cols());
  804. const auto old_C = s.C;
  805. VectorXi I;
  806. remove_unreferenced(old_C,new_BE,s.C,s.BE,I);
  807. s.sel.resize(0,1);
  808. break;
  809. }
  810. case 'A':
  811. case 'a':
  812. {
  813. push_undo();
  814. s.sel = colon<int>(0,s.C.rows()-1);
  815. break;
  816. }
  817. case 'C':
  818. case 'c':
  819. {
  820. push_undo();
  821. // snap close vertices
  822. SparseMatrix<double> A;
  823. adjacency_matrix(s.BE,A);
  824. VectorXi J = colon<int>(0,s.C.rows()-1);
  825. // stupid O(n²) version
  826. for(int c = 0;c<s.C.rows();c++)
  827. {
  828. for(int d = c+1;d<s.C.rows();d++)
  829. {
  830. if(
  831. A.coeff(c,d) == 0 && // no edge
  832. (s.C.row(c)-s.C.row(d)).norm() < 0.02*bbd //close
  833. )
  834. {
  835. // c < d
  836. J(d) = c;
  837. }
  838. }
  839. }
  840. for(int e = 0;e<s.BE.rows();e++)
  841. {
  842. s.BE(e,0) = J(s.BE(e,0));
  843. s.BE(e,1) = J(s.BE(e,1));
  844. }
  845. const auto old_BE = s.BE;
  846. const auto old_C = s.C;
  847. VectorXi I;
  848. remove_unreferenced(old_C,old_BE,s.C,s.BE,I);
  849. for(int i = 0;i<s.sel.size();i++)
  850. {
  851. s.sel(i) = J(s.sel(i));
  852. }
  853. VectorXi _;
  854. igl::unique(s.sel,s.sel,_,_);
  855. break;
  856. }
  857. case 'D':
  858. case 'd':
  859. {
  860. push_undo();
  861. s.sel.resize(0,1);
  862. break;
  863. }
  864. case 'P':
  865. case 'p':
  866. {
  867. // add bone to parents (should really only be one)
  868. push_undo();
  869. vector<int> new_sel;
  870. const int old_nbe = s.BE.rows();
  871. for(int si=0;si<s.sel.size();si++)
  872. {
  873. for(int b=0;b<old_nbe;b++)
  874. {
  875. if(s.BE(b,1) == s.sel(si))
  876. {
  877. // one new node
  878. s.C.conservativeResize(s.C.rows()+1,3);
  879. const int nc = s.C.rows();
  880. s.C.row(nc-1) = 0.5*(s.C.row(s.BE(b,1)) + s.C.row(s.BE(b,0)));
  881. // one new bone
  882. s.BE.conservativeResize(s.BE.rows()+1,2);
  883. s.BE.row(s.BE.rows()-1) = RowVector2i(nc-1,s.BE(b,1));
  884. s.BE(b,1) = nc-1;
  885. // select last node
  886. new_sel.push_back(nc-1);
  887. }
  888. }
  889. }
  890. list_to_matrix(new_sel,s.sel);
  891. break;
  892. }
  893. case 'R':
  894. case 'r':
  895. {
  896. // re-root try at first selected
  897. if(s.sel.size() > 0)
  898. {
  899. push_undo();
  900. // only use first
  901. s.sel.conservativeResize(1,1);
  902. // Ideally this should only effect the connected component of s.sel(0)
  903. const auto & C = s.C;
  904. auto & BE = s.BE;
  905. vector<bool> seen(C.rows(),false);
  906. // adjacency list
  907. vector<vector< int> > A;
  908. adjacency_list(BE,A,false);
  909. int e = 0;
  910. queue<int> Q;
  911. Q.push(s.sel(0));
  912. seen[s.sel(0)] = true;
  913. while(!Q.empty())
  914. {
  915. const int c = Q.front();
  916. Q.pop();
  917. for(const auto & d : A[c])
  918. {
  919. if(!seen[d])
  920. {
  921. BE(e,0) = c;
  922. BE(e,1) = d;
  923. e++;
  924. Q.push(d);
  925. seen[d] = true;
  926. }
  927. }
  928. }
  929. // only keep tree
  930. BE.conservativeResize(e,BE.cols());
  931. }
  932. break;
  933. }
  934. case 'S':
  935. case 's':
  936. {
  937. save();
  938. break;
  939. }
  940. case 'U':
  941. case 'u':
  942. {
  943. push_scene();
  944. push_object();
  945. for(int c = 0;c<s.C.rows();c++)
  946. {
  947. Vector3d P = project((Vector3d)s.C.row(c));
  948. Vector3d obj;
  949. int nhits = unproject_in_mesh(P(0),P(1),ei,obj);
  950. if(nhits > 0)
  951. {
  952. s.C.row(c) = obj;
  953. }
  954. }
  955. pop_object();
  956. pop_scene();
  957. break;
  958. }
  959. case 'Y':
  960. case 'y':
  961. {
  962. symmetrize();
  963. break;
  964. }
  965. case 'z':
  966. case 'Z':
  967. is_rotating = false;
  968. is_dragging = false;
  969. if(command_down)
  970. {
  971. if(shift_down)
  972. {
  973. redo();
  974. }else
  975. {
  976. undo();
  977. }
  978. break;
  979. }else
  980. {
  981. push_undo();
  982. Quaterniond q;
  983. snap_to_canonical_view_quat(camera.m_rotation_conj,1.0,q);
  984. camera.orbit(q.conjugate());
  985. }
  986. break;
  987. default:
  988. if(!TwEventKeyboardGLUT(key,mouse_x,mouse_y))
  989. {
  990. cout<<"Unknown key command: "<<key<<" "<<int(key)<<endl;
  991. }
  992. }
  993. glutPostRedisplay();
  994. }
  995. int main(int argc, char * argv[])
  996. {
  997. using namespace std;
  998. using namespace Eigen;
  999. using namespace igl;
  1000. string filename = "../shared/decimated-knight.obj";
  1001. string skel_filename = "";
  1002. output_filename = "";
  1003. switch(argc)
  1004. {
  1005. case 4:
  1006. output_filename = argv[3];
  1007. //fall through
  1008. case 3:
  1009. skel_filename = argv[2];
  1010. if(output_filename.size() == 0)
  1011. {
  1012. output_filename = skel_filename;
  1013. }
  1014. //fall through
  1015. case 2:
  1016. // Read and prepare mesh
  1017. filename = argv[1];
  1018. break;
  1019. default:
  1020. cerr<<"Usage:"<<endl<<" ./example input.obj [input/output.tgf]"<<endl;
  1021. cout<<endl<<"Opening default mesh..."<<endl;
  1022. }
  1023. // print key commands
  1024. cout<<"[Click] and [drag] Create bone (or select node) and reposition."<<endl;
  1025. cout<<"⇧ +[Click] and [drag] Select node (or create one) and _pull out_ new bone."<<endl;
  1026. cout<<"⌥ +[Click] and [drag] Rotate secene."<<endl;
  1027. cout<<"⌫ Delete selected node(s) and incident bones."<<endl;
  1028. cout<<"A,a Select all."<<endl;
  1029. cout<<"D,d Deselect all."<<endl;
  1030. cout<<"C,c Snap close nodes."<<endl;
  1031. cout<<"P,p Split \"parent\" bone(s) of selection by creating new node(s)."<<endl;
  1032. cout<<"R,r Breadth first search at selection to redirect skeleton into tree."<<endl;
  1033. cout<<"S,s Save current skeleton to output .tgf file."<<endl;
  1034. cout<<"U,u Project then unproject inside mesh (as if dragging each by ε)."<<endl;
  1035. cout<<"Y,Y Symmetrize selection over plane through object centroid and right vector."<<endl;
  1036. cout<<"Z,z Snap to canonical view."<<endl;
  1037. cout<<"⌘ Z Undo."<<endl;
  1038. cout<<"⇧ ⌘ Z Redo."<<endl;
  1039. cout<<"^C,ESC Exit (without saving)."<<endl;
  1040. string dir,_1,_2,name;
  1041. read_triangle_mesh(filename,V,F,dir,_1,_2,name);
  1042. if(output_filename.size() == 0)
  1043. {
  1044. output_filename = dir+"/"+name+".tgf";
  1045. }
  1046. if(file_exists(output_filename.c_str()))
  1047. {
  1048. cout<<YELLOWGIN("Output set to overwrite "<<output_filename)<<endl;
  1049. }else
  1050. {
  1051. cout<<BLUEGIN("Output set to "<<output_filename)<<endl;
  1052. }
  1053. if(skel_filename.length() > 0)
  1054. {
  1055. readTGF(skel_filename,s.C,s.BE);
  1056. }
  1057. init_relative();
  1058. ei.init(V.cast<float>(),F.cast<int>());
  1059. // Init glut
  1060. glutInit(&argc,argv);
  1061. if( !TwInit(TW_OPENGL, NULL) )
  1062. {
  1063. // A fatal error occured
  1064. fprintf(stderr, "AntTweakBar initialization failed: %s\n", TwGetLastError());
  1065. return 1;
  1066. }
  1067. // Create a tweak bar
  1068. rebar.TwNewBar("TweakBar");
  1069. rebar.TwAddVarRW("camera_rotation", TW_TYPE_QUAT4D,
  1070. camera.m_rotation_conj.coeffs().data(), "open readonly=true");
  1071. TwType RotationTypeTW = ReTwDefineEnumFromString("RotationType",
  1072. "igl_trackball,two-a...-fixed-up");
  1073. rebar.TwAddVarCB( "rotation_type", RotationTypeTW,
  1074. set_rotation_type,get_rotation_type,NULL,"keyIncr=] keyDecr=[");
  1075. rebar.TwAddVarRW("skeleton_on_top", TW_TYPE_BOOLCPP,&skeleton_on_top,"key=O");
  1076. rebar.TwAddVarRW("wireframe", TW_TYPE_BOOLCPP,&wireframe,"key=l");
  1077. TwType SkelStyleTypeTW = ReTwDefineEnumFromString("SkelStyleType",
  1078. "3d,vector-graphics");
  1079. rebar.TwAddVarRW("style",SkelStyleTypeTW,&skel_style,"");
  1080. rebar.TwAddVarRW("alpha",TW_TYPE_DOUBLE,&alpha,
  1081. "keyIncr=} keyDecr={ min=0 max=1 step=0.1");
  1082. rebar.load(REBAR_NAME);
  1083. // Init antweakbar
  1084. glutInitDisplayString( "rgba depth double samples>=8 ");
  1085. glutInitWindowSize(glutGet(GLUT_SCREEN_WIDTH)/2.0,glutGet(GLUT_SCREEN_HEIGHT)/2.0);
  1086. glutCreateWindow("skeleton-builder");
  1087. glutDisplayFunc(display);
  1088. glutReshapeFunc(reshape);
  1089. glutKeyboardFunc(key);
  1090. glutMouseFunc(mouse);
  1091. glutMotionFunc(mouse_drag);
  1092. glutPassiveMotionFunc((GLUTmousemotionfun)TwEventMouseMotionGLUT);
  1093. glutMainLoop();
  1094. return 0;
  1095. }