render_to_buffer.cpp 12 KB

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