#ifndef INCLUDED_RENDER_H#define INCLUDED_RENDER_H/*9%%% public interfaces for 3d graphics renderer. %%%	Graph~3D is a library of routines to allow C programmers to do relativelysimple, fast three dimensional graphics.  The user interface is differentfrom that of some other libraries in that it has very few functions.  Themajority of the work that a user does when working with Graph~3D is insetting up data structures in memory for the library to read.In keeping with this data centered design, I will describe the data structures used by the library first.\section{Fundamental Data Types}All objects displayed by the library are described using a few basicdata types representing fundamental geometric constructs and properties.\subsection{Colors}*/#include "game.h"/*9The \textc{PIX\_RGB32} structure describes the color of a surface, aswell as some of its other properties.  The \textc{red}, \textc{green},and \textc{blue} members specify the color.  Each color componentcan range from $0$ to $255$.  The \textc{alpha} member specifies thetransparency of the surface, as well as some other properties.It is divided into several bit fields:\begin{description}\item[bits $0$--$3$:] The transparency of the surface.  $0$ is completely	opaque, and $15$ is $15/16$ transparent.\item[bit $4$:] Self-Luminous.  If this bit is set, the color specified is	the color of the surface, as if it generates its own light.  If not, the  color is modified by the lighting model as if the surface is being  illuminated from outside.\item[bits $5$--$7$:] Unused.  These might be meaningful in later  implementations.\end{description}Bits inside the \textc{alpha} member are numbered so the lowest bit isleast significant.  For instance, the transparency bits can be found bymasking with \textc{0x0F}.The \textc{PIX\_RGB32} structure's layout is inherited from the game i/o library.In order to make optimal use of the computer's hardware, this structure can have it'sbytes packed in arbitrary order (selected at compile time to match the layout ofthe target machine's favorite frame buffer format).  Remember to use the macros providedby the game library for initializing color values to avoid portability problems.\subsection{Vectors}*/typedef struct tagvector {    float x,y,z;} PG_VECTOR;/*9A \textc{PG\_VECTOR} represents a location or distance in 3 dimensional space by specifying \textc{x}, \textc{y}, and \textc{z} coordinates.Vectors are used to specify points, and sometimes to specify direction.Vectors which represent direction only will be normalized such that$\sqrt{x^2 + y^2 + z^2}=1$.Because perspective geometry calculations always involve the ratio of twodistance vectors, the units used for vectors in 3~dimensional space arearbitrary, and can be chosen by the user as convenient.  The library doesnot care whether vectors are specified in inches, or centimeters, or milesas long as a consistent unit is used for all vectors.\subsection{2D Points}*/typedef struct tagpoint2d {    int x,y;} PG_POINT2D;/*9A \textc{PG\_POINT2D} structure represents a point on the image plane's2 dimensional surface.  The center of the displayed image is at $(0,0)$with increasing \textc{y} being farther towards the top, and increasing\textc{x} being farther to the right.  A user of this library will usuallynot have to work with \textc{PG\_POINT2D} structures, since almost everythingis specified by its 3 dimensional position.In cases where 2~dimensional distances are used explicitly, such as insetting up the image size of a camera, distance is measured in pixels.Normally these pixels are identical with the screen pixels of the computer'sdisplay, but on some machines there may be some differences.  In particular,the library assumes that pixels are exactly square.  If the library's I/Oroutines are ported to some environment where display pixels are far fromsquare, the I/O routines should compensate so that \textc{PG\_POINT2D}coordinates will continue to act square.\subsection{Planes}*/typedef struct tagplane {    float x,y,z,n;} PG_PLANE;/*9A plane is specified by four numbers in the \textc{PG\_PLANE} structure,\textc{x}, \textc{y}, \textc{z}, and \textc{n}.  The plane is the set ofpoints $\vec P$ such that $P_x \cdot x + P_y \cdot y + P_z \cdot z = n$.A user usually doesn't need to specify planes directly.\subsection{Bases}*/typedef struct tagbasis {    PG_VECTOR x;    PG_VECTOR y;    PG_VECTOR z;} PG_BASIS;/*9A basis, as specified by the \textc{PG\_BASIS} structure, is a local coordinate system for some object.  This coordinate system is specifiedrelative to some enclosing coordinate system.  For cameras and highestlevel objects, the enclosing coordinate system is the world's euclideancoordinates.  For subobjects, the enclosing coordinate system is thatof the parent object (see below for a description of objects, subobjects,and cameras).  The components of the basis are three vectors \textc{x},\textc{y}, and \textc{z} which specify the distance and direction movedthrough the enclosing coordinates when a component of a local coordinatechanges by $1$.  Because every object and camera has its own coordinatesystem, the user is free to interpret the world coordinate system in whatever way is convenient.  For example, the global $z$ coordinatecan be thought of as ``up'' or ``down'' or ``forward'' depending on the waycamera coordinates are positioned.  Camera coordinates are assumed to beleft-handed (meaning that $z$ points away from the viewer if $y$ is up and $x$ is right) but this does not mean that the world coordinate systemmust be left-handed, since the camera basis can have a negative signin the $z$ vector to effectively mirror the coordinate system.  Thissort of manipulation also allows special effects, such as making onecamera view a mirror image world.  One restriction is that the basis of acamera or object must be orthonormal;that is each vector in the basis must be perpendicular to the others, andeach must have length $1$.\subsection{Cameras}\label{cameras}*/typedef struct tagcamera {  float detail;  PG_VECTOR center;  PG_BASIS basis;  float zoom;  //long vh;	BITMAP *bmap;	float *zbuf;} PG_CAMERA;/*9The \textc{PG\_CAMERA} structure describes a viewpoint from which the3~dimensional scene is projected into a 2~dimensional image.  The cameraalso includes information about where in memory the image should be rendered.Multiple camera structures can be used to display multiple views of thescene, either in separate bitmaps, or at different times in the same bitmap.The \textc{detail} member of the camera structure allows adjustment ofhow complicated the rendering done for this camera will be.Every object has a detail value which is scaled by the distance to theobject and compared with the camera detail.  If the scaled object detailis larger than the camera detail, the object will not be drawn.  Changingthe camera's detail level changes how far away objects can be and still bevisible.  Doubling the camera's detail doubles the range at which theobject is visible.  If the camera's detail level is set to $1$ and anobject's detail level is set to $\frac{1}{x}$ where $x$ is the object'ssize in the longest dimension, then the object will be visible when itis close enough to appear at least one pixel long.The \textc{center} and \textc{basis} members specify the position anddirection of the camera in the world coordinate system.  The centeris the position of the viewer's eye.  The z vector of the basisis the direction the viewer is looking, the x vector points to theviewer's right, and the y vector points up in the viewer's reference frame.The \textc{zoom} member specifies how far the projection plane for theimage is from the view point in pixels.  For accurate perspective,this should be the distance between the viewer and the displayscreen in pixels, but for many purposes it is better to give a largerfield of view and more emphasized depth by using a smaller zoom factor.Increasing the zoom is an easy way to magnify the displayed image.The \textc{bmap} member is a bitmap from the game library.  This bitmap isthe where the image will be rendered.  The width and height of the2~dimensional image are set by the cropping rectangle of the bitmap.The perspective center of the rendering is always the geometric center of thecropping area.The \textc{zbuf} member should point to an array of \textc{float} values aslarge as the number of pixels in the bitmap.  Even if the bitmap has it'scropping values set to select a small subrectangle, the z buffer must be as large as the full bitmap, rather than the cropping region.  This array will be used as a z-buffer for doing hidden surface elimination.  Multiple cameras canshare the same z-buffer, as long as all rendering for one camera is completedbefore any rendering for the next camera is started.  Just as the game librarydoes not automatically clear the active bitmap, the Graph~3D library does notautomatically clear the z-buffer. Before rendering a scene, the z-buffer shouldbe cleared to $0$ (which represents an infinite distance from the camera) orset to some other reasonable values.  The z-buffer actually holds $\frac{1}{z}$values, as described in section \ref{zbuf}.\section{Objects}Every visible object in the scene being rendered is represented by a\textc{PG\_OBJECT} structure.  This does not include cameras and thebackground.  Each object has its own local coordinate system, informationfor controlling rendering detail, and geometry and color informationfor all the polygon surfaces of the object.  In addition, objects canhave subobjects attached to them.  A subobject is an object which usesthe parent object's coordinate system to express its position and basis.This arrangement causes the subobject to move and rotate as part of theparent object when the parent's coordinates are changed.  At the same time,the subobject has its own local coordinate system which allows it to be movedrelative to the parent object.  This scheme provides a powerful method forcreating object which have attached moving parts.All of the information required to describe an object is not stored directlyin the object structure.  Objects are composed of several data structures:objects, parts, windows, and polygons.  The relationship between the variousparts is shown in figure \ref{objpic}.\begin{figure}\begin{picture}(330,175)%135                               +---Windows%120              +---Parts--------+%105 Object-------+                +---Colors%90               +---WinObjects   |%75               |                +---Norms%60               +---Subobjects   |%45                                +---Polygons -----------+%30                                |                       |%15                                +----------------------Points%%%   00              100              200                300\def\myline(#1,#2){\put(#1,#2){\line(1,0){20}}}\def\myvect(#1,#2){\put(#1,#2){\vector(1,0){20}}}\def\mybar(#1,#2)#3{\put(#1,#2){\oval(20,#3)[l]}}\def\myarc(#1,#2){\put(#1,#2){\oval(20,20)[bl]}}             \put(0,102){Object}%-------------------------------------------------------------%             \myline(40,105)             \mybar(70,90){60}                         \myarc(70,100)\myvect(70,60)           \myvect(70,90)           \myvect(70,120)\put(95,57){Subobjects}  \put(95,87){Winobjects}  \put(100,117){Parts}%-------------------------------------------------------------%						 \myline(140,120)                 \mybar(170,75){120}\myarc(170,55)  \myarc(170,85)  \myarc(170,115)\myvect(170,45) \myvect(170,75) \myvect(170,105) \myvect(170,135)\put(200,42){Polygons}          \put(200,102){Colors}						    \put(200,72){Norms}        \put(200,132){Windows}%-------------------------------------------------------------%    \put(170,15){\vector(1,0){120}}    \put(250,45){\line(1,0){50}}    \put(310,35){\vector(0,-1){10}}    \put(300,35){\oval(20,20)[rt]}    \put(300,12){Points}\end{picture}\caption{The Structure of Objects \label{objpic}}\end{figure}\subsection{Objects}*/typedef struct tagpart PG_OBJECTPART;typedef struct tagobject PG_OBJECT;struct tagobject {    float detail;    float size;    PG_VECTOR center;    PG_BASIS basis;    int nparts;    PG_OBJECTPART *parts;		int nwindows;		PG_OBJECT **winobjects;		int nobjects;		PG_OBJECT **objects;		int mark;};/*9The \textc{PG\_OBJECT} structure holds information about the position ofan object, and its relationship to other objects.  Detailed informationabout the color and shape of the object is not kept in the object structureitself, but in the array of \textc{PG\_OBJECTPART} structures pointed toby the \textc{parts} member.  This separation makes creating several objectswith the same shape and color easy, and also saves the memory that would berequired to separately represent each identical object.  The multiple objectsneed only have separate \textc{PG\_OBJECT} structures, each of which containsa pointer to the same array of parts.  They will then have the same shape butbe individually movable.The \textc{detail} member is used to determine when distant objects canbe ignored because they are too small to be important to look at.  Thisnumber interacts with each camera's detail setting as described in Section \ref{cameras}.  In general, larger numbers for detail cause theobject to be treated as less important.  A value of $\frac{1}{x}$ where$x$ is the length of the object causes it to be visible whenever it wouldbe at least a pixel long in the image (although adjusting the camera's detailsetting can affect what is displayed).  Setting the detail to $0$ forcesthe object to always be drawn.The \textc{size} member is the radius of a sphere which completelycontains the object.  This value is used for quick visibility determinationby the rendering routines.  Making the size value too large will not causerendering problems, but may cause the library to run more slowly.  Making thesize too small may cause the object not to be displayed even though partsof it should actually be visible.Every object has a basis and center point which describe the position andorientation of the object.  The basis must be orthonormal in order forthe hidden surface and lighting model routines to work correctly.  Thismeans that the basis can be used to rotate or reflect the object, but notto change it's size or do shear distortions.Information about the shape and color of an object is contained in an arrayof zero or more \textc{PG\_OBJECTPART} structures.  each part is a completedescription of the shape of the object at a given level of detail.  Therendering routines will find the first part in the list which has at leastthe amount of detail (as specified by the part's detail number) the librarywants to render the object at, or the last part in the array if none of theparts have a high enough detail value.  Only the one part which is selectedwill be drawn.  By providing several parts in the array, in order ofincreasing detail,  the user can create objects which are drawn using morepolygons when they are closer.  Careful use of this technique can significantlyreduce the amount of work the library needs to do in order to draw a scenewith a given degree of realism.The \textc{objects} member of the object structure points to an array ofsubobects.  These subobjects are just like other objects, except thateach one's center and basis is specified in the current object's localcoordinates.  This is useful for adding details to a scene.  For example,a building could be an object, which contains several rooms which are itssubobjects.  Each room could contain pieces of furniture which are subobjectsof the room.  Causing an object to be its own subobject will result in aninfinite recursion which might crash the library.  Two different objects canshare an array of subobjects, which will result in both objects having thesame number and shape of subobjects, in the same relative places. The \textc{winobjects} member of the part structure provides the user a way ofspecifying potentially visible objects in cases where there are many objects,most of which are usually not visible because of occlusion, such as in anindoor environment where there are many rooms most of which are not visiblefrom inside the others.  This technique is described in detail in Section\ref{wins}.  If windows are not being used, the \textc{nwindows} member canbe set to $0$, and \textc{winobjects} can be \textc{NULL}.The \textc{mark} element is used by the library internally to prevent it fromdrawing the same object more than once when following window chains.  Thisfield must be set to $0$ when the object is created.\subsection{Object Parts}*/typedef struct tagpolygon PG_POLYGON;struct tagpart {  float detail;  int npolys;  PG_POLYGON *polys;  /* array of polygons */  PG_VECTOR *norms;	/*  Norms for polys */  PIX_RGB32 *colors;   /* one color for each polygon */	int npoints;  PG_VECTOR *points;  /* the points which compose the polygons */  PG_POLYGON *windows;  PG_VECTOR *wnorms;	/*  Norms for windows */};/*9The object structure described above specifies the location and size of anobject, but says nothing about its shape.  An object's shape is defined bya set of polygons, which are organized using a \textc{PG\_OBJECTPART}structure.The part structure's \textc{detail} member is used to select which of thepart structures in an object structure will be used to display the object.In gneral the detail value for each part should be set to roughly$\frac{1}{x}$ where $x$ is the length of one of the smallest polygons in thepart's polygon list, although the exact detail values often need to be chosenby trial an error to get the best looking output.The part structure also describes polygons, points, and windows.The \textc{polys}, \textc{norms}, and \textc{colors} members of the partstructure are all arrays of size \textc{npolys}, one element for eachpolygon to be drawn.  The colors array specifies the color of each polygon(along with its transparency and possibly other color effects) while thenorms array contains a unit vector with direction perpendicular to thepolygon.  The norm vector for each polygon must point towards the outsideof the object; the library will treat any polygon which has a normpointing away from the view point as invisible.  This means that polygonswhich represent two dimensional surfaces which can be seen from either sidemust actually be implemented as two identical polygons with norm vectorspointing in opposite directions.The \textc{points} array specifies the position of each vertex of the object.The polys array references each point in each polygon by indexing into thepoints array.  This is done instead of including the point positions in thepolygons directly for two reasons.  First, most points are actually sharedby several polygons.  For example, each point in a cube is part of threedifferent faces.  Keeping the points separate from the polygons reduces thenumber of times each point needs to be specified and transformed.Secondly, when animating an object it is often true that the positions of thepoints change but the relationships between the polygons don't.  If the point array is separated from the polygon array, many sorts of animationcan be achieved by changing the point values and the norm values whileleaving the polys array alone.The \textc{windows} and \textc{wnorms} members of the part structure provide the user a way of specifying potentially visible objects in cases where there are many objects, most of which are usually not visible becauseof occlusion, such as in an indoor environment where there are many rooms most of which are not visible from inside the others.  This technique is described in detail in Section \ref{wins}.  If windows are not being used, \textc{windows} and \textc{wnorms} canbe set to \textc{NULL}. The number of windows in all parts of an objectmust be the same.  If windows are needed for some parts but not others,provide the maximim number of windows needed for all parts, and set someto have $0$ points.\subsection{Polygons}*/struct tagpolygon {    int n;    int *points;    /* array of indexes to points */};/*9The array of \textc{PG\_POLYGON} structures specify the vertices of eachpolygon in the object.  Each polygon structure specifies the \textc{n} vertices of a polygon by listing the index of each vertex in the partstructure's point list.  The \textc{points} member of the polygon structurepoints to an array of index numbers, one for each vertex of the polygon.The library allows vertices to be listed in either clockwise orcounterclockwise order, and allows any number of vertices per polygon,but requires that each polygon be convex and flat.  These conditions arealways true for triangles, byt if polygons with four or more points areused the user is responsible for making sure that these requirements are met.\subsection{Windows}\label{wins} a window is a way of optimizing rendering in cases where objects aremostly closed but have a few holes.  If a hole is covered by a window,the renderer knows that the only thing visible through the hole isthe object in the winobject (and possibly anything in it's winobjects.)this is particularly useful in the case where each object is a room inan indoor environment, since the renderer doesn't have to render all rooms,only those which are visible through a series of visible windows.Each window has two parts: a polygon in the windows array of thepart structure which describes the shape of the window, and an object pointerin the winobjects array of the main object structure which tells what isvisible through the window.  All windows arrays of all parts of the object,as well as the winobjects array must have exactly the number of elementsspecified in the nwindows element of the object structure.  A window can bedisabled for a partucular part by setting the \textc{n} value of that window's\textc{PG\_POLYGON} to $0$, or the window can be disabled for the entireobject by setting the object pointer in the winobjects array to \textc{NULL}.The library will never try to draw an object more than once while doingwindows.  The mark field of the object structure is used to keep track ofwhich objects have been drawn.  This means that sets of objects withmultiple windows to the same place will not cause problems.The \textc{wnorms} array in the object part structure holds the normal vectorsfor the window polygons.  Just as normal polygons do, windows have a front sideand a back side, and will only be seen through if the normal vector pointstowards the view point.\subsection{Environment}*/typedef struct taglight PG_LIGHT;typedef struct tagfog PG_FOG;typedef struct tagenvironment {	int nlights;	PG_LIGHT *lights;	PG_FOG *fog;} PG_ENVIRONMENT;/*9The \textc{PG\_ENVIRONMENT} structure holds the properties of theenvironment in which objects are displayed, including lighting andfog.\subsection{Fog}*/struct tagfog {	int type;		PIX_RGB32 col;	float start_dist;	float stop_dist;};/*9 Type $0$ fog does nothing.  Type $1$ fog calculates the distance to eachpolygon from the camera.  If the distance is between \textc{start\_dist} and \textc{stop\_dist}, the color of the polygon is linearly varied between itsnormal color (at the closest distances) to the fog color (at the farther distances).  Other types are currently unimplemented.\subsection{Lights}*/struct taglight {    int type;    PG_VECTOR pos;    float blue,green,red;};/*9The scene being displayed can be illuminated by lights.  If no lights arespecified ($\textc{nlights}=0$) then each surface is displayed withthe exact color it's \textc{PG\_COLOR} attribute specifies.  If lightsare provided, the color of each surface is adjusted based on the color andintensity of the lights, providing a more realistic 3~dimensional appearance.The \textc{type} member of the \textc{PG\_LIGHT} structure allows the user to select between different types of lights which give differenteffects.  Each of several lights can have a different type.  Currently,there are three types of lights defined, but the current implementationonly understands two of them.  The available types are:\begin{description}	\item[0:] Light is ambient. The \textc{pos} vector is not used.	\item[1:] Light is at infinity.  \textc{pos} is a unit vector 						pointing toward it.	\item[2:] Light is a local point source centered at \textc{pos}.						This type is not yet implemented.\end{description}Notice that more than one ambient light is redundant; they can bereplaced by one source with the sum of the colors.  An ambientlight color of $(1.0,1.0,1.0)$ causes the colors of the variousobjects to be displayed without modification.\subsection{Functions}*/short BeginRender3D(PG_CAMERA *c,PG_ENVIRONMENT *env);/*9\subsubsection*{BeginRender3D}This function takes a camera pointer and an environment pointer as arguments,and sets up the library to begin rendering to the camera's bitmap.  Thebitmap is not cleared, and the z-buffer is not zeroed.  The cropping settingsof the bitmap at the time BeginRender3D is called are used to control theregion of the bitmap which is rendered to.*/void EndRender3D(PG_CAMERA *c);/*9\subsubsection*{EndRender3D}This function tells the library that rendering to a particular camera iscomplete.  Currently this function doesn't do anything.  Call it anyway.I may want to use it for something in a future version.*/short ChangeCamera(PG_CAMERA *c);/*9\subsubsection*{ChangeCamera}This function can be called between BeginRender3D and EndRender3D to changethe camera settings.  This differs from calling EndRender3D and BeginRender3Dagain in that it doesn't mark all objects as unrendered.  This can be usefulfor simulating reflections, double exposures, and the like.  */short ChangeEnvironment(PG_ENVIRONMENT *env);/*9\subsubsection*{ChangeEnvironment}This function can be called between BeginRender3D and EndRender3D to changethe environment settings.  This differs from calling EndRender3D and BeginRender3D again in that it doesn't mark all objects as unrendered.  This can be useful for changing between indoor and outdoor lighting, andother color effects.*/int IsRendered(PG_OBJECT *obj);/*9\subsubsection*{IsRendered}At any time between one call to BeginRender3D and the next, IsRendered willreturn nonzero if an attempt was made to draw a given object, eitherusing the DrawObject function directly or through a chain of windows.In applications which rely heavily on windows this can be used as atest to determine how much of a linked set of objects is actually visible.*/void MarkRendered(PG_OBJECT *obj);/*9\subsubsection*{MarkRendered}This function can be used to artificially prevent an object from beingdrawn when seen through windows.  There are obscure cases where a programmay want to render an object directly instead of letting the windowsystem do it.  This will not prevent a direct call to DrawObject fromredrawing the object.  MarkRendered is only useful between BeginRender3Dand EndRender3D.*/void MarkUnrendered(PG_OBJECT *obj);/*9\subsubsection*{MarkUnrendered}This function tells the window system that the object has not already beendrawn, and should not be skipped over if it is encountered again.  Thiscan be helpful if you're doing weird things with coordinate systems whichcause the same object to be rendered in more than one location, or if youmake changes to the camera or environment settings while rendering.MarkUnrendered is only useful between BeginRender3D and EndRender3D.*/void DrawObject(PG_OBJECT *obj);/*9\subsubsection*{DrawObject}Calling this function is the main point of the library.  DrawObjectdraws an image of the specified object using the camera and environmentsettings selected by BeginRender3D.  It also draws any subobjects, andany objects visible through windows from this one.  Do not callDrawObject outside of a BeginRender3D and EndRender3D pair.*/void DrawTable(PG_VECTOR *axis,PG_BASIS *basis,float zoom,							PIX_RGB32 *cols);/*9\subsubsection*{DrawTable}	This function fills the background of the image (that is, every pointwhere the z-buffer is $0$) with a $1$ dimensional texture.  Thetexture is mapped as if painted on an infinite sphere with the camera atthe center.  Each of the $513$ color values is the color of a small ringor constant latitude on the sphere with $0$ being one pole, $512$ beingthe other, and $256$ being the equator.  The axis vector points in thedirection of the pole with color $512$.  The basis and zoom values arethe coordinates and zoom factor of the viewpoint (usually the same asthe active camera's basis and zoom values).This can be a faster way to do smoothly shaded ground and sky effectsthan rendering a lot of polygons.*/void DrawBack(PG_VECTOR *axis,PG_BASIS *basis,float zoom,							PIX_RGB32 *equ,PIX_RGB32 *pole);/*9\subsubsection*{DrawBack}This function draws a texture, the same way DrawTable does.  The textureis a smoothly varying color gradient, with \textc{equ} specifying thecolor at the equator, and \textc{pole} giving the color change betweenthe equator and the positive pole.  The negative pole will have theopposite color change.  Note that for the pole color, the red, green, andblue color values can be treated as signed bytes.Watch out for large values of pole, since DrawBack will allow color valuesto overflow $255$ and wrap back to $0$.*/void DrawPoly(PIX_RGB32 c,						int n,PG_VECTOR *pts,						PG_VECTOR *norm,float zoom);/*9\subsubsection*{DrawPoly}DrawPoly draws a single polygon into the camera's bitmap, using the specifiedzoom value, color and normal vector.  The polygon is given as an array of npoints.The polygon is not clipped before drawing, and undefined behavior will resultif any of the points are outside of the region viewable by the bitmap'sclipping rectangle.  (I mean this.  There will be divide by $0$ errors, and badmemory accesses.  It's not pretty.)  The points are specified in cameracoordinates, with positive z being into the screen, positive y being up, andpositive x being to the right.  The color is the exact color value that will bewritten into the buffer; the lighting model is not used to modify it.*/int ClipPoly(int npts,PG_VECTOR *pts,PG_VECTOR *out,int nplns,PG_PLANE *plns);/*9\subsubsection*{ClipPoly}This is the library's 3~Dimensional clipping routine.  Pass an array of pointsrepresenting a polygon in, along with an array of clipping planes, and theout array will be filled with the points of the clipped polygon.  The newnumber of points will be returned.  Notice that the number of points in theclipped polygon might be larger than in the original.  Be sure the out bufferhas enough room for the extra points.*//* vector and matrix macros *//*9\subsubsection*{Vector and Matrix Macros}\begin{eqnarray*} \mathrm{transpose}(d,s) & \equiv &	d_{ij} \leftarrow s_{ji} \\\mathrm{vecmult}(w,v,b) & \equiv &	w_j \leftarrow \sum_i v_i \cdot b_{ij} \\ \mathrm{matmult}(n,m,b) & \equiv &	n_{ij} \leftarrow \sum_k m_{ik} \cdot b_{kj} \\ \mathrm{dot}(a,b) & \equiv & \langle a,b \rangle \equiv	\sum_i a_i \cdot b_i  \\ \mathrm{cross}(d,a,b) & \equiv &	d \leftarrow a \times b \equiv	\left\{ \begin{array}{c}			d_x \leftarrow a_z \cdot b_y - a_y \cdot b_z \\			d_y \leftarrow a_x \cdot b_z - a_z \cdot b_x \\			d_z \leftarrow a_y \cdot b_x - a_x \cdot b_y 	\end{array} \right.\end{eqnarray*}*/#define transpose(d,s) \    (d).x.x=(s).x.x;\    (d).x.y=(s).y.x;\    (d).x.z=(s).z.x;\    (d).y.x=(s).x.y;\    (d).y.y=(s).y.y;\    (d).y.z=(s).z.y;\    (d).z.x=(s).x.z;\    (d).z.y=(s).y.z;\    (d).z.z=(s).z.z;#define vecmult(nv,ov,b) \    (nv).x=(ov).x*(b).x.x + (ov).y*(b).y.x + (ov).z*(b).z.x; \    (nv).y=(ov).x*(b).x.y + (ov).y*(b).y.y + (ov).z*(b).z.y; \    (nv).z=(ov).x*(b).x.z + (ov).y*(b).y.z + (ov).z*(b).z.z;#define matmult(nm,om,b) \    vecmult((nm).x,(om).x,(b)) \    vecmult((nm).y,(om).y,(b)) \    vecmult((nm).z,(om).z,(b))#define mysqrt(x) sqrt(x)#define mysin(x) sin(x)#define mycos(x) cos(x)#define dot(a,b) ((a).x*(b).x+(a).y*(b).y+(a).z*(b).z)#define cross(vd,va,vb) \	(vd).x=(va).z*(vb).y-(va).y*(vb).z; \	(vd).y=(va).x*(vb).z-(va).z*(vb).x; \	(vd).z=(va).y*(vb).x-(va).x*(vb).y;/* some common geometry calculations */void GramSchmidt(PG_BASIS *b);void RotVect(PG_VECTOR *v,PG_VECTOR *w,float cosx,float sinx);void Rotate(PG_BASIS *b,PG_VECTOR *w);/* forces norms on the object to be actually normal to surfaces. */void FixNorms(PG_OBJECT *obj);#endif
