render_to_buffer.cpp 12 KB

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