render_to_buffer.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. // This required to get correct linking with Objective-C files
  2. extern "C" {
  3. #include "render_to_buffer.h"
  4. };
  5. #include <igl/per_face_normals.h>
  6. #include <igl/normalize_row_lengths.h>
  7. #include <igl/get_seconds.h>
  8. #include <igl/draw_mesh.h>
  9. #include <igl/draw_floor.h>
  10. #include <igl/material_colors.h>
  11. #include <igl/pathinfo.h>
  12. #include <igl/readOBJ.h>
  13. #include <igl/readPLY.h>
  14. #include <igl/readSTL.h>
  15. #include <igl/readWRL.h>
  16. #include <igl/polygon_mesh_to_triangle_mesh.h>
  17. #include <igl/readOFF.h>
  18. #include <igl/readMESH.h>
  19. #include <igl/boundary_facets.h>
  20. #include <igl/barycenter.h>
  21. #include <igl/doublearea.h>
  22. #include <igl/EPS.h>
  23. #include <igl/Camera.h>
  24. #include <igl/canonical_quaternions.h>
  25. #include <igl/quat_to_mat.h>
  26. #include <igl/Viewport.h>
  27. #include <Eigen/Core>
  28. #include <GL/glu.h>
  29. #include <algorithm>
  30. static int width,height;
  31. static Eigen::MatrixXd V,N;
  32. static Eigen::MatrixXi F;
  33. static Eigen::Vector3d Vmean, Vmax,Vmin;
  34. //static bool invert = false;
  35. static float background_color[4] = {0,0,0,1};
  36. // Small viewports struct for keeping track of size and camera info
  37. #define NUM_VIEWPORTS 6
  38. class AugViewport : public igl::Viewport
  39. {
  40. public:
  41. igl::Camera camera;
  42. } viewports[NUM_VIEWPORTS];
  43. // Red screen for errors
  44. void red(const int width, const int height, GLubyte * buffer)
  45. {
  46. for(int h = 0;h<height;h++)
  47. {
  48. for(int w = 0;w<width;w++)
  49. {
  50. for(int c = 0;c<4;c++)
  51. {
  52. if(c == 0 || c==3)
  53. {
  54. buffer[c+4*w+4*width*h] = 255;
  55. }else
  56. {
  57. buffer[c+4*w+4*width*h] = 0;
  58. }
  59. }
  60. }
  61. }
  62. }
  63. // Initialize the viewport angles and camera rotations
  64. void init_viewports()
  65. {
  66. using namespace igl;
  67. using namespace std;
  68. for(auto & vp : viewports)
  69. {
  70. // Reset. I guess Mac is keeping global variables alive...
  71. vp.camera = Camera();
  72. vp.camera.push_away(3.);
  73. vp.camera.dolly_zoom(10.-vp.camera.m_angle);
  74. }
  75. // Above view
  76. double XZ_PLANE_QUAT_D_FLIP[4];
  77. copy(XZ_PLANE_QUAT_D,XZ_PLANE_QUAT_D+4,XZ_PLANE_QUAT_D_FLIP);
  78. XZ_PLANE_QUAT_D_FLIP[0] *= -1.0;
  79. // Straight on
  80. copy(
  81. XY_PLANE_QUAT_D,
  82. XY_PLANE_QUAT_D+4,
  83. viewports[0].camera.m_rotation_conj.coeffs().data());
  84. // Left side view
  85. copy(
  86. CANONICAL_VIEW_QUAT_D[9],
  87. CANONICAL_VIEW_QUAT_D[9]+4,
  88. viewports[1].camera.m_rotation_conj.coeffs().data());
  89. copy(
  90. CANONICAL_VIEW_QUAT_D[14],
  91. CANONICAL_VIEW_QUAT_D[14]+4,
  92. viewports[2].camera.m_rotation_conj.coeffs().data());
  93. // Straight on
  94. copy(
  95. CANONICAL_VIEW_QUAT_D[4],
  96. CANONICAL_VIEW_QUAT_D[4]+4,
  97. viewports[3].camera.m_rotation_conj.coeffs().data());
  98. copy(
  99. XZ_PLANE_QUAT_D,
  100. XZ_PLANE_QUAT_D+4,
  101. viewports[4].camera.m_rotation_conj.coeffs().data());
  102. copy(
  103. XZ_PLANE_QUAT_D_FLIP,
  104. XZ_PLANE_QUAT_D_FLIP+4,
  105. viewports[5].camera.m_rotation_conj.coeffs().data());
  106. }
  107. // Viewports are arranged to see all sides
  108. //
  109. // /-----.-----.-----\
  110. // | 3 | 2 | 1 |
  111. // -------------------
  112. // | 4 | |
  113. // ------- 0 |
  114. // | 5 | |
  115. // \-----.-----------/
  116. void reshape_viewports()
  117. {
  118. using namespace igl;
  119. using namespace std;
  120. viewports[0].reshape(1./3.*width, 0,2./3.*width,2./3.*height);
  121. viewports[1].reshape(2./3.*width, 2./3.*height,1./3.*width,1./3.*height);
  122. viewports[2].reshape(1./3.*width, 2./3.*height,1./3.*width,1./3.*height);
  123. viewports[3].reshape( 0, 2./3.*height,1./3.*width,1./3.*height);
  124. viewports[4].reshape( 0, 1./3.*height,1./3.*width,1./3.*height);
  125. viewports[5].reshape( 0, 0,1./3.*width,1./3.*height);
  126. for(auto & vp : viewports)
  127. {
  128. vp.camera.m_aspect = (double)vp.width/(double)vp.height;
  129. }
  130. }
  131. void reshape(int width, int height)
  132. {
  133. using namespace std;
  134. ::width = width;
  135. ::height = height;
  136. reshape_viewports();
  137. }
  138. // Simple two-sided, diffuse-only light
  139. void lights()
  140. {
  141. using namespace std;
  142. glEnable(GL_LIGHTING);
  143. glLightModelf(GL_LIGHT_MODEL_TWO_SIDE,GL_TRUE);
  144. glEnable(GL_LIGHT0);
  145. glEnable(GL_LIGHT1);
  146. float WHITE[4] = {0.8,0.8,0.8,1.};
  147. float GREY[4] = {0.4,0.4,0.4,1.};
  148. float BLACK[4] = {0.,0.,0.,1.};
  149. float pos[4];
  150. float light_pos[4] = {0.1,0.1,1.0,0.0};
  151. copy(light_pos,light_pos+4,pos);
  152. glLightfv(GL_LIGHT0,GL_AMBIENT,GREY);
  153. glLightfv(GL_LIGHT0,GL_DIFFUSE,WHITE);
  154. glLightfv(GL_LIGHT0,GL_SPECULAR,BLACK);
  155. glLightfv(GL_LIGHT0,GL_POSITION,pos);
  156. pos[0] *= -1;
  157. pos[1] *= -1;
  158. pos[2] *= -1;
  159. glLightfv(GL_LIGHT1,GL_AMBIENT,GREY);
  160. glLightfv(GL_LIGHT1,GL_DIFFUSE,WHITE);
  161. glLightfv(GL_LIGHT1,GL_SPECULAR,BLACK);
  162. glLightfv(GL_LIGHT1,GL_POSITION,pos);
  163. }
  164. // Push scene based on viewport
  165. void push_scene(const AugViewport & vp)
  166. {
  167. using namespace igl;
  168. using namespace std;
  169. glMatrixMode(GL_PROJECTION);
  170. glPushMatrix();
  171. glLoadIdentity();
  172. auto & camera = vp.camera;
  173. glMultMatrixd(camera.projection().data());
  174. glMatrixMode(GL_MODELVIEW);
  175. glPushMatrix();
  176. glLoadIdentity();
  177. // -1 because buffer y-coordinates are flipped
  178. gluLookAt(
  179. camera.eye()(0), camera.eye()(1), camera.eye()(2),
  180. camera.at()(0), camera.at()(1), camera.at()(2),
  181. camera.up()(0), -1*camera.up()(1), camera.up()(2));
  182. }
  183. // Scale and shift for object so that it fits current view
  184. void push_object(const AugViewport & vp)
  185. {
  186. using namespace Eigen;
  187. glPushMatrix();
  188. Matrix3d m = vp.camera.m_rotation_conj.matrix();
  189. Vector3d eff_Vmax = m*Vmax;
  190. Vector3d eff_Vmin = m*Vmin;
  191. Vector3d eff_Vmean = m*Vmean;
  192. const double dy = fabs(eff_Vmax(1,0)-eff_Vmin(1,0));
  193. const double dx = fabs(eff_Vmax(0,0)-eff_Vmin(0,0));
  194. //const double dz = fabs(eff_Vmax(2,0)-eff_Vmin(2,0));
  195. // Assumes height < width
  196. const double sx = dx*(double)height/(double)width;
  197. const double sy = dy;
  198. const double s = 2./(sy > sx ? sy : sx);
  199. glScaled(s,s,s);
  200. glTranslated(-Vmean(0,0),-Vmean(1,0),-Vmean(2,0));
  201. // Hack. Should really just figure out max scale so that full model fits on
  202. // screen with given perspective.
  203. //const double dz_off = (dz > 2.*dy && dz > 2.*dx ? dz/2. : 0);
  204. //glTranslated(0,0,-dz_off);
  205. }
  206. void pop_object()
  207. {
  208. glPopMatrix();
  209. }
  210. void pop_scene()
  211. {
  212. glMatrixMode(GL_PROJECTION);
  213. glPopMatrix();
  214. glMatrixMode(GL_MODELVIEW);
  215. glPopMatrix();
  216. }
  217. void display()
  218. {
  219. using namespace std;
  220. using namespace igl;
  221. glClearColor(
  222. background_color[0],
  223. background_color[1],
  224. background_color[2],
  225. background_color[3]);
  226. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  227. glEnable(GL_DEPTH_TEST);
  228. glEnable(GL_NORMALIZE);
  229. glDisable(GL_CULL_FACE);
  230. glCullFace(GL_BACK);
  231. // "Flash light" attached to camera
  232. lights();
  233. // Draw for each viewport
  234. for(int vp = 0;vp<NUM_VIEWPORTS;vp++)
  235. {
  236. glViewport(
  237. viewports[vp].x,
  238. viewports[vp].y,
  239. viewports[vp].width,
  240. viewports[vp].height);
  241. push_scene(viewports[vp]);
  242. push_object(viewports[vp]);
  243. // Draw the mesh, inverted if need be.
  244. // Set material properties
  245. glDisable(GL_COLOR_MATERIAL);
  246. //if(invert)
  247. //{
  248. // glFrontFace(GL_CW);
  249. // glMaterialfv(GL_FRONT, GL_AMBIENT, CYAN_AMBIENT);
  250. // glMaterialfv(GL_FRONT, GL_DIFFUSE, CYAN_DIFFUSE );
  251. // glMaterialfv(GL_FRONT, GL_SPECULAR, CYAN_SPECULAR);
  252. // glMaterialf (GL_FRONT, GL_SHININESS, 128);
  253. // glMaterialfv(GL_BACK, GL_AMBIENT, SILVER_AMBIENT);
  254. // glMaterialfv(GL_BACK, GL_DIFFUSE, FAST_RED_DIFFUSE);
  255. // glMaterialfv(GL_BACK, GL_SPECULAR, SILVER_SPECULAR);
  256. // glMaterialf (GL_BACK, GL_SHININESS, 128);
  257. //}else
  258. //{
  259. glMaterialfv(GL_FRONT, GL_AMBIENT, GOLD_AMBIENT);
  260. glMaterialfv(GL_FRONT, GL_DIFFUSE, GOLD_DIFFUSE );
  261. glMaterialfv(GL_FRONT, GL_SPECULAR, GOLD_SPECULAR);
  262. glMaterialf (GL_FRONT, GL_SHININESS, 128);
  263. glMaterialfv(GL_BACK, GL_AMBIENT, SILVER_AMBIENT);
  264. glMaterialfv(GL_BACK, GL_DIFFUSE, FAST_GREEN_DIFFUSE );
  265. glMaterialfv(GL_BACK, GL_SPECULAR, SILVER_SPECULAR);
  266. glMaterialf (GL_BACK, GL_SHININESS, 128);
  267. //}
  268. if(F.rows() == 0)
  269. {
  270. glPointSize(1.+ 20./log10(V.rows()));
  271. const bool has_normals = N.rows() == V.rows();
  272. glBegin(GL_POINTS);
  273. for(int v = 0;v<V.rows();v++)
  274. {
  275. if(has_normals)
  276. {
  277. glNormal3d(N(v,0),N(v,1),N(v,2));
  278. }
  279. glVertex3d(V(v,0),V(v,1),V(v,2));
  280. }
  281. glEnd();
  282. }else
  283. {
  284. draw_mesh(V,F,N);
  285. }
  286. //if(invert)
  287. //{
  288. // glFrontFace(GL_CCW);
  289. //}
  290. pop_object();
  291. // Draw a nice floor unless we're looking from beneath it
  292. if(vp != 4)
  293. {
  294. glPushMatrix();
  295. glTranslated(0,-1,0);
  296. glScaled(4,4,4);
  297. draw_floor();
  298. glPopMatrix();
  299. }
  300. pop_scene();
  301. }
  302. // Screen space
  303. glDisable(GL_DEPTH_TEST);
  304. glDisable(GL_LIGHTING);
  305. glViewport(0,0,width,height);
  306. glMatrixMode(GL_PROJECTION);
  307. glLoadIdentity();
  308. gluOrtho2D(0,width,0,height);
  309. glMatrixMode(GL_MODELVIEW);
  310. glLoadIdentity();
  311. // Draw separation lines between (around) viewports
  312. const double BAR_THICKNESS = 3.0;
  313. glColor3f(0.5,0.5,0.5);
  314. for(int vp = 0;vp<NUM_VIEWPORTS;vp++)
  315. {
  316. glLineWidth(BAR_THICKNESS);
  317. glBegin(GL_LINE_STRIP);
  318. glVertex2f(viewports[vp].x,viewports[vp].y);
  319. glVertex2f(viewports[vp].x+viewports[vp].width,viewports[vp].y);
  320. glVertex2f(viewports[vp].x+viewports[vp].width,viewports[vp].y+viewports[vp].height);
  321. glVertex2f( viewports[vp].x,viewports[vp].y+viewports[vp].height);
  322. glEnd();
  323. }
  324. glFinish();
  325. }
  326. bool render_to_buffer(
  327. const char * filename,
  328. const float * background_color,
  329. const int width,
  330. const int height,
  331. GLubyte * buffer)
  332. {
  333. using namespace igl;
  334. using namespace std;
  335. using namespace Eigen;
  336. double ts = get_seconds();
  337. copy(background_color,background_color+4,::background_color);
  338. // Read and prepare mesh
  339. // dirname, basename, extension and filename
  340. string d,b,ext,f;
  341. pathinfo(filename,d,b,ext,f);
  342. // Convert extension to lower case
  343. transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
  344. vector<vector<double > > vV,vN,vTC;
  345. vector<vector<int > > vF,vFTC,vFN;
  346. if(ext == "obj")
  347. {
  348. // Convert extension to lower case
  349. if(!igl::readOBJ(filename,vV,vTC,vN,vF,vFTC,vFN))
  350. {
  351. cerr<<"readOBJ failed."<<endl;
  352. red(width,height,buffer);
  353. return false;
  354. }
  355. }else if(ext == "off")
  356. {
  357. // Convert extension to lower case
  358. if(!igl::readOFF(filename,vV,vF,vN))
  359. {
  360. cerr<<"readOFF failed."<<endl;
  361. red(width,height,buffer);
  362. return false;
  363. }
  364. }else if(ext == "wrl")
  365. {
  366. // Convert extension to lower case
  367. if(!igl::readWRL(filename,vV,vF))
  368. {
  369. red(width,height,buffer);
  370. return false;
  371. }
  372. }else if(ext == "ply")
  373. {
  374. // Convert extension to lower case
  375. if(!igl::readPLY(filename,vV,vF,vN,vTC))
  376. {
  377. red(width,height,buffer);
  378. return false;
  379. }
  380. }else if(ext == "stl")
  381. {
  382. // Convert extension to lower case
  383. if(!igl::readSTL(filename,vV,vF,vN))
  384. {
  385. red(width,height,buffer);
  386. return false;
  387. }
  388. }else
  389. {
  390. // Convert extension to lower case
  391. MatrixXi T;
  392. if(!igl::readMESH(filename,V,T,F))
  393. {
  394. red(width,height,buffer);
  395. return false;
  396. }
  397. //if(F.size() > T.size() || F.size() == 0)
  398. {
  399. boundary_facets(T,F);
  400. }
  401. }
  402. if(vV.size() > 0)
  403. {
  404. if(!list_to_matrix(vV,V))
  405. {
  406. cerr<<"list_to_matrix failed."<<endl;
  407. red(width,height,buffer);
  408. return false;
  409. }
  410. if(!list_to_matrix(vN,N))
  411. {
  412. // silently continue
  413. N.resize(0,0);
  414. }
  415. polygon_mesh_to_triangle_mesh(vF,F);
  416. }
  417. cout<<"IO: "<<(get_seconds()-ts)<<"s"<<endl;
  418. ts = get_seconds();
  419. // Compute already normalized per triangle normals
  420. if(N.rows() != V.rows() && N.rows() != F.rows())
  421. {
  422. per_face_normals(V,F,N);
  423. }
  424. //Vmean = 0.5*(V.colwise().maxCoeff()+V.colwise().minCoeff());
  425. Vmax = V.colwise().maxCoeff();
  426. Vmin = V.colwise().minCoeff();
  427. Vmean = 0.5*(Vmax + Vmin);
  428. //// Figure out if normals should be flipped (hopefully this is never a
  429. //// bottleneck)
  430. //MatrixXd BC;
  431. //VectorXd dblA;
  432. //barycenter(V,F,BC);
  433. //BC.col(0).array() -= Vmean(0,0);
  434. //BC.col(1).array() -= Vmean(1,0);
  435. //BC.col(2).array() -= Vmean(2,0);
  436. //doublearea(V,F,dblA);
  437. //VectorXd BCDN = (BC.array() * N.array()).rowwise().sum();
  438. //const double tot_dp = dblA.transpose() * BCDN;
  439. //invert = tot_dp < 0;
  440. //cout<<"Normals: "<<(get_seconds()-ts)<<"s"<<endl;
  441. //ts = get_seconds();
  442. // Initialize MESA
  443. OSMesaContext ctx;
  444. /* Create an RGBA-mode context */
  445. # if OSMESA_MAJOR_VERSION * 100 + OSMESA_MINOR_VERSION >= 305
  446. /* specify Z, stencil, accum sizes */
  447. ctx = OSMesaCreateContextExt( OSMESA_RGBA, 32, 0, 0, NULL );
  448. # else
  449. ctx = OSMesaCreateContext( OSMESA_RGBA, NULL );
  450. # endif
  451. if (!ctx)
  452. {
  453. fprintf(stderr,"OSMesaCreateContext failed!\n");
  454. red(width,height,buffer);
  455. return false;
  456. }
  457. /* Bind the buffer to the context and make it current */
  458. if (!OSMesaMakeCurrent( ctx, buffer, GL_UNSIGNED_BYTE, width, height))
  459. {
  460. fprintf(stderr,"OSMesaMakeCurrent failed!\n");
  461. red(width,height,buffer);
  462. return false;
  463. }
  464. // Render
  465. init_viewports();
  466. reshape(width,height);
  467. display();
  468. cout<<"Display: "<<(get_seconds()-ts)<<"s"<<endl;
  469. ts = get_seconds();
  470. /* destroy the context */
  471. OSMesaDestroyContext( ctx );
  472. return true;
  473. }