home *** CD-ROM | disk | FTP | other *** search
/ DP Tool Club 24 / CD_ASCQ_24_0995.iso / vrac / 3d_prog.zip / 3D_PROG.18 next >
Text File  |  1995-08-11  |  37KB  |  866 lines

  1. Newsgroups: rec.games.programmer,comp.graphics,rec.answers,comp.answers,news.answers
  2. Path: senator-bedfellow.mit.edu!bloom-beacon.mit.edu!news.kei.com!news.mathworks.com!uunet!inews.intel.com!itnews.intel.com!chnews!ornews.intel.com!news.jf.intel.com!psinntp!psinntp!isc-newsserver!csh-newsserver.csh.rit.edu!nick.csh.rit.edu!pat
  3. From: pat@mail.csh.rit.edu
  4. Subject: FAQ: 3-D Information for the Programmer
  5. X-Archive-Information: /pub/3dfaq/FAQ.n @ ftp.csh.rit.edu
  6. Message-ID: <L3+16D.bvD@csh-newsserver.csh.rit.edu>
  7. Followup-To: rec.games.programmer
  8. Summary: Still in progress, fill-in-the-blanks...
  9. Originator: pat@nick.csh.rit.edu
  10. Keywords: game-programming 3d-transforms faq
  11. Sender: pat@mail.csh.rit.edu
  12. Nntp-Posting-Host: mcp.csh.rit.edu
  13. Reply-To: pat@mail.csh.rit.edu
  14. Organization: Computer Science House @ RIT
  15. X-Posting-Information: This article posted automagically, weekly.
  16. Date: Mon, 3 Apr 1995 08:46:35 GMT
  17. Approved: news-answers-request@MIT.Edu
  18. Lines: 845
  19. Xref: senator-bedfellow.mit.edu rec.games.programmer:51483 comp.graphics:73551 rec.answers:11127 comp.answers:11011 news.answers:41244
  20.  
  21. Archive-name: 3d-programmer-info
  22. Version: $Id: .header,v 1.8 1994/05/23 15:55:59 pat Exp pat $
  23.  
  24.                       O                                O
  25.  
  26.  ---+  +---- F A Q ------------------+  +------- F A Q ---------------+  +---
  27.  %[%|  |X$HOOR$H\[[8@DoooDDDDD8@@[%[%|  |X$HOOR$H\[[8@DoooDDDDD8@@[%[%|  |X$H
  28.  [[%|  |$C$OOR$H\%[8DooooDDDD8D@@[[[%|  |$C$OOR$H\%[8DooooDDDD8D@@[[[%|  |$C$
  29.  [[%|  |X$HHRR$H@[            88@@[[%|  |X$HHRR            DDDD88@@[[%|  |X$H
  30.  [[[|  |$$$HRR$H@%[@8ooooD   888@[[[[|  |$$$HRR$H@%[@8o   DDDD888@[[[[|  |$$$
  31.  [[[|  |X$$H            /   /  88[[[[|  |X$          /   /    D888[[[[|  |X$$
  32.  [%[|  |XC$H    \%[@8DDD   DD   @[[%[|  |XC    $H\%[@   DDDD   88@[[%[|  |XC$
  33.  [[%|  |XC$H    \%%@8DD   DDDD   @[[%|  |XC    $H\%%   DDDDDD   8@@[[%|  |XC$
  34.  [%[|  |X$$H    \%%@88DDD   D8   @[%[|  |X$    $H\%%@8   DDD8   8@@[%[|  |X$$
  35.  [%[|  |CX$H    \%%[88DDD88  D   @[%[|  |CX    $H\%%[88D  88D   8@@[%[|  |CX$
  36.  [%[|  |X$CH    \%[[@888D8D8  |  @[%[|  |X$   _$H\%[[@888  88   88@[%[|  |X$C
  37.  [%[|  |XXCH    |  [@888D888  | @@[%[|  |XX  |  H\@[[@888  8   88@@[%[|  |XXC
  38.  [%[|  |XC$$    \  \       |  |88@[%[|  |XC  \  \       |  |  8888@[%[|  |XC$
  39.  [%[|  |XX$HOR$HH@  [@88888  8D8@@[%[|  |XX$HOR  H@[%[@8  @8888D8@@[%[|  |XX$
  40.  [%[|  |X$CHOR$H\@%  @@@@Y  8888@@[%[|  |X$CHOR$  @%%[Y  @8888888@@[%[|  |X$C
  41.  [%[|  |CX$$OR$HH@%%      .d8D88@@[%[|  |CX$$OR$H      .d@@888D88@@[%[|  |CX$
  42.  [[[|  |X$$HOR$HH@%%[[@@@@88D8D88@[[[|  |X$$HOR$HH@%%[[@@@@88D8D88@[[[|  |X$$
  43.  [%[|  |CX$HOR$HH\%[%[@@@@888D88@@[%[|  |CX$HOR$HH\%[%[@@@@888D88@@[%[|  |CX$
  44.  ---+  +--------------- F A Q -------+  +------------------ F A Q ----+  +---
  45.  
  46. Contents:
  47. 1) General references for 3-d graphics questions.
  48. 2) How do I define an object?
  49. 3) How do I define space?
  50. 4) How do I define position?
  51. 5) How do I define orientation?
  52. 6) How do I define a velocity?
  53. 7) Drawing three-dimensional objects on a two-dimensional screen.
  54. 8) Vector Math - Dot Product and Cross-Product.
  55. 9) Matrix Math
  56. 10) Collisions.
  57. 11) Perspective.
  58. 12) Z-Buffering & the Painters Algorithm & BSP-Trees.
  59. 13) Shading.
  60. 14) 3-space clipping.
  61. 15) 3-d scanning.
  62. 16) Publically available source-code.
  63. 17) Books on the topics.
  64. 18) Other forums.
  65. 19) Current Contents of Archive ftp.csh.rit.edu::/pub/3dfaq
  66.  
  67. Last update:
  68.      03Jan95
  69.  
  70. What's new?
  71.  
  72.      Added a bunch of new books without net-reviews and a few more http
  73.      sites.
  74.  
  75.      Added some information on velocity calculations.
  76.  
  77. 1) General references for 3-d graphics questions.
  78.  
  79.      Well, this FAQ is just getting off the ground.  Hopefully it will
  80. touch on most of the bases you need to get started for now, and
  81. hopefully it will expand at least as fast as you need it too.  But...
  82. regardless, things you'll want to locate for more help are Matrix
  83. Algebra books, Physics books talking about Eulerian motion, and some
  84. books on the Graphics Hardware you want to program for.  The code
  85. examples included in this FAQ will most likely be in C with pseudo-code
  86. in comments.
  87.  
  88.      One of the most popular references, (and one of my favorites), is:
  89.           Computer Graphics: Principles and Practice
  90.           ------------------------------------------
  91.           Foley, van Dam, Feiner, and Hughes
  92.           Addison Wesley -- Reading, Massachusetts
  93.           (c) 1990.  ISBN 0-201-12110-7
  94.  
  95.      But, you'll also want to definitely check out the FAQ for
  96. comp.graphics.  That FAQ touches mainly on 2-D needs, but some 3-D
  97. aspects are reviewed there, too.
  98.  
  99. 2) How do I define an object?
  100.  
  101.      There are lots of ways to define objects.  One of the most commonly
  102. used is the OFF (Object File Format).  The OFF toolkit and a library of
  103. objects are available via anonymous ftp from gatekeeper.dec.com -- XXX
  104. ??? (I can't find it anymore.  I found it here once about 2 years ago,
  105. but I haven't found it since).  The format provides easy methods for
  106. extensions and a base set of things you can expect for each object.  The
  107. toolkit is a bit bulky, but the file format (in ascii) is easy enough to
  108. parse by hand.
  109.  
  110.      The OFF.aoff file contains information about the object.  The most
  111. important one there is the location of the surface specification file
  112. (usually object name.geom).  This file also contains other attributes
  113.                -
  114. and file names relevant to this object.
  115.  
  116.      The OFF surface specification begins with the number of points, the
  117. number of polygons and the number of segments.
  118.  
  119.         npts nplys nsegs
  120.  
  121. This line is followed by the floating point coordinates for the points
  122. that make up the object.
  123.  
  124.         x1 y1 z1
  125.         x2 y2 z2
  126.         x3 y3 z3
  127.            .
  128.  
  129.            .
  130.  
  131.            .
  132.         x(npts) y(npts) z(npts)
  133.  
  134. Then, it gets a bit more complicated.  The following lines begin with a
  135. number to indicate the number of vertices in this polygon.  That number
  136. is followed by that many numbers, one for each vertex.  These are given
  137. in an order specified in the .aoff (usually conter-clockwise).  So, for
  138. example, a triangle and a pentagon which share a side are shown below.
  139.  
  140.         3       1 3 4
  141.         5       2 4 3 6 7
  142.  
  143. Here is some quick and dirty sample code to read in the .geom file:
  144.  
  145. struct polygon {
  146.     int nvert;          /* Number of vertices in this polygon */
  147.     int *verts;         /* Vertices in this polygon */
  148. };
  149.  
  150. struct object {
  151.     int npts;           /* The number of points */
  152.     int npolys;         /* The number of polygons */
  153.     int nsegs;          /* The number of segments */
  154.     double *point x,*point y,*point z;
  155.                  -        -        -
  156.     struct polygon *polys;
  157. };
  158.  
  159. int
  160. read geom file( char *geom file, struct object *obj )
  161.     -    -                -
  162. {
  163.     FILE *fp;
  164.     int i,j;
  165.  
  166.     if (!(fp = fopen(geom file,"r")))           /* Open the .geom file */
  167.                          -
  168.         return -1;
  169.  
  170.                                                 /* Get header information */
  171.     fscanf(fp,"%d %d %d",&obj.npts,&obj.npolys,&obj.nsegs);
  172.  
  173.         /*
  174.         ** Allocate room for the points.
  175.         */
  176.     obj.point x = (double *)malloc(obj.npts*sizeof(double));
  177.              -
  178.     obj.point y = (double *)malloc(obj.npts*sizeof(double));
  179.              -
  180.     obj.point z = (double *)malloc(obj.npts*sizeof(double));
  181.              -
  182.  
  183.     for (i=0;i<obj.npts;++i)
  184.         fscanf(fp,"%lf %lf %lf",&obj.point x[i],
  185.                                           -
  186.                                 &obj.point y[i],
  187.                                           -
  188.                                 &obj.point z[i]);
  189.                                           -
  190.  
  191.         /* Allocate room for the polygons.  */
  192.     obj.polys = (struct polygon *)malloc(obj.npolys*sizeof(struct polygon));
  193.  
  194.     for (i=0;i<obj.npts;++i) {
  195.             /* See how many vertices this has */
  196.         fscanf(fp,"%d",&obj.polys[i].nvert);
  197.  
  198.             /* Allocate room for vertices */
  199.         obj.polys[i].verts = (int *)malloc(obj.npolys*sizeof(int));
  200.  
  201.             /* Get each vertex */
  202.  
  203.         for (j=0;j<obj.polys[i].nvert;++j)
  204.  
  205.             fscanf(fp,"%d",&obj.polys[i].verts[j]);
  206.     }
  207. }
  208.  
  209. 3) How do I define space?
  210.  
  211.      There are several things to consider when picking a coordinate
  212. system.  Most important of these is how you intend to handle objects.
  213. If your objects are defined in terms of <x,y,z> triplets, it will
  214. require a fair bit of work on reading them in to turn them into
  215. spherical coordinates.  If you're looking to this FAQ for information on
  216. how to define the space your objects will be in, I'd strongly suggest
  217. using rectangular coordinates and some derivative of the OFF-format.
  218.  
  219.      For starters, let me just throw in that while our universe may be
  220. infinite in all directions, that doesn't make for good programming.  We
  221. have to limit ourselves to small enough numbers that we can multiply
  222. them together without overflowing them, we can divide them without
  223. crashing our systems, and we can add them without accidentally flipping
  224. a sign bit.
  225.  
  226.      Now, the fun begins.  The simplest form of defining the Universe is
  227. to flat out say that the Universe stretches over these coordinates, say
  228. in the bounding box of <-65536, -65536, -65536> to <65536, 65536,
  229. 65536>.  This is often referred to as a Universal Coordinate system or
  230. an Absolute Coordinate system.  Then, each object in the Universe will
  231. be centered about some coordinate in that range.  This includes your
  232. viewpoint.  Several strategies are available for dealing with the edge
  233. of the Universe.  One can make the Universe wrap around so that an
  234. object leaving the cube at < X, Y, 65536> will re-appear in the Universe
  235. at < X, Y, -65536>.  Or, one can make objects bounce or stop at the edge
  236. of the Universe.  And, given any approach, one can have the edge of the
  237. Universe be transparent or opaque.
  238.  
  239.      In an Absolute Coordinate system, all objects must be shown from
  240. the position of your viewpoint.  This involves lots of interesting math
  241. that we'll get into later.  But, in general, an objects position with
  242. respect to you is it's absolute position - your absolute position (with
  243. all kinds of hell breaking loose if you can see past the edge of the
  244. Universe).  Then, after this position is calculated, it must be rotated
  245. based on your orientation in the Universe.
  246.  
  247.      Another possibility for defining space is a Relative Coordinate
  248. system or a View-Centered Coordinate system.  In this sort of system,
  249. the Viewpoint is always at coordinates <0,0,0> and everything else in
  250. the Universe is based relatively to this home position.  This causes
  251. funky math to come into play when dealing with velocities of objects,
  252. but... it does wonders for not having to deal with the 'edge of the
  253. Universe'.  This is the Schroedinger's cat method of the 'edge of the
  254. Universe'.... in the truest sense of out of sight is out of mind.  Small
  255. provisions have to be made if objects aren't to wrap around.  But... a
  256. Relative Coordinate system can be used to give the illusion of infinite
  257. space on a finite machine.  (Yes, even your 486/66DX is finite).
  258.  
  259.      I'll leave spherical coordinates to a later version if people think
  260. they'll be of use...
  261.  
  262. 4) How do I define position?
  263.  
  264.      Position in an Absolute Coordinate system is easy.  Each object has
  265.  
  266. three coordinates.  These are often stored in a data-type called a
  267. vector to abstract further the notion that these numbers belong
  268. together.
  269.  
  270.         typedef struct {
  271.                 long x;
  272.                 long y;
  273.                 long z;
  274.         } VECT;
  275.  
  276. Usually, each object in the Universe is defined about its center with
  277. each coordinate on its surface being centered at its own <0,0,0>.  This
  278. helps tremendously in rotating the object, and I would highly recommend
  279. this.  Then, the object as a whole is given a position in space.  When
  280. it comes time to draw this object, its points' coordinates get added on
  281. to its position.
  282.  
  283.      In a Relative Coordinate system, position is also fairly straight
  284. forward.  The view-point always has position VECT={ 0, 0, 0 };.  Other
  285. objects follow the same sort of system that they would in Absolute
  286. Coordinate systems.
  287.  
  288. 5) How do I define orientation?
  289.  
  290.      Orientation can be quite tricky.  I interchange some of the terms
  291. here quite often.  In 3-space, orientation must be defined be two-and-
  292. a-half angles.  "Two and a half?" you say.  Well, almost everyone uses
  293. three because two just isn't enough, but if you want to be technical,
  294. one of those angles only has to range from 0 - 180 degrees (0 - PI/2
  295. radians).
  296.  
  297.      But, taking that for granted now.... you have to pick an
  298. orientation for your view.  I personally prefer to have the X-axis run
  299. from left to right across the center of my screen.  I also like to have
  300. the Y-axis run from the bottom of my screen; and I also like to have the
  301. Z-axis running from me straight into my screen.  With some tweaking of
  302. plus and minus signs and a bit of re-ordering, all of the math here-in
  303. can be modified to reflect any orientation of the coordinate system.
  304. Some people prefer to have the Y-axis heading into the screen with the
  305. Z-axis going vertically.  It's all a matter of how you want to define
  306. stuff.
  307.  
  308.      Given that you've agreed with me that Z can go into the screen,
  309. what 3-angles do you need?  (Here's where I stand the biggest chance of
  310. mucking up the terms.)  You need roll, pitch, and yaw.  (I often mix up
  311. roll and yaw and such... so if you can follow along without getting
  312. locked into my terminology, future FAQ's will correct it.)
  313.  
  314.      Look at your monitor as you're reading this.  Now tilt your head so
  315. that your right ear is on your right shoulder.  This change in
  316. orientation is roll (or yaw... but I call it roll).
  317.  
  318.      Ok, now sit up straight again. Now bring your chin down to meet
  319. your chest.  (Hmmm... LOOK BACK NOW!!!, whew... glad you heard me.)
  320. That motion was pitch.
  321.  
  322.      Ok, now look over your right shoulder keeping your head vertical to
  323. see who's behind you.  (LOOK BACK AGAIN!!.)  Ok... that was yaw (or
  324. roll, but I call it yaw).
  325.  
  326.      That's the basics.  Now, what do I do with them?  Well, here's
  327.  
  328. where a nice book on Matrix Arithmetic will help you out.  You have to
  329.  
  330. use these three angles to make a Transformation matrix.  [See the
  331. section on Matrix Math].  Here is a typical method of doing these
  332. transformations: [Note, if you don't have Z going into your screen
  333. you'll have to munge these considerably].
  334.  
  335.         typedef double matrix[4][4];
  336.         double sr,sp,sy,cr,cp,cy;
  337.         matrix mr, mp, my;      /* individual transformations */
  338.         matrix s;               /* final matrix */
  339.  
  340.         sr = sin( roll );     cr = cos( roll );
  341.         sp = sin( pitch );    cp = cos( pitch );
  342.         sy = sin( yaw );      cy = cos( yaw );
  343.  
  344.                                 /* clear all matrixes
  345.                                 ** [See the section on Matrix Math]
  346.                                 */
  347.         identity( &mr ); identity( &mp ); identity( &my );
  348.                                 /* prepare roll matrix */
  349.         mr[0][0] = mr[1][1] = cr;
  350.         mr[1][0] = - (mr[0][1] = sr);
  351.  
  352.                                 /* prepare pitch matrix */
  353.         mp[1][1] = mp[2][2] = cp;
  354.         mp[1][2] = - (mp[2][1] = sp);
  355.  
  356.                                 /* prepare yaw matrix */
  357.         my[0][0] = my[2][2] = cy;
  358.         my[0][2] = - (my[2][0] = sy);
  359.  
  360.         multiply( &mr, &my, &s );
  361.         multiply( &s, &mp, &s );
  362.  
  363. 6) How do I define a velocity?
  364.  
  365. I've always been annoyed by programs that make it advantageous to run on
  366. a slower machine.  A naive view of velocity as n-units per time-
  367. through-this-loop means that things move faster if you get through the
  368. loop faster.
  369.  
  370.      In order to by-pass this problem, you have to keep track of time in
  371. some non-hardware-dependent way.  Then, you can define your velocity in
  372. n-units per known-time-unit.  For ease of mental calculations, I always
  373. define my velocities in units per second.  (In actuality, in programming
  374. in DOS, I define my velocity in n-units per 160/182ths of a second
  375. because I'd rather divide by 16 than 18.2).
  376.  
  377.      Here is some pseudo-code for an object moving along a line....
  378.  
  379.     int x = 0;                  /* position */
  380.     int vx = 10;                /* velocity */
  381.     int dx;
  382.     int err fact = 0;
  383.            -
  384.     int old time = gettime(); /* in milliseconds for instance */
  385.            -
  386.     int new time;
  387.            -
  388.     int elapsed;
  389.  
  390.     for (;;) {
  391.         new time = gettime();
  392.            -
  393.         elapsed = new time - old time;
  394.                      -          -
  395.         dx = vx * elapsed + err fact;
  396.                                -
  397.  
  398.         x += dx/1000;
  399.  
  400.         err fact = dx - (dx/1000)*1000;
  401.            -
  402.         old time = new time;
  403.            -          -
  404.     }
  405.  
  406.      You can ignore all of the err fact stuff if you like, but then
  407.                                   -
  408. velocities that are much lower than your time frequency could end up
  409. excessively slow or fast.
  410.  
  411.      This approach can be used for each linear velocity (x, y, and z).
  412. But, this approach isn't nearly so good for rotational velocities.  I'm
  413. still stewing on the best way to handle them.
  414.  
  415. 7) Drawing three-dimensional objects on a two-dimensional screen.
  416.  
  417.      Modified from comp.graphics FAQ:
  418.  
  419.      "There are many ways to do this.  Some approaches map the
  420.      viewing rectangle onto the scene, by shooting rays through
  421.      each pixel center and assigning color according to the object
  422.      hit by the ray.  Other approaches map the scene onto the
  423.      viewing rectangle, by drawing each object into the region,
  424.      keeping track of which object is in front of which.
  425.  
  426.      The mapping mentioned above is also referred to as a
  427.      'projection', and the two most popular projections are
  428.      perspective projection and parallel projection.  For example,
  429.      to do a parallel projection of a scene onto a viewing
  430.      rectangle, you can just discard the Z coordinate, and 'clip'
  431.      the objects to the viewing rectangle (discard portions that
  432.      lie outside the region).  To do a perspective projection,
  433.      dividing each the x and the y by some multiple or the Z-depth
  434.      is the usual approach.
  435.  
  436.      For details on 3D rendering, the Foley, van Dam, Feiner and
  437.      Hughes book, reading.  Chapter 6 is 'Viewing in 3D', and
  438.      chapter 15 is 'Visible-Surface Determination'.  For more
  439.      information go to chapter 16 for shading, chapter 19 for
  440.      clipping, and branch out from there."
  441.  
  442. 8) Vector Math - Dot Product and Cross-Product.
  443.  
  444.      Adding and subtracting vectors is as easy as subtracting their
  445. respective parts:
  446.  
  447.         <A,B,C> + <D,E,F> = <A+D, B+E, C+F>
  448.         <A,B,C> - <D,E,F> = <A-D, B-E, C-F>
  449.  
  450.      Scaling vectors is as simple as multiplying each part by a
  451. constant:
  452.  
  453.         S * <A,B,C> = <S*A, S*B, S*C>
  454.  
  455.      The Dot-Product of two vectors is simply the sum of the products of
  456. their respective parts:
  457.  
  458.         <A,B,C> . <D,E,F> = A*D + B*E + C*F
  459.  
  460. Note that this value is not a vector.
  461.  
  462.      The Cross-Product of two vectors is a bit more complex (it is the
  463. determinant of the matrix with the direction vector as the first row,
  464. the first vector as the second row, and the second vector as the third
  465. row):
  466.  
  467.         <A,B,C> X <D,E,F> = <B*F - C*E, C*D - A*F, A*E - B*D>
  468.  
  469. Note that:
  470.  
  471. <A,B,C> X <D,E,F> = -1 * ( <D,E,F> X <A,B,C> )
  472.         -and-
  473. (<A,B,C> X <D,E,F>) . <A,B,C> = (<A,B,C> X <D,E,F>) . <D,E,F> = 0
  474.  
  475.      More later.
  476.  
  477. 9) Matrix Math
  478.  
  479.      The identity matrix is a square matrix (same number of rows as
  480. columns) with all elements {i,j} given by:
  481.  
  482.                   { 1.0   if i == j
  483.         m[i][j] = {
  484.                   { 0.0   otherwise
  485.  
  486.      Multiplication of matrices:
  487.  
  488.     if X is a matrix that is m rows and n columns (an m-by-n (or mxn) matrix)
  489.     and Y is a matrix that is n rows and r columns (nxr), then the product
  490.     X * Y ==> m[i][j] = sum{ a=0, a<n, X[i][a] * Y[a][j] };
  491.  
  492. As you can see in this example, the result is a matrix with m rows and r
  493. columns (an mxr) matrix.  The most usual case in basic 3-d graphics is
  494. multiplication of 3x3 or 4x4 matrices to each other.
  495.  
  496.      Some important things to remember about matrix multiplication: (The
  497. following assume X and Y and Z are matrices and I is an identity matrix)
  498.  
  499.     X * Y rarely equals Y * X.  but,
  500.     X * ( Y * Z )  equals ( X * Y ) * Z
  501.     X * I = I * X = X
  502.     if (X * Y = I) then (Y * X = I)
  503.  
  504.      Multiplication of a Matrix and a Vector is simply a special case of
  505. multiplying two matrixes.  It just so happens that a vector is a matrix
  506. with only one column.  So, in order to multiply an mxn matrix by a
  507. vector, you have to have an nx1 matrix ("an n-vector" or "a vector in
  508. n").  The result is a vector in m.  As a quick example:
  509.  
  510.     [ a b ]   [ g ]   [ a*g + b*h ]
  511.     [ c d ] x [ h ] = [ c*g + d*h ]
  512.     [ e f ]           [ e*g + f*h ]
  513.  
  514. 10) Collisions.
  515.  
  516.      Sorry... This is a FAQ in-progress.  Will do more later.  Please
  517. feel free to send me a paragraph for this section.
  518.  
  519. 11) Perspective.
  520.  
  521. (Message nova:2746)
  522. From: Raul Deluth Miller <rockwell@nova.umd.edu>
  523.  
  524.      Perspective is easy: realize that the viewpoint isn't on the
  525. surface of the screen but is some distance back.  Then,
  526.  
  527.      [a] convert to a relative coordinate system centered around the
  528. viewpoint, oriented so that x and y are like this:
  529.                  y
  530.                  |
  531.  
  532.              ----+----x
  533.                  |
  534.  
  535. and z is the distance into the screen.  Now, divide your coordinates by
  536. z.
  537.  
  538.      That's all.
  539.  
  540.      Ok, sure, you don't really have to call your directions x y and z,
  541. but that's just changing the description which fits the math.  And,
  542. sure, you have to decide what to do about things that are "the other
  543. direction from the screen" -- but that's really something different.
  544.  
  545.      And, ok, you have to decide how many game units the viewpoint is,
  546. behind the screen [this is something you add to the z coordinate before
  547. dividing].  And, ok, maybe you want to scale things a bit to make it
  548. look nicer.  But none of that is really all that hard to deal with.
  549.  
  550.      What's annoying is that you don't want to do division for every
  551. pixel that you draw on the screen.  That means, for instance, that you
  552. might have a line where both ends are off the screen but part of the
  553. line [in the middle] are visible.  However, that's related to the
  554. problem of detecting collisions.  Or, better yet, clipping.  Yeah,
  555. that's it take a look at the section on clipping...
  556. Raul D. Miller             n =: p*q               NB. prime p, q, e
  557. <rockwell@nova.umd.edu>                           NB. public e, n, y
  558.                            y =: n&|&(*&x)^:e 1
  559.                            x -: n&|&(*&y)^:d 1    NB. 1 < (d*e) +.&<: (p,q)
  560.  
  561. 12) Z-Buffering & the Painters Algorithm & BSP-Trees.
  562.  
  563. There are several methods available for displaying polygons in a 3-d
  564. object so as to assure that what's behind is behind and what's in front
  565. is in front.  Each, however, has its pros and cons.  With each of these
  566. methods, it is often useful to implement backface culling.  Backface
  567. culling is simply not rendering surfaces which aren't facing you.
  568.  
  569.      The Painter's Algorithm is probably the most intuitive for the
  570. beginner, one of the easiest to implement, and the hardest to get right.
  571. The Painter's Algorithm, quite simply, is Paint the from back to front.
  572. Once it has been determined which polygons will be drawn, it is
  573. necessary to sort them from furthest away to closest.  Then, starting
  574. with the furthest polygon and moving to the closest, draw them.
  575.  
  576.      The tricky part of the Painter's Algorithm is determining when one
  577. polygon is closer or farther than another.  The closest to satisfactory
  578. method I've found uses this criteria -- Surface A is further away then
  579. surface B if:
  580.         1) The furthest point of A is further away than the furthest
  581.             point of B.
  582.  
  583.         2) B faces you more directly than A.
  584.  
  585.         3) The closest point of A is further than the closest point of B.
  586.         4) Surface B is more "important" than surface A.
  587. These are to be taken in order until a decision is reached.  But, I've
  588. yet to find good enough criteria to work well on most objects that
  589. people design.  If you keep these criteria in mind when making the
  590. objects, it can help.  But, if you're using 3rd party objects, I'd
  591. suggest a different method.
  592.  
  593.      Z-Buffering is a buzzword that's finally come down to reality.
  594. It's been replaced by 'texture-mapping' and 'bump-mapping' and 'realtime
  595. raytracing' as the 'what's fancy' buzzword.  Z-buffering is costly in
  596. terms of memory and processing time, but gives beautiful results.  If
  597. you've got some freedom with your memory usage and a bit of processor
  598. time to spare, and you're ok with filling your own polygons, then Z-
  599. buffering may be for you.
  600.  
  601.      To Z-buffer, one keeps a 2d-array of numbers (shorts or ints
  602. usually) the same dimensions as the viewport.  As each <X,Y,Z> point is
  603. prepared for display, the final value is compared to the Z value already
  604. in the <X,Y> position in the Z-buffer array.  If the new Z is less than
  605. the one already in the buffer, the pixel-color is placed in the Screen-
  606. Buffer at position <X,Y> and the new Z is copied into position <X,Y> of
  607. the Z-Buffer.
  608.  
  609.      The expense of Z-Buffering is having to set each element to the
  610. MAX Z VALUE after each frame and keeping track of the Z-value for every
  611.    - -
  612. pixel in the Screen Buffer and every pixel in the polygon you're
  613. drawing.  In most applications, it is unnecessary to keep track of the
  614. Z-values of any more than the vertices of a polygon.
  615.  
  616.      And, my favorite of the bunch (but the nastiest to store in an
  617. object file, is BSP-trees.  BSP-tree stands for Binary Space Partition
  618. tree.  They are based the idea that surfaces of most objects don't
  619. change positions relative to each other.  Objects whose surfaces change
  620. relative positions cannot be (to my knowledge) easily used with BSP-
  621. trees.
  622.  
  623.      The first step in using BSP-trees is to break up your object into a
  624. 'good' object.  But, I can't think of a way to describe a 'good' object
  625. without just telling you how to make one.  So, here's a general
  626. algorithm for making a BSP-tree object from ye average object:
  627.     1) Pick a surface to call the root node.
  628.     2) Compare every other surface in the set of surfaces to the
  629.         root node.
  630.     3) If a surface is In-Front-Of the root node, then put it in
  631.         the 'Front Heap'.
  632.        If a surface is Behind the root node, then put it in the
  633.         'Back Heap'.
  634.        If neither of the above is true, chop up the surface into
  635.         smaller surfaces that are all either In-Front-Of or Behind
  636.         the root node.  (This is the tricky bit).
  637.     4) Repeat these steps with the 'Front Heap' and the 'Back Heap'.
  638. As an interesting note, I can see no advantage at all to trying to keep
  639. a relatively balanced tree.
  640.  
  641.      Now comes the interesting bit.  Now that the object is a 'good'
  642. BSP-tree object, it is time for the drawing algorithm.  This is fairly
  643. straight- forward.
  644.     1) Compare the root node with you.
  645.     2) If you are In-Front-Of the root node,
  646.         draw 'Root->Back', then the Root surface, then 'Root->Front'.
  647.        If you are Behind the root node,
  648.  
  649.         draw 'Root->Front', then the Root surface (unless you're
  650.  
  651.         backface culling), then 'Root->Back'.
  652.  
  653.      I fully admit that I didn't believe BSP-trees would work when I
  654. first read about them in Foley-van Dam, nor did I believe they would
  655. work after seeing them work for me.  Now, three months later, I fully
  656. believe they work, and I can even say I understand why.  I may soon
  657. attempt an explanation here, but suffice it for now to say, 'they can be
  658. grokked'.
  659.  
  660. 13) Shading.
  661.  
  662.      Sorry... This is a FAQ in-progress.  Will do more later.  Please
  663. feel free to send me a paragraph for this section.
  664.  
  665. 14) 3-space clipping.
  666.  
  667.      Sorry... This is a FAQ in-progress.  Will do more later.  Please
  668. feel free to send me a paragraph for this section.
  669.  
  670. 15) 3-d scanning.
  671.  
  672. Three dimensional scanning is a verifiable pain.  I've only really heard
  673. of three basic techniques.  Two of them require the scanned item to be
  674. entirely still, and one of them even destroys the object being scanned.
  675.  
  676.      The first technique I ever saw was in 'The Making of T-2'.  An
  677. actor was dressed in tight, dark clothing and a mesh of masking tape was
  678. placed over his body.  This mesh was filmed simultaneously from several
  679. different camera positions as the actor walked.  The films were then
  680. digitally processed to provide a close model of a person walking.  The
  681. amount of work and expense involved in creating the images, registration
  682. of the multiple images, and conversion into 3-space data makes this a
  683. big time investment.
  684.  
  685.      The second technique I saw set the item to be scanned on a
  686. turntable.  A laser sensing system or simple armature-stylus were used
  687. to obtain a bump-map along a vertical slice of the item.  Then, the item
  688. was rotated 5 degrees and the process repeated.  The gives a very
  689. detailed cylindrical bump-map of an item.
  690.  
  691.      The third technique is by far the most interesting I've seen.  But,
  692. it is useful mostly only for height-field generation.  This method
  693. employs a CAT-scan like approach.  First, the object is painted solid
  694. black (or white).  Then, the item is dipped in milk (or chocolate syrup)
  695. to a certain depth.  A still photo is taken.  Then, the item is dipped
  696. further into the liquid.  Another still is taken.  This is done to
  697. obtain slice view of the item.  The photos are then digitally scanned to
  698. locate the boundaries of the items.
  699.  
  700. 16) Publically available source-code.
  701.  
  702.      Well, I've started a collection at ftp.csh.rit.edu::/pub/3dfaq/src.
  703. Feel free to upload relevant stuff (that I can't find on archie in under
  704. twenty minutes).  Some other sites of interest:
  705.     3d images;
  706.         ftp://wuarchive.wustl.edu/graphics/ray
  707.         ftp://princeton.edu/pub/Graphics
  708.  
  709.     3d Information:
  710.  
  711.         http://www.mindspring.com/~cwatkins/algor.html
  712.  
  713.         http://archpropplan.auckland.ac.nz/People/Paul/Paul.html
  714.         ftp://x2ftp.oulu.fi/pub/msdos/programming/docs/zed3d023.zip
  715.         http://www.csh.rit.edu/~pat/misc/3dFaq.html
  716.  
  717.     3d geometry files:
  718.         http://archpropplan.auckland.ac.nz/People/Paul/Paul.html
  719.         ftp://ftp.kgc.com/pub/mirror/avalon
  720.  
  721.     ray tracers:
  722.         ftp://alfred.ccs.carleton.ca/pub/pov-ray
  723.         http://www.mindspring.com/~cwatkins/algor.html
  724.  
  725.     stereograms:
  726.         ftp://ftp.comlab.ox.ac.uk/pub/Documents/3d
  727.         http://enigma.phys.utk.edu/stereo/index.html
  728.         ftp://sugrfx.acs.syr.edu/3d/stereograms
  729.  
  730.      Sorry... This is a FAQ in-progress.  Will do more later.  Please
  731. feel free to send me a paragraph for this section.
  732.  
  733. 17) Books on the topics.
  734.  
  735. Computer Graphics: Principles and Practice Foley, van Dam, Feiner, and
  736.      Hughes; Addison Wesley -- Reading, Massachusetts; (c) 1990.  ISBN
  737.      0-201-12110-7.
  738.  
  739.      I highly reccomend this book for the person seriously interested in
  740.      understanding Computer Graphics concepts for 2-D image-generation
  741.      and 3-D representation.  As a warning though, if you're struggling
  742.      to follow vector math and such, you might not spend the $60-$80
  743.      bucks on this one yet.
  744.  
  745. Computer Graphics Handbook: Geometry and Mathematics, Michael E.
  746.      Mortenson.  ISBN 0-8311-1002-3
  747.  
  748.      I've never seen this one, but it comes net-recommended.  Anyone
  749.      care to make a more complete statement?
  750.  
  751. Programming in 3 Dimensions Christopher D. Watkins and Larry Sharp;
  752.      Barnes & Noble.  ISBN: 1-55851-220-9 $39.95
  753.  
  754.      I've never seen this book.  I've got an ad for it in front of me.
  755.      I would guess it's a very low-density version of some of the 3-D
  756.      things from Foley.  The book boasts sample source code on MS/PC-DOS
  757.      floppy included.  "This one is for all graphics enthusiasts who
  758.      want a detailed look at 3-D graphics and modeling.  Also features
  759.      discussions of popular ray tracinge methods and computer
  760.      animation." [sic]
  761.  
  762.      From: MarsSaxMan@aol.com
  763.  
  764.      You mentioned Watkins & Sharp's book "Programming in 3
  765.      Dimensions" in your FAQ... I have this book, so I thought I'd
  766.      give you a capsule review.
  767.  
  768.      I like the book overall. It is cleanly written & they give a
  769.      pretty good explanation of the mathematics (of course, having
  770.      spent eons in advanced math has probably bent my perspective
  771.      on what's clear in mathematics). However it doesn't get too
  772.      bogged down in theory, which is nice. There are also a bunch
  773.      of interesting side issues that get covered, such as fractals,
  774.  
  775.      color cycling, color tables, etc. Complete source code to a
  776.  
  777.      ray tracer, an animation interface to the ray tracer, and some
  778.      interesting display hacks are included.
  779.       Overall a very practical way to get into 3-D graphics; it's
  780.      pretty easy to see how the code could be modified for this or
  781.      that purpose. It'll take some work to turn its raytracer into
  782.      a Doom engine or whatever but it could be done & would still
  783.      be worth it.
  784.  
  785.      Only thing I didn't really like (though this is probably a
  786.      natural consequence of the down-to-earth real-world nature of
  787.      the book) is that it is a bit too DOS PC specific. I hack
  788.      Macintosh so a lot of the graphics code is unusable and some
  789.      of the memory things have to be changed; one chapter on VGA
  790.      graphics is wasted on me. But overall I think the book is a
  791.      good buy. Also it's $39.95, so it's not a bad buy compared to
  792.      some other 3-D books I've seen (gacckkk!)
  793.  
  794.      Just thought you might like to know, and maybe have a bit more
  795.      filler to stash in the FAQ...
  796.  
  797.      -MarsSaxMan Red Planet Software
  798.  
  799. And, if you liked that... Christopher Watkins sent me a more complete
  800.      book list (most of which follows).  Feel free to send me any
  801.      personal reviews of any of these books.  Like or dislike.
  802.  
  803. Stereogram Programming Techniques.  Christopher D. Watkins and Vincent
  804.      P. Mallette (Charles River Media, Inc.), 1995 ISBN: 1-886801-00-2
  805.      $34.95 Learning Windows(tm) Programming Using Virtual Reality.
  806.      Christopher D. Watkins and Russ Berube (Academic Press
  807.      Professional, Inc.), 1994 ISBN: 0-12-737842-1
  808.  
  809.      learning Microsoft Windows(tm) programming by developing a
  810.      texturing 3-D game engine and application similar to Wolfenstein
  811.      3-D(tm) and the popular game DOOM(tm)
  812.  
  813. Virtual Reality ExCursions with Programs in C.  Christopher D. Watkins
  814.      and Stephen R. Marenka (Academic Press Professional, Inc.), 1994
  815.      ISBN: 0-12-737865-0 $39.95
  816.  
  817.      produce polygonal 3-D virtual worlds on your PC, understand human
  818.      perception issues, near complete list of VR information and
  819.      technology sources, includes all source code, includes anaglyph 3-D
  820.      glasses
  821.  
  822. Photorealism and Ray Tracing in C Christopher D. Watkins and Stephen B.
  823.      Coy (M&T Books, Inc.), 1992 ISBN: 1-55851-247-0 $44.95
  824.  
  825.      generate photorealistic ray-traced computer graphics, includes all
  826.      source code for a photorealistic renderer and assorted fractal (and
  827.      other) database generators, includes many 3-D models
  828.  
  829. Exploring Photorealism and Ray Tracing Christopher D. Watkins, Vincent
  830.      Mallette, Stephen R. Marenka and Robert Johnson (M&T Books, Inc.),
  831.      1995 ISBN: 1-55851-383-3 $29.95
  832.  
  833.      source code for a beginner's ray tracer, the definitive beginner's
  834.      book on ray tracing, faster BOB/VIVID executable than in the
  835.      original, Photorealism and Ray Tracing in C book with even more
  836.      texture mapping and texturing capabilities, a CD ROMs worth of 3-D
  837.      models, worlds and tools, various 3-D modeling tools (blobs,
  838.      polygonal, etc.), learn how to raytrace the beautiful quaternion
  839.  
  840.      Julia set fractals (Quaternion -> 4-dimensional object)
  841.  
  842. Advanced Graphics Programming in C and C++ Roger Stevens and Christopher
  843.      D. Watkins (M&T Books, Inc.), 1991 ISBN: 1-55851-171-7 $39.95
  844.  
  845.      beginners book to computer graphics, includes a simple ray tracer,
  846.      polygon renderer, and height-field renderer, and fractals, includes
  847.      all source code, PASCAL version of this book also available, 1990
  848.  
  849. 18) Other forums.
  850.  
  851.      Sorry... This is a FAQ in-progress.  Will do more later.  Please
  852. feel free to send me a paragraph for this section.
  853.  
  854. 19) Current Contents of Archive ftp.csh.rit.edu::/pub/3dfaq
  855.  
  856.    2 -rw-r--r--    1 pat      member    219 Apr  2 20:40 README
  857.   16 -rw-r--r--    1 pat      member   7787 Mar 28 19:11 DoomTechniques.gz
  858.   10 -rw-r--r--    1 pat      member   4243 May 23 12:34 bsp.gz
  859.   14 -rw-r--r--    1 pat      vr       6266 Apr  2 20:38 imath.gz
  860.  
  861.   22 -rw-r--r--    1 pat      vr      11262 Apr  2 20:43 imath.tar.gz
  862.  
  863. -- 
  864.      "Milk and cookies kept you awake?"
  865.  
  866.