code_junkie

How do I reverse-project 2D points into 3D?

Nov 10th, 2011
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. void YCamera :: CalculateWorldCoordinates(float x, float y, YVector3 *vec)
  2. {
  3. // START
  4. GLint viewport[4];
  5. GLdouble mvmatrix[16], projmatrix[16];
  6.  
  7. GLint real_y;
  8. GLdouble mx, my, mz;
  9.  
  10. glGetIntegerv(GL_VIEWPORT, viewport);
  11. glGetDoublev(GL_MODELVIEW_MATRIX, mvmatrix);
  12. glGetDoublev(GL_PROJECTION_MATRIX, projmatrix);
  13.  
  14. real_y = viewport[3] - (GLint) y - 1; // viewport[3] is height of window in pixels
  15. gluUnProject((GLdouble) x, (GLdouble) real_y, 1.0, mvmatrix, projmatrix, viewport, &mx, &my, &mz);
  16.  
  17. /* 'mouse' is the point where mouse projection reaches FAR_PLANE.
  18. World coordinates is intersection of line(camera->mouse) with plane(z=0) (see LaMothe 306)
  19.  
  20. Equation of line in 3D:
  21. (x-x0)/a = (y-y0)/b = (z-z0)/c
  22.  
  23. Intersection of line with plane:
  24. z = 0
  25. x-x0 = a(z-z0)/c <=> x = x0+a(0-z0)/c <=> x = x0 -a*z0/c
  26. y = y0 - b*z0/c
  27.  
  28. */
  29. double lx = fPosition.x - mx;
  30. double ly = fPosition.y - my;
  31. double lz = fPosition.z - mz;
  32. double sum = lx*lx + ly*ly + lz*lz;
  33. double normal = sqrt(sum);
  34. double z0_c = fPosition.z / (lz/normal);
  35.  
  36. vec->x = (float) (fPosition.x - (lx/normal)*z0_c);
  37. vec->y = (float) (fPosition.y - (ly/normal)*z0_c);
  38. vec->z = 0.0f;
  39.  
  40. GLint real_y;
  41. GLdouble mx, my, mz;
  42.  
  43. glGetIntegerv(GL_VIEWPORT, viewport);
  44. glGetDoublev(GL_MODELVIEW_MATRIX, mvmatrix);
  45. glGetDoublev(GL_PROJECTION_MATRIX, projmatrix);
  46.  
  47. real_y = viewport[3] - (GLint) y - 1; // viewport[3] is height of window in pixels
  48. gluUnProject((GLdouble) x, (GLdouble) real_y, 1.0, mvmatrix, projmatrix, viewport, &mx, &my, &mz);
  49.  
  50. /* 'mouse' is the point where mouse projection reaches FAR_PLANE.
  51. World coordinates is intersection of line(camera->mouse) with plane(z=0) (see LaMothe 306)
  52.  
  53. Equation of line in 3D:
  54. (x-x0)/a = (y-y0)/b = (z-z0)/c
  55.  
  56. Intersection of line with plane:
  57. z = 0
  58. x-x0 = a(z-z0)/c <=> x = x0+a(0-z0)/c <=> x = x0 -a*z0/c
  59. y = y0 - b*z0/c
  60.  
  61. */
  62. double lx = fPosition.x - mx;
  63. double ly = fPosition.y - my;
  64. double lz = fPosition.z - mz;
  65. double sum = lx*lx + ly*ly + lz*lz;
  66. double normal = sqrt(sum);
  67. double z0_c = fPosition.z / (lz/normal);
  68.  
  69. vec->x = (float) (fPosition.x - (lx/normal)*z0_c);
  70. vec->y = (float) (fPosition.y - (ly/normal)*z0_c);
  71. vec->z = 0.0f;
Add Comment
Please, Sign In to add comment