example.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. // Small GLUT application to test different scene rotation paradigms
  2. //
  3. #include <igl/readOBJ.h>
  4. #include <igl/writeOBJ.h>
  5. #include <igl/writeOFF.h>
  6. #include <igl/readWRL.h>
  7. #include <igl/report_gl_error.h>
  8. #include <igl/triangulate.h>
  9. #include <igl/readOFF.h>
  10. #include <igl/readMESH.h>
  11. #include <igl/draw_mesh.h>
  12. #include <igl/draw_floor.h>
  13. #include <igl/pathinfo.h>
  14. #include <igl/list_to_matrix.h>
  15. #include <igl/quat_to_mat.h>
  16. #include <igl/per_face_normals.h>
  17. #include <igl/material_colors.h>
  18. #include <igl/trackball.h>
  19. #include <igl/snap_to_canonical_view_quat.h>
  20. #include <igl/REDRUM.h>
  21. #include <igl/Camera.h>
  22. #include <igl/ReAntTweakBar.h>
  23. #include <igl/get_seconds.h>
  24. #include <igl/jet.h>
  25. #include <igl/randperm.h>
  26. #include <igl/normalize_row_lengths.h>
  27. #include <igl/boost/manifold_patches.h>
  28. #include <igl/boost/components.h>
  29. #include <igl/boost/bfs_orient.h>
  30. #include <igl/orient_outward.h>
  31. #include <Eigen/Core>
  32. #include <Eigen/Geometry>
  33. #include <GLUT/glut.h>
  34. #include <string>
  35. #include <vector>
  36. #include <stack>
  37. #include <iostream>
  38. Eigen::MatrixXd V,C;
  39. Eigen::VectorXd Vmid,Vmin,Vmax;
  40. double bbd = 1.0;
  41. Eigen::MatrixXi F;
  42. struct State
  43. {
  44. igl::Camera camera;
  45. Eigen::MatrixXd N;
  46. } s;
  47. // See README for descriptions
  48. enum RotationType
  49. {
  50. ROTATION_TYPE_IGL_TRACKBALL = 0,
  51. ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP = 1,
  52. NUM_ROTATION_TYPES = 2,
  53. } rotation_type;
  54. std::stack<State> undo_stack;
  55. std::stack<State> redo_stack;
  56. bool is_rotating = false;
  57. int down_x,down_y;
  58. igl::Camera down_camera;
  59. bool is_animating = false;
  60. double animation_start_time = 0;
  61. double ANIMATION_DURATION = 0.5;
  62. Eigen::Quaterniond animation_from_quat;
  63. Eigen::Quaterniond animation_to_quat;
  64. int width,height;
  65. Eigen::Vector4f light_pos(-0.1,-0.1,0.9,0);
  66. #define REBAR_NAME "temp.rbr"
  67. igl::ReTwBar rebar;
  68. void push_undo()
  69. {
  70. undo_stack.push(s);
  71. // Clear
  72. redo_stack = std::stack<State>();
  73. }
  74. void TW_CALL set_camera_rotation(const void * value, void *clientData)
  75. {
  76. using namespace std;
  77. // case current value to double
  78. const double * quat = (const double *)(value);
  79. std::copy(quat,quat+4,s.camera.rotation);
  80. }
  81. void TW_CALL set_rotation_type(const void * value, void * clientData)
  82. {
  83. using namespace Eigen;
  84. using namespace std;
  85. using namespace igl;
  86. const RotationType old_rotation_type = rotation_type;
  87. rotation_type = *(const RotationType *)(value);
  88. if(rotation_type == ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP &&
  89. old_rotation_type != ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP)
  90. {
  91. push_undo();
  92. copy(s.camera.rotation,s.camera.rotation+4,animation_from_quat.coeffs().data());
  93. const Vector3d up = animation_from_quat.matrix() * Vector3d(0,1,0);
  94. Vector3d proj_up(0,up(1),up(2));
  95. if(proj_up.norm() == 0)
  96. {
  97. proj_up = Vector3d(0,1,0);
  98. }
  99. proj_up.normalize();
  100. Quaterniond dq;
  101. dq = Quaterniond::FromTwoVectors(up,proj_up);
  102. animation_to_quat = dq * animation_from_quat;
  103. // start animation
  104. animation_start_time = get_seconds();
  105. is_animating = true;
  106. }
  107. }
  108. void TW_CALL get_rotation_type(void * value, void *clientData)
  109. {
  110. RotationType * rt = (RotationType *)(value);
  111. *rt = rotation_type;
  112. }
  113. void TW_CALL get_camera_rotation(void * value, void *clientData)
  114. {
  115. using namespace std;
  116. // case current value to double
  117. double * quat = (double *)(value);
  118. std::copy(s.camera.rotation,s.camera.rotation+4,quat);
  119. }
  120. void reshape(int width, int height)
  121. {
  122. ::width = width;
  123. ::height = height;
  124. glViewport(0,0,width,height);
  125. // Send the new window size to AntTweakBar
  126. TwWindowSize(width, height);
  127. }
  128. void push_scene()
  129. {
  130. using namespace igl;
  131. using namespace std;
  132. const double angle = s.camera.angle;
  133. glMatrixMode(GL_PROJECTION);
  134. glPushMatrix();
  135. glLoadIdentity();
  136. double zNear = 1e-2;
  137. double zFar = 100;
  138. double aspect = ((double)width)/((double)height);
  139. // Amount of scaling needed to "fix" perspective z-shift
  140. double z_fix = 1.0;
  141. // 5 is far enough to see unit "things" well
  142. const double camera_z = 2;
  143. // Test if should be using true orthographic projection
  144. if(angle == 0)
  145. {
  146. glOrtho(
  147. -0.5*camera_z*aspect,
  148. 0.5*camera_z*aspect,
  149. -0.5*camera_z,
  150. 0.5*camera_z,
  151. zNear,
  152. zFar);
  153. }else
  154. {
  155. // Make sure aspect is sane
  156. aspect = aspect < 0.01 ? 0.01 : aspect;
  157. gluPerspective(angle,aspect,zNear,zFar);
  158. z_fix = 2.*tan(angle/2./360.*2.*M_PI);
  159. }
  160. glMatrixMode(GL_MODELVIEW);
  161. glPushMatrix();
  162. glLoadIdentity();
  163. gluLookAt(0,0,camera_z,0,0,0,0,1,0);
  164. // Adjust scale to correct perspective
  165. glScaled(z_fix,z_fix,z_fix);
  166. // scale, pan
  167. glScaled( s.camera.zoom, s.camera.zoom, s.camera.zoom);
  168. double mat[4*4];
  169. quat_to_mat(s.camera.rotation,mat);
  170. glMultMatrixd(mat);
  171. }
  172. void push_object()
  173. {
  174. using namespace igl;
  175. glPushMatrix();
  176. glScaled(2./bbd,2./bbd,2./bbd);
  177. glTranslated(-Vmid(0),-Vmid(1),-Vmid(2));
  178. }
  179. void pop_object()
  180. {
  181. glPopMatrix();
  182. }
  183. void pop_scene()
  184. {
  185. glMatrixMode(GL_PROJECTION);
  186. glPopMatrix();
  187. glMatrixMode(GL_MODELVIEW);
  188. glPopMatrix();
  189. }
  190. // Set up double-sided lights
  191. void lights()
  192. {
  193. using namespace std;
  194. using namespace Eigen;
  195. glEnable(GL_LIGHTING);
  196. //glLightModelf(GL_LIGHT_MODEL_TWO_SIDE,GL_TRUE);
  197. glEnable(GL_LIGHT0);
  198. float WHITE[4] = {1,1,1,1.};
  199. float GREY[4] = {0.4,0.4,0.4,1.};
  200. float BLACK[4] = {0.,0.,0.,1.};
  201. float NEAR_BLACK[4] = {0.1,0.1,0.1,1.};
  202. Vector4f pos = light_pos;
  203. glLightfv(GL_LIGHT0,GL_AMBIENT,BLACK);
  204. glLightfv(GL_LIGHT0,GL_DIFFUSE,WHITE);
  205. glLightfv(GL_LIGHT0,GL_SPECULAR,BLACK);
  206. glLightfv(GL_LIGHT0,GL_POSITION,pos.data());
  207. //glEnable(GL_LIGHT1);
  208. //pos(0) *= -1;
  209. //pos(1) *= -1;
  210. //pos(2) *= -1;
  211. //glLightfv(GL_LIGHT1,GL_AMBIENT,BLACK);
  212. //glLightfv(GL_LIGHT1,GL_DIFFUSE,NEAR_BLACK);
  213. //glLightfv(GL_LIGHT1,GL_SPECULAR,BLACK);
  214. //glLightfv(GL_LIGHT1,GL_POSITION,pos.data());
  215. }
  216. void display()
  217. {
  218. using namespace igl;
  219. using namespace std;
  220. using namespace Eigen;
  221. glClearColor(1,1,1,0);
  222. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  223. if(is_animating)
  224. {
  225. double t = (get_seconds() - animation_start_time)/ANIMATION_DURATION;
  226. if(t > 1)
  227. {
  228. t = 1;
  229. is_animating = false;
  230. }
  231. Quaterniond q;
  232. q.coeffs() =
  233. animation_to_quat.coeffs()*t + animation_from_quat.coeffs()*(1.-t);
  234. q.normalize();
  235. copy(q.coeffs().data(),q.coeffs().data()+4,s.camera.rotation);
  236. }
  237. glEnable(GL_DEPTH_TEST);
  238. glEnable(GL_NORMALIZE);
  239. lights();
  240. push_scene();
  241. push_object();
  242. // Set material properties
  243. glEnable(GL_COLOR_MATERIAL);
  244. glColorMaterial(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE);
  245. draw_mesh(V,F,s.N,C);
  246. pop_object();
  247. // Draw a nice floor
  248. glPushMatrix();
  249. const double floor_offset =
  250. -2./bbd*(V.col(1).maxCoeff()-Vmid(1));
  251. glTranslated(0,floor_offset,0);
  252. const float GREY[4] = {0.5,0.5,0.6,1.0};
  253. const float DARK_GREY[4] = {0.2,0.2,0.3,1.0};
  254. draw_floor(GREY,DARK_GREY);
  255. glPopMatrix();
  256. pop_scene();
  257. report_gl_error();
  258. TwDraw();
  259. glutSwapBuffers();
  260. glutPostRedisplay();
  261. }
  262. void mouse_wheel(int wheel, int direction, int mouse_x, int mouse_y)
  263. {
  264. using namespace std;
  265. push_undo();
  266. if(wheel == 0)
  267. {
  268. static double mouse_scroll_y = 0;
  269. const double delta_y = 0.125*direction;
  270. mouse_scroll_y += delta_y;
  271. // absolute scale difference when changing zooms (+1)
  272. const double z_diff = 0.01;
  273. GLint viewport[4];
  274. glGetIntegerv(GL_VIEWPORT,viewport);
  275. if(TwMouseMotion(mouse_x, viewport[3] - mouse_y))
  276. {
  277. TwMouseWheel(mouse_scroll_y);
  278. }else
  279. {
  280. s.camera.zoom *= (1.0+double(direction)*z_diff);
  281. const double min_zoom = 0.01;
  282. const double max_zoom = 10.0;
  283. s.camera.zoom = min(max_zoom,max(min_zoom,s.camera.zoom));
  284. }
  285. }else
  286. {
  287. if(!is_rotating)
  288. {
  289. // Change viewing angle (reshape will take care of adjust zoom)
  290. const double a_diff = 1.0;
  291. s.camera.angle += double(direction)*a_diff;
  292. const double min_angle = 15.0;
  293. s.camera.angle =
  294. min(90.0,max(min_angle,s.camera.angle));
  295. }
  296. }
  297. }
  298. void mouse(int glutButton, int glutState, int mouse_x, int mouse_y)
  299. {
  300. using namespace std;
  301. using namespace Eigen;
  302. using namespace igl;
  303. bool tw_using = TwEventMouseButtonGLUT(glutButton,glutState,mouse_x,mouse_y);
  304. switch(glutButton)
  305. {
  306. case GLUT_RIGHT_BUTTON:
  307. case GLUT_LEFT_BUTTON:
  308. {
  309. switch(glutState)
  310. {
  311. case 1:
  312. // up
  313. glutSetCursor(GLUT_CURSOR_INHERIT);
  314. is_rotating = false;
  315. break;
  316. case 0:
  317. if(!tw_using)
  318. {
  319. push_undo();
  320. glutSetCursor(GLUT_CURSOR_CYCLE);
  321. // collect information for trackball
  322. is_rotating = true;
  323. down_camera = s.camera;
  324. down_x = mouse_x;
  325. down_y = mouse_y;
  326. }
  327. break;
  328. }
  329. break;
  330. // Scroll down
  331. case GLUT_WHEEL_DOWN:
  332. {
  333. mouse_wheel(0,-1,mouse_x,mouse_y);
  334. break;
  335. }
  336. // Scroll up
  337. case GLUT_WHEEL_UP:
  338. {
  339. mouse_wheel(0,1,mouse_x,mouse_y);
  340. break;
  341. }
  342. // Scroll left
  343. case GLUT_WHEEL_LEFT:
  344. {
  345. mouse_wheel(1,-1,mouse_x,mouse_y);
  346. break;
  347. }
  348. // Scroll right
  349. case GLUT_WHEEL_RIGHT:
  350. {
  351. mouse_wheel(1,1,mouse_x,mouse_y);
  352. break;
  353. }
  354. }
  355. }
  356. }
  357. void mouse_drag(int mouse_x, int mouse_y)
  358. {
  359. using namespace igl;
  360. using namespace std;
  361. using namespace Eigen;
  362. if(is_rotating)
  363. {
  364. glutSetCursor(GLUT_CURSOR_CYCLE);
  365. switch(rotation_type)
  366. {
  367. case ROTATION_TYPE_IGL_TRACKBALL:
  368. {
  369. // Rotate according to trackball
  370. igl::trackball<double>(
  371. width,
  372. height,
  373. 2.0,
  374. down_camera.rotation,
  375. down_x,
  376. down_y,
  377. mouse_x,
  378. mouse_y,
  379. s.camera.rotation);
  380. break;
  381. }
  382. case ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP:
  383. {
  384. Quaterniond down_q;
  385. copy(down_camera.rotation,down_camera.rotation+4,down_q.coeffs().data());
  386. Vector3d axis(0,1,0);
  387. const double speed = 2.0;
  388. Quaterniond q;
  389. q = down_q *
  390. Quaterniond(
  391. AngleAxisd(
  392. M_PI*((double)(mouse_x-down_x))/(double)width*speed/2.0,
  393. axis.normalized()));
  394. q.normalize();
  395. {
  396. Vector3d axis(1,0,0);
  397. const double speed = 2.0;
  398. if(axis.norm() != 0)
  399. {
  400. q =
  401. Quaterniond(
  402. AngleAxisd(
  403. M_PI*(mouse_y-down_y)/(double)width*speed/2.0,
  404. axis.normalized())) * q;
  405. q.normalize();
  406. }
  407. }
  408. copy(q.coeffs().data(),q.coeffs().data()+4,s.camera.rotation);
  409. break;
  410. }
  411. default:
  412. break;
  413. }
  414. }
  415. }
  416. void init_relative()
  417. {
  418. using namespace Eigen;
  419. using namespace igl;
  420. per_face_normals(V,F,s.N);
  421. normalize_row_lengths(s.N,s.N);
  422. Vmax = V.colwise().maxCoeff();
  423. Vmin = V.colwise().minCoeff();
  424. Vmid = 0.5*(Vmax + Vmin);
  425. bbd = (Vmax-Vmin).norm();
  426. }
  427. void init_patches()
  428. {
  429. using namespace Eigen;
  430. using namespace igl;
  431. using namespace std;
  432. VectorXi CC;
  433. SparseMatrix<int> A;
  434. components(F,CC);
  435. cout<<"There are "<<CC.maxCoeff()+1<<" connected components."<<endl;
  436. //manifold_patches(F,CC,A);
  437. bfs_orient(F,F,CC);
  438. VectorXi I;
  439. orient_outward(V,F,CC,F,I);
  440. C.resize(CC.rows(),3);
  441. double num_cc = (double)CC.maxCoeff()+1.0;
  442. cout<<"There are "<<num_cc<<" 'manifold/orientable' patches."<<endl;
  443. randperm(num_cc,I);
  444. for(int f = 0;f<CC.rows();f++)
  445. {
  446. jet(
  447. (double)I(CC(f))/num_cc,
  448. C(f,0),
  449. C(f,1),
  450. C(f,2));
  451. }
  452. }
  453. void undo()
  454. {
  455. using namespace std;
  456. if(!undo_stack.empty())
  457. {
  458. redo_stack.push(s);
  459. s = undo_stack.top();
  460. undo_stack.pop();
  461. }
  462. }
  463. void redo()
  464. {
  465. using namespace std;
  466. if(!redo_stack.empty())
  467. {
  468. undo_stack.push(s);
  469. s = redo_stack.top();
  470. redo_stack.pop();
  471. }
  472. }
  473. void key(unsigned char key, int mouse_x, int mouse_y)
  474. {
  475. using namespace std;
  476. int mod = glutGetModifiers();
  477. switch(key)
  478. {
  479. // ESC
  480. case char(27):
  481. rebar.save(REBAR_NAME);
  482. // ^C
  483. case char(3):
  484. exit(0);
  485. case 'I':
  486. case 'i':
  487. {
  488. push_undo();
  489. s.N *= -1.0;
  490. break;
  491. }
  492. case 'z':
  493. case 'Z':
  494. if(mod & GLUT_ACTIVE_COMMAND)
  495. {
  496. if(mod & GLUT_ACTIVE_SHIFT)
  497. {
  498. redo();
  499. }else
  500. {
  501. undo();
  502. }
  503. break;
  504. }else
  505. {
  506. push_undo();
  507. igl::snap_to_canonical_view_quat<double>(
  508. s.camera.rotation,
  509. 1.0,
  510. s.camera.rotation);
  511. break;
  512. }
  513. default:
  514. if(!TwEventKeyboardGLUT(key,mouse_x,mouse_y))
  515. {
  516. cout<<"Unknown key command: "<<key<<" "<<int(key)<<endl;
  517. }
  518. }
  519. }
  520. int main(int argc, char * argv[])
  521. {
  522. using namespace std;
  523. using namespace Eigen;
  524. using namespace igl;
  525. string filename = "../shared/truck.obj";
  526. if(argc < 2)
  527. {
  528. cerr<<"Usage:"<<endl<<" ./example input.obj"<<endl;
  529. cout<<endl<<"Opening default mesh..."<<endl;
  530. }else
  531. {
  532. // Read and prepare mesh
  533. filename = argv[1];
  534. }
  535. // print key commands
  536. cout<<"[Click] and [drag] Rotate model using trackball."<<endl;
  537. cout<<"[Z,z] Snap rotation to canonical view."<<endl;
  538. cout<<"[⌘ Z] Undo."<<endl;
  539. cout<<"[⇧ ⌘ Z] Redo."<<endl;
  540. cout<<"[^C,ESC] Exit."<<endl;
  541. // dirname, basename, extension and filename
  542. string d,b,ext,f;
  543. pathinfo(filename,d,b,ext,f);
  544. // Convert extension to lower case
  545. transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
  546. vector<vector<double > > vV,vN,vTC;
  547. vector<vector<int > > vF,vFTC,vFN;
  548. if(ext == "obj")
  549. {
  550. // Convert extension to lower case
  551. if(!igl::readOBJ(filename,vV,vTC,vN,vF,vFTC,vFN))
  552. {
  553. return 1;
  554. }
  555. }else if(ext == "off")
  556. {
  557. // Convert extension to lower case
  558. if(!igl::readOFF(filename,vV,vF,vN))
  559. {
  560. return 1;
  561. }
  562. }else if(ext == "wrl")
  563. {
  564. // Convert extension to lower case
  565. if(!igl::readWRL(filename,vV,vF))
  566. {
  567. return 1;
  568. }
  569. //}else
  570. //{
  571. // // Convert extension to lower case
  572. // MatrixXi T;
  573. // if(!igl::readMESH(filename,V,T,F))
  574. // {
  575. // return 1;
  576. // }
  577. // //if(F.size() > T.size() || F.size() == 0)
  578. // {
  579. // boundary_faces(T,F);
  580. // }
  581. }
  582. if(vV.size() > 0)
  583. {
  584. if(!list_to_matrix(vV,V))
  585. {
  586. return 1;
  587. }
  588. triangulate(vF,F);
  589. }
  590. init_patches();
  591. init_relative();
  592. // Init glut
  593. glutInit(&argc,argv);
  594. if( !TwInit(TW_OPENGL, NULL) )
  595. {
  596. // A fatal error occured
  597. fprintf(stderr, "AntTweakBar initialization failed: %s\n", TwGetLastError());
  598. return 1;
  599. }
  600. // Create a tweak bar
  601. rebar.TwNewBar("TweakBar");
  602. rebar.TwAddVarCB("camera_rotation", TW_TYPE_QUAT4D, set_camera_rotation,get_camera_rotation, NULL, "open");
  603. TwEnumVal RotationTypesEV[NUM_ROTATION_TYPES] =
  604. {
  605. {ROTATION_TYPE_IGL_TRACKBALL,"igl trackball"},
  606. {ROTATION_TYPE_TWO_AXIS_VALUATOR_FIXED_UP,"two axis fixed up"}
  607. };
  608. TwType RotationTypeTW =
  609. ReTwDefineEnum(
  610. "RotationType",
  611. RotationTypesEV,
  612. NUM_ROTATION_TYPES);
  613. rebar.TwAddVarCB( "rotation_type", RotationTypeTW,
  614. set_rotation_type,get_rotation_type,NULL,"keyIncr=] keyDecr=[");
  615. rebar.load(REBAR_NAME);
  616. // Init antweakbar
  617. glutInitDisplayString( "rgba depth double samples>=8 ");
  618. glutInitWindowSize(glutGet(GLUT_SCREEN_WIDTH)/2.0,glutGet(GLUT_SCREEN_HEIGHT)/2.0);
  619. glutCreateWindow("patches");
  620. glutDisplayFunc(display);
  621. glutReshapeFunc(reshape);
  622. glutKeyboardFunc(key);
  623. glutMouseFunc(mouse);
  624. glutMotionFunc(mouse_drag);
  625. glutPassiveMotionFunc((GLUTmousemotionfun)TwEventMouseMotionGLUT);
  626. glutMainLoop();
  627. return 0;
  628. }