example.cpp 29 KB

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