example.cpp 15 KB

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