introduction - true basic · introduction the true basic 3-d graphics toolkit fully supports both...

59

Upload: others

Post on 08-May-2020

6 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make
Page 2: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

IntroductionThe True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro-jections with simple and useful defaults that make it easy to get good-looking images.The 3-D Graphics Toolkit also includes advanced routines that give you complete controlover the images.

Included in this PackageThe following programs are included with the True BASIC 3-D Graphics Toolkit disk:

3Dlib – 3-D Graphics Toolkit (Loadable module).

3Dcont – 3-D Contour Plotting (Not loadable).

The following Demo Programs:Axes3 House3 Project3 Splot3 Zmesh3Bars3 ImagData Record Topo3 Zplot3Blocks3 Oblique3 Scale3 Zbar3 Zsplot3Cube3 PlayBack Spiral3 Zdata3

01/01

TRUE BASIC REFERENCE SERIES:

3-D GraphicsToolkit

Page 3: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

Additional ReadingFor full descriptions of 3-D graphics, consult:

Fundamentals of Computer Graphics,Foley and van Dam, Addison-Wesley, 1983.

Principles of Interactive Computer Graphics, Second Edition, Newman and Sproull, McGraw-Hill, 1979.

Computer Graphics: A Programming Approach,Harrington, McGraw-Hill, 1983.

Mathematical Elements for Computer Graphics,Rogers and Adams, McGraw-Hill, 1976.

2 3-D Graphics Toolkit

01/01

Page 4: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

Getting StartedBefore you start, load the compiled version of 3Dlib*. This is not strictly necessary, butit allows the 3-D graphics programs run much faster! Then try running several sampleprograms. Two of them are described below; the others are described in the “SamplePrograms” section.

The Axes3 ProgramCall up the Axes3 program and run it. It shows the 3-D outline of a box, and drawsaxes with tick marks, and a circle.

Figure 40.1: Unit Cube with Ticks and Circle.

Now look at the source program. It consists mainly of calls to 3-D graphics subrou-tines. In a nutshell, they are:

PersWindow opens a 3-D window onto some rectangular block of space, and posi-tions the “camera” so it gives a clear view of that volume. Frame3 draws the edges ofthe viewing volume. Ticks3 draws the x, y, and z axes with tick marks spaced at theintervals specified. CircleZ3 draws a circle in the plane z = 0, much like TrueBASIC’s BOX CIRCLE statement.

Getting Started 3

01/01

Page 5: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

The Zplot3 ProgramCall up the Zplot3 program and run it. It shows the “contour plot” of a fairly compli-cated function.

Figure 40.2: Contour Plot of a Function.

Now look at the source code. It contains only a few subroutine calls. PersWindow, asabove, describes the viewing volume. SetCamera3 repositions the camera to a newlocation in 3-D space. Zplot draws a contour graph of the function F. And finally,Zplot3 defines the function F that will be plotted. That’s all it takes!

4 3-D Graphics Toolkit

01/01

Page 6: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

The Zbar3 ProgramCall up the Zbar3 program and run it. It shows a 3-D bar chart of a number of datapoints, superimposed on top of a topographic map of the same data.

Figure 40.3: Bar Chart and Topographic Map of Data Set.

The source code contains several advanced subroutine calls. ZbarData and TopoDatado most of the work; they draw the bar chart and topographic map, respectively. TheBlock3 routine draws the solid slabs on which the bars and topo map sit. The otherroutines perform minor tasks such as setting bar colors.

What Next?The next two sections describe in detail all the nuts and bolts of 3-D graphics. You canread them, if you wish, or you can skip them and proceed directly to descriptions of the3-D Graphics Toolkit subroutines.

But you’ll probably want to turn back to these sections later to get a good understandingof how 3-D graphics works.

Getting Started 5

01/01

Page 7: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

3-D TheoryThree-dimensional graphics shows “projections” of 3-D objects on a flat, two-dimen-sional screen. This is a complicated affair. Let’s begin by going over the basics.

The Camera AnalogyUsing 3-D graphics is like taking a picture with a camera.

Figure 40.4: Taking a Picture.

We are taking a picture of an object. This requires both the object itself and a camera.The camera is a certain distance away from the object and aims at some point. (Thispoint is usually somewhere on the object itself, but need not be.)

Let’s now switch to computer graphics terms. The camera is aimed at the referencepoint. The film within the camera corresponds to the view plane. The viewing dis-tance is the distance between the reference point and the view plane.

6 3-D Graphics Toolkit

01/01

z

y

x

viewing distance

view reference point

Page 8: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

Perspective and Parallel ProjectionsA camera records the 3-dimensional world on a 2-dimensional piece of film. In computergraphics, this is called “projecting” objects onto the view plane. The 3-D GraphicsToolkit handles two kinds of projections: perspective projections and parallel projec-tions (sometimes called orthographic projections). Figure 40.5 shows the difference.When viewing an object, you must first choose whether you want to see a perspective orparallel projection.

Figure 40.5: Perspective and Parallel Projections.

Perspective projections mimic how we see things. “Projection lines” emerging from anobject all converge at one point — the center of perspective. The camera must be sit-uated between the reference point and the center of perspective. (In fact, the 3-D Graph-ics Toolkit gives an error if you try to place the camera behind the center of perspective.)As in real life, the camera position determines the size of the projected image. As thecamera approaches the object, the image gets bigger. As it gets farther away, the imageshrinks.

Parallel projections are simpler than perspective projections since their projection linesnever converge — they remain parallel to infinity. Thus moving the camera nearer tothe object, or farther away, doesn’t affect the size of the object’s image. Parallel projec-tions look less realistic than perspective projections but are easier to draw (by hand) andoften easier to use. They are often used for architecture, mechanical engineering, and soforth. Some common forms of parallel projections are called axonometric, isometric,dimetric, cavalier, and cabinet projections. Despite the forbidding range of names, theseare all parallel projections, and the 3-D Graphics Toolkit handles them all.

3-D Theory 7

01/01

Parallel Projection

Perspective Projection

Page 9: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

To see the difference between perspective and parallel projections, call up the Project3program from your disk and run it.

Three-Dimensional WindowsRefering back to Figure 40.4, you’ll see that there are many variables involved in point-ing a camera at an object. You must supply the reference point, the camera position, theprojection type, and perhaps the center of perspective. Fortunately, you don’t have tocontrol each of these variables yourself. You can give one subroutine call and have the3-D Graphics Toolkit supply a reasonable view.

The PersWindow and ParaWindow subroutines do all the work. The two routines areexactly the same except that one provides a perspective projection, and the other a par-allel projection. Both are 3-dimensional equivalents of True BASIC’s SET WINDOWstatement; they specify a block viewing volume instead of a flat viewing rectangle. SeeFigure 40.6.

Figure 40.6: The Viewing Volume.

These routines automatically set the reference point, camera position, and (if relevant)center of perspective. The center of the viewing volume becomes the reference point.The camera is positioned so that three sides of the viewing volume are visible. The x axisis horizontal, and the z axis is vertical. The positive y axis recedes “into the screen.”

8 3-D Graphics Toolkit

01/01

z

y

x

Page 10: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

For perspective views, the camera is positioned far enough away from the referencepoint so that the perspective looks natural. The center of perspective is behind the cam-era.

You can adjust any of these defaults after you open the window. Call SetCamera3 toadjust the camera position, and SetRefPt3 to adjust the reference point. (At a lowerlevel, the SetViewPlane3 subroutine changes the view plane normal, and SetDistance3changes the viewing distance. SetCP3 controls the center of perspective.)

Your Viewing Window and its Aspect RatioRemember that your 3-D volume is projected onto a 2-D plane. As in True BASIC’s owngraphics, only a portion of this infinite plane is visible on your screen. In fact, your cur-rent True BASIC window acts as the window onto the view plane. You see exactly thepart of the view plane that lies inside your current window. Figure 40.7 illustrates.

Figure 40.7. Your window onto the View Plane.

When you specify a 3-D viewing volume, the graphics routines automatically try to scaleeverything so that the results are all visible on your screen. In particular, they resetyour current True BASIC window so the origin (0,0) is at the center.

3-D Theory 9

01/01

Perspective Projection

Your True BASICwindow is a windowonto the View Plane.

-1 1-1

1

Page 11: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

You can use True BASIC’s SET WINDOW statement, at any time, to change your win-dow onto the view plane. The bigger you make your window, the more of the view planeyou will see (but the smaller the projected image will look). And the smaller you makeit, the less you’ll see.

The perennial problem of “aspect ratios” crops up, again, at this point. That is, althoughthe resulting window runs from -n to n in both directions, the window itself probablyisn’t square. The output is stretched to fit in the window, and hence may be distorted.To fix the aspect ratio, adjust either the horizontal or vertical window dimension. Withenough fiddling, you can make squares look square and circles look circular.

Rotating the CameraYou can “rotate” the camera, keeping it focused on the same point but turning the cam-era 90 degrees, upside down, or whatever. The default views used in the 3-D GraphicsToolkit keep the camera upright — i.e., keep the z axis vertical — but the SetUp3 sub-routine can change this view-up direction.

Changing the Parallel Projection LinesThere’s a final trick you can play with parallel projections. The projection lines don’thave to be perpendicular to the view plane. Instead, they can strike the view plane atsome angle other than 90 degrees. Figure 40.8 illustrates.

Figure 40.8. Normal and Oblique Projections.

10 3-D Graphics Toolkit

01/01

Normal Projection

ObliqueProjection

Page 12: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

This can be handy at times. For instance, cavalier and cabinet projections position thecamera directly “in front” of an object but also show its top and sides. They do this bychanging the projection lines so they no longer are perpendicular to the view plane. (Seethe section on “Oblique Projections” for more information.)

The SetProj3 subroutine controls the parallel projection lines.

Wireframes vs. Hidden SurfacesThis package provides wireframe graphics. Hidden surfaces are not removed, so theresulting image looks like a wireframe model of the object.

More complicated graphics packages provide “hidden surface” projections as well aswireframe projections. These projections carefully remove surfaces which are hiddenbehind other, closer surfaces. The result looks more natural than wireframe drawings.

However, beauty has a price. Hidden surface drawings are, in general, much slower todisplay than wireframe drawings since the computer must do many calculations todetermine which surfaces hide other surfaces. Furthermore, they require all drawing tobe done in terms of polygons rather than lines, and hence are noticeably harder to usethan wireframe systems.

Note: The contour-plotting subroutines do allow specialized kinds of hidden surfaceremoval. They plot the 3-dimensional image of a data set or function by drawing barcharts or “contour lines” over the surface. These routines do remove hidden lines. Seethe section on “Contour Plots” for more information.

Three-Dimensional ClippingThe 3-D Graphics Toolkit does not perform any three-dimensional clipping (although itdoes clip the projected image in the view plane window). Clipping is usually not neededfor simple problems.

However, if you move the camera within an object, you will notice stray lines on the pro-jected image. These are the unclipped projections of lines which lie behind the camera.The solution is simple: don’t draw lines behind the camera. Increase the viewing dis-tance so that the camera is far enough away.

3-D Theory 11

01/01

Page 13: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

Some Well-Known ProjectionsThis section describes the older, artisan’s classifications of 3-D projections in terms ofmodern computer graphics. Skip this section if you’re not interested.

Perspective ProjectionsWhen perspective projections were drawn by hand, draftsmen used “vanishing points”to control the perspective. They classified perspective drawings by the number of van-ishing points needed to draw them. You may have seen these mysterious points in bookson perspective drawing. Vanishing points are no longer used with computerized graph-ics, but you can easily simulate them.

Figure 40.9: Vanishing Points in Perspective Views.

One-point perspective occurs when one of the faces of the viewing volume is parallel tothe view plane: the camera position shares two coordinates with the reference point.Thus, if the reference point is (x1, y, z) then the camera position could be (x2, y, z) etc.

Two-point perspective occurs when one pair of the viewing volume’s edges is parallel tothe view plane (but no face). In other words, the camera position shares one coordinatewith the reference point. For example, if the reference point is (x1, y1, z) then the cam-era position could be (x2, y2, z) etc.

Three-point perspective occurs when none of the viewing volume’s edges are parallel tothe view plane. The camera position shares no coordinates with the reference point.Thus if the reference point is (x1, y1, z1) then the camera position could be (x2, y2, z2).

12 3-D Graphics Toolkit

01/01

One point

Two point Three point

Page 14: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

The default camera position gives three-point perspective. This is the hardest kind ofview to draw by hand but the most informative — and after all, that’s why we havecomputers.

Parallel ProjectionsParallel projections can be classified as “axonometric” and “oblique” projections. Axono-metric projections keep the view plane perpendicular to the projection direction.Oblique projections tilt the view plane.

The default parallel view is an axonometric (trimetric) projection.

Axonometric Parallel ProjectionsAxonometric projections can be most easily described by discussing their effects on acube.

Figure 40.10: Types of Axonometric Projections.

Isometric projections shorten all edges equally. They occur when the camera is lookingdirectly through one corner of the cube to the cube’s center — the x, y, and z distancesfrom the camera to the reference point are all equal.

Dimetric projections shorten two edges of the cube equally. In other words, two out of thethree x, y and z distances from the reference point to the camera are equal.

Trimetric projections shorten each edge by a different amount. In other words, the x, y,and z distances from the reference point to the camera are all different.

Well-Known Projections 13

01/01

Isometric

TrimetricDimetric

Page 15: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

Oblique Parallel ProjectionsOblique projections “slant” the projection direction so that it’s no longer perpendicularto the view plane. Cavalier and cabinet projections are the two most common obliqueprojections; they differ only in how much the projection direction is altered.

Both change the projection direction so points farther away than the reference point areprojected up and to the right. Points closer than the reference point are projected downand to the left.

Figure 40.11: Two Common Oblique Projections.

Cavalier projections preserve “depth” distance. Suppose one point is directly behindanother point. These two points will be projected to two different points on the viewplane. The distance between the two projected points will exactly equal the distancebetween the two original points in 3-dimensional space. You can get a cavalier projec-tion by setting a parallel viewing volume, picking a camera position, and then calling theCavalier3 routine.

Cabinet projections divide the “depth” distance by 2 when projecting. This looks consid-erably more natural than a cavalier projection, but is otherwise very similar. You canget a cabinet projection by setting a parallel viewing volume, picking a camera position,and then calling the Cabinet3 routine.

14 3-D Graphics Toolkit

01/01

CabinetCavalier

Page 16: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

Simple GraphicsThis section describes all the routines which allow simple 3-D graphics. They let youmake perspective or parallel drawings with a minimum of fuss.

PersWindow Set perspective window.ParaWindow Set parallel window.

SetCamera3 Set camera position.AskCamera3 Ask camera position.

PlotOff3 Plot point, turn beam off. PlotOn3 Plot point, turn beam on. PlotRoff3 Plot relative, turn beam off.PlotRon3 Plot relative, turn beam on.

LineOn3 Plot line segment, turn beam off.LineOff3 Plot line segment, turn beam on.

PlotText3 Plot label.Project3 Convert 3-D to 2-D coordinates.

Default Values for a ViewIf you refer back to the 3-D Theory section, you’ll see that proper control of the “camera”involves many different variables. The PersWindow, ParaWindow, and SetCamera3routines all have simple calling interfaces and provide reasonable default values formany of these variables. These default values are described for each routine. To controlthe variables yourself, see the Advanced Viewing section.

The Current Point and The BeamLike True BASIC’s plotting, these routines all know about the “current point.” You canplot a point and leave the beam turned on; when you next plot a point, these routines willdraw a line from the old current point to the new one. If you turn the beam off, it won’tdraw the line.

PersWindow (x1, x2, y1, y2, z1, z2)PersWindow is like True BASIC’s SET WINDOW statement. It tells what block of 3-dimensional space you want to view and sets the view reference point to be at the exactcenter of this window’s volume. It sets up a perspective projection of the volume.

Simple Graphics 15

01/01

Page 17: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

It positions the camera at a location that usually makes a clear and attractive view of thewindow volume. The camera sits in front of, to the side of, and above, this volume. Itsexact position depends on the relative sizes of the window’s x, y and z dimensions. You canuse the SetDistance3 routine to bring the camera closer to the viewing window (and thusemphasize the perspective effect), or move it farther away (and thus diminish the effect).

Furthermore, PersWindow points the camera at the center of the volume and sets thecenter of perspective to some distance directly behind the camera. This gives “natural-looking” effects. You can use the SetViewPlane3 and SetCP3 routines to change the cam-era direction and center of perspective, respectively.

Finally, PersWindow uses the same scale for the x, y, and z axes. See theScalePersWindow routine if you want to use different scales for each dimension. (It’sin the Scaled Views section.)

PersWindow doesn’t clear the screen, so you must use True BASIC’s CLEAR statementwhen you want to start a new display.

! Draw the marked cube with! a default perspective view.!library “3dlib”call PersWindow(0, 1, 0, 1, 0, 1)call MarkedCubeend

Exceptions:33 3-D window minimum = maximum.

ParaWindow (x1, x2, y1, y2, z1, z2)ParaWindow is like True BASIC’s SET WINDOW statement. It tells what block of 3-dimensional space you want to view and sets the view reference point to be at the exactcenter of this window’s volume. It sets up a parallel projection of the volume.

Like PersWindow, it positions the camera at the position in front of, above, and to theside of the viewing window, and points the camera directly at the reference point. Thisgives rise to parallel view in which all three sides of the viewing volume are visible, withall of them having different lengths.

Finally, ParaWindow uses the same scale for the x, y, and z axes. See theScaleParaWindow routine if you want to use different scales for each dimension. (It’sin the “Scaled Views” section.)

ParaWindow doesn’t clear the screen, so you must use True BASIC’s CLEAR statementwhen you want to start a new display.

16 3-D Graphics Toolkit

01/01

Page 18: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

! Draw the marked cube with! a default parallel view.!library “3dlib”call ParaWindow(0, 1, 0, 1, 0, 1)call MarkedCubeend

Exceptions:

33 3-D window minimum = maximum.

AskWindow3 (x1, x2, y1, y2, z1, z2)AskWindow3 returns the current viewing window’s coordinates in x1, x2, y1, y2, z1, andz2.

AskView3 (view$)AskView3 returns either “PERSPECTIVE” or “PARALLEL” in view$, depending onwhether the current view is a perspective view or a parallel view.

SetCamera3 (x, y, z)SetCamera3 moves the camera to a new location (x, y, z). It works for both perspectiveand parallel projections, and does not change what’s already drawn on the screen.

SetCamera3 always points the camera directly at the reference point. You can then usethe SetDistance3 routine to move the camera closer to (or farther from) the referencepoint; SetDistance3 doesn’t affect the camera angle.

The resulting image is always “normalized” so its size remains roughly constant. Inother words, moving the camera farther from the object does not make the objectsmaller. To control the image size, use the SetScale3 routine.

If you want to control the camera aim and distance independently, use the SetView-Plane3 and SetDistance3 routines. See the Advanced Viewing section for more infor-mation, and see the Cube3 program for an example of SetCamera3.

Exceptions:

42 Viewing distance is zero.

Simple Graphics 17

01/01

Page 19: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

AskCamera3 (x, y, z)AskCamera3 returns the current camera position. It works for either parallel or per-spective views.

PlotOff3 (x, y, z)PlotOff3 moves to the point (x, y, z) and turns the beam off. If the beam was on, it drawsa line as it moves from the previous point to the new point. Hence it’s the 3-dimensionalequivalent of True BASIC’s statement:

PLOT x, y

You can use it either to draw an isolated point or to finish drawing a line segment. Tosimply turn off the beam, you can use True BASIC’s empty PLOT statement.

PlotOn3 (x, y, z)PlotOn3 moves to the point (x, y, z) and turns the beam on. If the beam was already on,it draws a line as it moves from the previous point to the new point. Hence it’s the 3-dimensional equivalent of True BASIC’s statement:

PLOT x, y;

This is the general workhorse for drawing 3-dimensional graphics since most graphs arecomposed from lines. To turn off the beam, you can use True BASIC’s empty PLOT state-ment or the PlotOff3 routine.

When you draw a complicated object, with many line segments, you may want to useMatLines3 rather than many calls to PlotOn3.

Figure 40.12: Simple 3-D Graphics — The SPIRAL3 Program.

18 3-D Graphics Toolkit

01/01

Page 20: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

PlotRoff3 (dx, dy, dz)PlotRoff3 moves (dx, dy, dz) units away from the current point and turns off the beam. Ifthe beam was on before this routine was called, it draws a line as it moves to the point.

PlotRon3 (dx, dy, dz)PlotRon3 moves (dx, dy, dz) units away from the current point and turns on the beam. Ifthe beam was on before this routine was called, it draws a line as it moves to the newpoint.

LineOn3 (x1, y1, z1, x2, y2, z2)LineOn3 draws a line segment from (x1, y1, z1) to (x2, y2, z2) and leaves the beam turnedon. You could do the same thing by calling PlotOn3 twice but this is more convenient.

LineOff3 (x1, y1, z1, x2, y2, z2)LineOff3 draws a line segment from (x1, y1, z1) to (x2, y2, z2) and turns the beam off. Youcould do the same thing by calling PlotOn3 and then PlotOff3 but this is more conve-nient.

PlotText3 (x, y, z, text$)PlotText3 works like True BASIC’s PLOT TEXT statement. It prints the text with itsanchor point (lower, left corner) placed at the point (x, y, z). You can use True BASIC’sSET TEXT JUSTIFY statement to change the anchor point’s position.

The text itself is not affected by perspective or the viewing angle. It always appearsnormal and two-dimensional.

Project3 (x, y, z, flatx, flaty)Project3 converts a 3-dimensional (x, y, z) coordinate to the corresponding flat TrueBASIC window coordinate (flatx, flaty).

This is useful if you want to mix 2- and 3-dimensional graphics. For instance, it makesit easy to draw a circle around a given point in a three dimensional space to illustrate itsposition.

Simple Graphics 19

01/01

Page 21: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

20 3-D Graphics Toolkit

01/01

Advanced Drawing RoutinesThis section contains the advanced drawing routines. These routines are usually notneeded for graphics work but can prove handy from time to time.

MatPoints3 Plot array of points.MatLines3 Plot array of line segments.MatArea3 Plot polygon surface.MatPlot3 Plot segments and/or points.MatProject3 Project array of points.

Frame3 Draw outline of current window.Box3 Draw outline of “block.”Block3 Draw shaded “block” volume.Axes3 Draw axes.Ticks3 Draw axes with tick marks.AxesSub3 Low-level axes routine.UnitCube Draw unit cube outline.MarkedCube Draw marked unit cube outline.

RectX3 Draw rectangle in x plane.RectY3 Draw rectangle in y plane.RectZ3 Draw rectangle in z plane.FillRectX3 Draw filled rectangle in x plane.FillRectY3 Draw filled rectangle in y plane.FillRectZ3 Draw filled rectangle in z plane.

CircleX3 Draw ellipse in x plane.CircleY3 Draw ellipse in y plane.CircleZ3 Draw ellipse in z plane.FillCircleX3 Draw filled ellipse in x plane.FillCircleY3 Draw filled ellipse in y plane.FillCircleZ3 Draw filled ellipse in z plane.

GridX3 Draw grid in x plane.GridY3 Draw grid in y plane.GridZ3 Draw grid in z plane.

Page 22: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

MatPoints3 (pts(,))MatPoints3 is like True BASIC’s MAT PLOT points statement except that it works in 3dimensions. It draws a series of points, each of which is saved in the pts(,) array.

The array may have any lower bound in either dimension but it must have exactly threeelements across — they’re used as the x, y, and z coordinates of the points.

Exceptions:

32 Bad 3-D graphics MAT points array.

MatLines3 (pts(,))MatLines3 is like True BASIC’s MAT PLOT LINES statement, except that it works in 3dimensions. It draws a series of line segments between the points saved in the pts(,)array and turns off the beam when done.

The array may have any lower bound in either dimension, but it must have exactly threeelements across — they’re used as the x, y, and z coordinates of the points.

When you draw a complicated object with many line segments, you may want to useMatLines3 rather than many calls to PlotOn3.

Exceptions:

32 Bad 3-D graphics MAT points array.

Figure 40.13: MatLines3, RectX3, CircleX3— The HOUSE3 Program.

Advanced Drawing Routines 21

01/01

Page 23: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

MatArea3 (pts(,))MatArea3 is like True BASIC’s MAT PLOT AREA statement, except that it works in 3dimensions. It draws the edges of the polygon defined by the points in the pts(,) arrayand then fills in the area of this polygon in the current color.

The array may have any lower bound in either dimension, but it must have exactly threeelements across — they’re used as the x, y, and z coordinates of the points.

Exceptions:

32 Bad 3-D graphics MAT points array.

MatPlot3 (pts(,))MatPlot3 draws one or more points or line segments. The pts(,) array contains a seriesof 3-D points; and for each point, it also contains a flag saying whether the beam shouldbe turned on or off after that point.

The array may have any lower bound in either dimension, but it must have exactly fourelements across — the first three are used as the x, y, and z coordinates of a point, andthe last is used as the beam flag. If the flag is zero, the beam is turned off after that point;otherwise, it’s turned on.

! Draw an “X” shape.!library “3dlib”dim pts(4,4)call PersWindow(-2, 2, -2, 2, -2, 2)mat read ptsdata -2,-2,-2,1, 2,2,2,0, -2,2,-2,1, 2,-2,-2,0call MatPlot3(pts)end

Exceptions:

32 Bad 3-D graphics MAT points array.

MatProject3 (pts(,))MatProject3 finds the projected images of one or more points. The pts(,) array containsa series of 3-D points. For each point, MatProject3 returns the corresponding flat TrueBASIC window coordinate. Thus it’s a version of Project3 which works on a number ofpoints in one operation.

22 3-D Graphics Toolkit

01/01

Page 24: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

The array may have any lower bound in either dimension, but it must have exactly fiveelements across — the first three are used as the x, y, and z coordinates of a point. Thelast two are the resulting flatx and flaty image coordinates.

Exceptions:32 Bad 3-D graphics MAT points array.

Frame3Frame3 draws the outline of your current viewing volume. It’s often useful for checkingyour current camera position to make sure that everything is visible and neatlyarranged.

Box3 (x1, x2, y1, y2, z1, z2)Box3 draws the outline of the 3-dimensional block specified by the given coordinates.

Block3 (x1, x2, y1, y2, z1, z2, col1$, col2$, col3$, frame)Block3 draws a “shaded” block in 3 dimensions. This is suitable for histogram blocks andso forth.

The block’s edges are defined by the x, y, and z coordinates. Then the routine draws thevisible sides of the blocks using col1$, col2$, and col3$ as the colors for each of the threevisible sides. These color strings can be True BASIC colors, such as “red” or “yellow”, orcan represent color numbers such as “1” or “25.” They don’t affect the current color.

Figure 40.14: A Collection of Blocks — The BLOCKS3 Program.

Advanced Drawing Routines 23

01/01

Page 25: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

If frame is nonzero, the routine finishes by tracing the block’s edges with lines drawn inthe current color. See the Blocks3 program for examples.

Exceptions:11008 No such color: xxx

-11008 On DOS systems

Axes3Axes3 draws the x-y-z axes in your current window. It does not draw any “tick marks” onthe axes. Use Ticks3 to get tick marks.

Ticks3 (xi, yi, zi)Ticks3 draws the axes in your current window with tick marks at xi, yi, and zi unitsapart. If any of the tick mark increments is zero, that axis will be drawn without ticks.Negative increments are treated exactly like positive increments.

If the tick marks are too large or too small for your taste, change the ticksize variable inthe AxesSub3 routine. Make it bigger for bigger ticks, and smaller for smaller ticks. Seethe Axes3 program for an example.

Figure 40.15: Unit Cube with Ticks and Circle — The AXES3 Program.

AxesSub3 (x1, x2, y1, y2, z1, z2, xi, yi, zi)AxesSub3 is a low-level subroutine used by the Axes3 and Ticks3 routines. You will prob-ably not need to use it. However, it is slightly more flexible than the other two routines.

24 3-D Graphics Toolkit

01/01

Page 26: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

AxesSub3 draws tick marks along portions of the x-y-z axes. Tick marks are placedbetween x1 and x2 along the x-axis, spaced xi units apart. (The other two axes aretreated similarly.) If x1 = x2, that axis is not drawn. If xi = 0, no tick marks are drawn.

! Draw the X-Y axes, but not the Z axis.!library “3dlib”call PersWindow(-10, 10, -10, 10, -10, 10)call AxesSub3(-10, 10, -10, 10, 0, 0, 2, 2, 0)call UnitCubeend

UnitCubeUnitCube draws the “unit cube,” that is, the cube whose opposite corners are at the ori-gin (0,0,0) and (1,1,1).

It’s handy for calibrating your view if you start to adjust the viewing parameters. How-ever, you may find the MarkedCube routine (below) more useful.

MarkedCubeMarkedCube is like UnitCube except that it has a small diagonal line cutting across thex-y plane’s corner just past the origin. It also has diagonal lines making an X across theface where x = 1. This makes it easier to see which way the cube is lying, in case you arecompletely confused as to which direction is upwards, etc. (Which is often the case!)

The CUBE3 program, on your disk, shows off MarkedCube.

! Show the marked cube in an! easy-to-see angle.!library “3dlib”call PersWindow(0, 1, 0, 1, 0, 1)call SetCamera3(3, 4, 5)call MarkedCubeend

RectX3 (x, y1, y2, z1, z2)RectX3 draws a two-dimensional rectangle perpendicular to the x axis. That is, the rect-angle’s corners are (x, y1, z1) and (x, y2, z2).

The House3 program uses RectX3 to draw windows on the side of the house.

Advanced Drawing Routines 25

01/01

Page 27: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

RectY3 (y, x1, x2, z1, z2)RectY3 draws a two-dimensional rectangle perpendicular to the y axis. That is, the rect-angle’s corners are (x1, y, z1) and (x2, y, z2).

RectZ3 (z, x1, x2, y1, y2)RectZ3 draws a two-dimensional rectangle perpendicular to the z axis. That is, the rect-angle’s corners are (x1, y1, z) and (x2, y2, z).

FillRectX3 (x, y1, y2, z1, z2)FillRectX3 is like RectX3 except that it colors the entire area of the rectangle rather thandrawing the outline.

FillRectY3 (y, x1, x2, z1, z2)FillRectY3 is like RectY3 except that it colors the entire area of the rectangle rather thandrawing the outline.

FillRectZ3 (z, x1, x2, y1, y2)FillRectZ3 is like RectZ3 except that it colors the entire area of the rectangle rather thandrawing the outline.

CircleX3 (x, y1, y2, z1, z2)CircleX3 draws a two-dimensional ellipse perpendicular to the x axis. That is, the ellipseis inscribed within a rectangle whose corners are (x, y1, z1) and (x, y2, z2). It’s similar toTrue BASIC’s BOX CIRCLE statement.

! Draw unit cube with circle! inscribed on each side.!library “3dlib”call PersWindow(0, 1, 0, 1, 0, 1)call UnitCube

for side = 0 to 1call CircleX3(side, .2, .8, .2, .8)call CircleY3(side, .2, .8, .2, .8)call CircleZ3(side, .2, .8, .2, .8)

next sideend

26 3-D Graphics Toolkit

01/01

Page 28: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

CircleY3 (y, x1, x2, z1, z2)CircleY3 draws a two-dimensional ellipse perpendicular to the y axis. That is, the ellipseis inscribed within a rectangle whose corners are (x1, y, z1) and (x2, y, z2). It’s similar toTrue BASIC’sBOX CIRCLE statement.

CircleZ3 (z, x1, x2, y1, y2)CircleZ3 draws a two-dimensional ellipse perpendicular to the z axis. That is, the ellipseis inscribed within a rectangle whose corners are (x1, y1, z) and (x2, y2, z). It’s similar toTrue BASIC’s BOX CIRCLE statement.

FillCircleX3 (x, y1, y2, z1, z2)FillCircleX3 is like CircleX3 except that it colors the entire area of the ellipse ratherthan drawing the outline.

FillCircleY3 (y, x1, x2, z1, z2)FillCircleY3 is like CircleY3 except that it colors the entire area of the ellipse rather thandrawing the outline.

FillCircleZ3 (z, x1, x2, y1, y2)FillCircleZ3 is like CircleZ3 except that it colors the entire area of the ellipse rather thandrawing the outline.

Figure 40.16: Blocks on a Grid — The BARS3 Program.

Advanced Drawing Routines 27

01/01

Page 29: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

GridX3 (x, y1, y2, z1, z2, ystep, zstep)GridX3 draws a two-dimensional grid that’s perpendicular to the x axis. That is, the gridis drawn over a rectangle whose corners are (x, y1, z1) and (x, y2, z2). The ystep and zstepparameters control the spacing of the grid lines in the y and z directions.

GridY3 (y, x1, x2, z1, z2, xstep, zstep)GridY3 draws a two-dimensional grid that’s perpendicular to the y axis. That is, the gridis drawn over a rectangle whose corners are (x1, y, z1) and (x2, y, z2). The xstep and zstepparameters control the spacing of the grid lines in the x and z directions.

GridZ3 (z, x1, x2, y1, y2, xstep, ystep)GridZ3 draws a two-dimensional grid that’s perpendicular to the z axis. That is, the gridis drawn over a rectangle whose corners are (x1, y1, z) and (x2, y2, z). The xstep and ystepparameters control the spacing of the grid lines in the x and y directions. See the Bars3program for an example.

28 3-D Graphics Toolkit

01/01

Page 30: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

Contour PlotsThis section describes specialized routines that draw contour graphs of 3-D data sets orof “z functions” of two variables z = F(x,y). These routines draw the z surface of the dataset or function by drawing blocks or following contour lines along the x and/or y direc-tions.

Note: You must include a LIBRARY “3dcont” statement in any program that uses oneof these routines.

Zmesh Plot z function surface with a mesh.ZmeshData Plot data-set surface with a mesh.Zplot Plot z function surface, hiding lines.ZplotData Plot data surface, hiding lines.Splot Plot z function surface, clipping.Zbar Plot z function surface by bar chart.ZbarData Plot data surface by bar chart.

Tplot Plot topographic map of z function.TplotData Plot topographic map of data set.

ZplotRect Plot z function surface over x-y rectangle.ZmeshRect Plot z function mesh over x-y rectangle.ZplotSub Lower level routine for Zplot.

SetMesh3 Set number of divisions in mesh.SetZlines3 Set number of contour lines.SetZseg3 Set number of segments per contour line.SetTlines3 Set number of lines in topo plot.SetBarSize3 Set “footprint” of 3-D bars.SetBarColor3 Set color scheme for 3-D bars.SetColor3 Set color scales for contour plot or topo plot.

AskMesh3 Ask number of divisions in mesh.AskZlines3 Ask number of contour lines.AskZseg3 Ask number of segments per contour line.AskTlines3 Set number of lines in topo plot.AskBarSize3 Set “footprint” of 3-D bars.AskBarColor3 Set color scheme for 3-D bars.AskColor3 Ask color scales for contour plot or topo plot.

Advanced Drawing Routines 29

01/01

Page 31: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

30 3-D Graphics Toolkit

01/01

Plotting a Function F(x,y) or Data SetTo plot the surface of a function, you must define an external function F(x,y) that returnsa numeric result. Zmesh, Zplot, etc., will graph this function over an x-y rectangle. Tograph several functions, use a PUBLIC variable to communicate between your mainprogram and F, which can compute different functions based on its value.

To graph a data set, put your data into a two-dimensional array. The first dimension isthe x direction; the second is the y direction. The array will be drawn as data pointsevenly spaced over an x/y rectangle. Each element gives the height at the correspond-ing point.

Adjusting the Contour LinesZplot displays a surface by drawing “contour lines” along the surface. SetMesh3 controlsthe number of lines for drawing mesh plots. SetZlines3 sets the number of contour linesfor Zplot, and SetZseg3 sets the number of segments in each contour line. Figure 40.17shows contour lines and segments for the Zplot3 sample program.

Figure 40.17: Adjusting Contour Lines.

ZmeshZmesh draws a graph of the function F(x,y) by drawing contour lines along x and y direc-tions. You must define an external numeric function F(x,y). Zmesh will draw this func-tion’s value over x values ranging from the viewing volume’s xmin to xmax and y valuesranging from ymin to ymax.

Page 32: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

Zmesh will use the current viewing volume, camera angle, viewing distance, and soforth, when graphing the function. You may use it with any kind of perspective or par-allel view. Use SetMesh3 to adjust the fineness of the covering mesh.

Figure 40.18: A Function Plotted with Zmesh — The Zmesh3 Program.

ZmeshRect (xmin, xmax, ymin, ymax)ZmeshRect is like Zmesh except that you supply the xmin, xmax, ymin, and ymax rect-angle instead of using the viewing volume’s x-y range.

ZplotZplot draws a graph of the function F(x,y) by drawing contour lines along either the x ory direction. You must define an external numeric function F(x,y). Zplot will draw thisfunction’s value over x values ranging from the viewing volume’s xmin to xmax and y val-ues ranging from ymin to ymax.

Zplot will use the current viewing volume, camera angle, viewing distance, and so forth,when graphing the function. Use it with any kind of perspective or parallel view.

Zplot will choose to run contour lines along either the x or y direction, depending onwhich looks best. It prefers to use contours parallel to the x axis but will use y contourswhen the view runs “down” the x direction (i.e., more or less parallel to the x axis). SeeFigure 40.17 for a sample image.

Contour Plots 31

01/01

Page 33: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

! A simple Zplot.!library “3dlib”call PersWindow(-pi, pi, -pi, pi, -1, 1)call Zplotend

def F(x, y) = Sin(Sqr(x^2+y^2))

ZplotRect (xmin, xmax, ymin, ymax)ZplotRect is like Zplot except that you supply the xmin, xmax, ymin, and ymax rectangleinstead of using the viewing volume’s x-y range.

ZplotSub (xmin, xmax, ymin, ymax, xy, nlines, step)ZplotSub is a subroutine used by Zplot and ZplotRect. It’s more general than Zplot butharder to use. You probably won’t want to use it.

Like Zplot, ZplotSub graphs a function F(x,y) where the x values range from xmin toxmax and the y values range from ymin to ymax. The xy parameter controls the contourlines: xy=0 means the contour lines parallel the x axis, xy=1 means they parallel the yaxis.

Nlines controls the number of contour lines. Step controls how many line segments areused to draw each contour line. As step gets bigger, the graph gets more accurate butslower. As it gets smaller, the graph looks more jagged but is faster.

Warning: ZplotSub does not always draw the contour lines in the right order! It rangesboth the x and y values from their minimums to their maximums but this order is wrongfor many views. The output will look peculiar. Furthermore, it does not correctly han-dle some cases where the view looks “down” the contour lines — i.e., runs more or lessparallel to the contours. For these reasons, you should probably stick to the Zplot rou-tine.

! A simple ZplotSub.!library “3dlib”call PersWindow(-pi, pi, -pi, pi, -1, 1)call SetCamera3(0, -5, 3)call ZplotSub(0, -pi, pi, -pi, pi, 0, .5, 25)end

def F(x, y) = Sin(Sqr(x^2+y^2))

32 3-D Graphics Toolkit

01/01

Page 34: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

SplotSplot draws the surface of a function F(x,y) running the values of x and y from the view-ing volume’s xmin to xmax and ymin to ymax.

It ignores points which do not have values, i.e., those for which F(x,y) causes an excep-tion. And it “clips” contour lines that extend outside of the viewing volume.

This makes Splot suitable for viewing functions such as half spheres, which are notdefined over an entire rectangle, and parabolic functions, which are hard to understandif not clipped to the viewing volume.

Unlike Zplot, Splot does not hide hidden surfaces.

! A simple Splot on a half-sphere.!library “3dlib”call PersWindow(-2, 2, -2, 2, 0, 1)call Splotend

def F(x, y) = Sqr(4 - (x^2+y^2))

Zplot versus SplotThe program Zsplot3, on your disk, shows how you can use either Zplot or Splot to grapha “tricky” function. Figure 40.19 shows the output for both an equation of a half-sphere,and one of a quadratic surface.

Figure 40.19. Zplot vs. Splot on some Tricky Cases.

Contour Plots 33

01/01

Page 35: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

Both functions are clipped to the viewing volume; points outside the 3D window are notshown. The half-sphere equation has many undefined points – those off the sphere’s surface.

Splot automatically handles clipping and undefined points. You can also plot such sur-faces with Zplot, provided that you carefully write the function F so it clips points andhandles the undefined points.

Zsplot3 uses a function F which can draw 4 different functions. Two of them, public fn = 0 or2, are used for calls from Zplot. Notice how the function with fn = 0 defines a value of 0 for allundefined points on the sphere and clips z values greater than 1. If you don’t take this spe-cial care, F would give errors with “Square root of a negative number” and would draw func-tion surfaces extending outside the viewing volume. F with fn = 2 also clips z values.

Sometimes Zplot works better and sometimes Splot works better. Use whichever youthink works best for your problem.

Graphing Multiple FunctionsThe short program below shows how you can use a PUBLIC variable to plot several dif-ferent functions in one program:

! Show how to graph multiple functions.!library “3Dcont”public fn

open #1: screen 0, .5, .1, .9let fn = 1call PersWindow(-pi, pi, -pi, pi, -1, 1)call Zplot

open #2: screen .5, 1, .1, .9let fn = 2call PersWindow(-pi, pi, -pi, pi, -1, 1)call Zplotend

def F(x, y)declare public fnif fn = 1 then

let F = sin(x+y)else

let F = sin(x)^2+cos(y)^2end if

end def

34 3-D Graphics Toolkit

01/01

Page 36: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

For another example, see the Zsplot3 program on your disk. It draws four differentfunctions in four windows.

Tplot (zplane)Tplot draws a “topographic map” of the function F(x,y). This map is flat — it’s a two-dimensional projection of the function, as seen from above. You must define the exter-nal numeric function F(x,y).

Tplot will draw this function’s value over the x values ranging from viewing volume’sxmin to xmax and y values ranging from ymin to ymax. F is sampled at a rectangularmesh of points; use SetMesh3 to control the number of points in the mesh.

The flat map is drawn with its z coordinate at zplane.

Tplot uses the current viewing volume, camera angle, distance, and so on, when graph-ing. You can use it with perspective or parallel views. See the Topo3 program for anexample.

Figure 40.20. A Topographic Map with Zplot — The Topo3 Program.

ZbarZbar is like Zplot or Zmesh, but plots the function values as a 3-D bar chart. SetMesh3controls the number of bars used for the chart.

You can control the colors and shapes of the bars by SetBarColor3 and SetBarSize3. Seetheir descriptions for more detail.

Contour Plots 35

01/01

Page 37: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

Zbar does not usually give very interesting graphs; it’s included mainly for the sake ofcompleteness. The corresponding routine for graphing data, ZbarData, is more useful.

ZmeshData (data(,), x1, x2, y1, y2)ZmeshData is like Zmesh but plots the image of data points instead of a function’s sur-face. You must pass a collection of z values in the data(,) array. They will be drawn aspoints evenly spaced over the interval x1 to x2 and y1 to y2.

In general, you should have at least 20 elements in each dimension of data for the Z-mesh to look good.

ZplotData (data(,), x1, x2, y1, y2)ZplotData is like Zplot but plots the image of data points instead of a function’s surface.You must pass a collection of z values in the data(,) array. They will be drawn as pointsevenly spaced over the interval x1 to x2 and y1 to y2.

In general, you should have at least 20 elements in each dimension of data for the Z-plotto look good.

ZbarData (data(,), x1, x2, y1, y2)ZbarData draws a 3-D bar chart of the data() elements. It evenly spaces the bars overthe indicated x-y region. The base of each bar is at z = 0; the height of each bar is givenby the corresponding element of the data() array.

You can use SetBarColor3 to control the colors of the sides and tops of the bars. Properuse of SetBarColor3 and SetColor3 let you get bars of different colors depending on theirheights. The edges of the bars are always outlined in the current color.

You can also use SetBarSize3 to change the “footprint” of each bar, that is, the size andshape of each bar’s horizontal cross-section.

Figure 40.21 shows samples of ZbarData and TplotData.

36 3-D Graphics Toolkit

01/01

Page 38: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

Figure 40.21. ZbarData and TplotData — The ZDATA3 Program.

TplotData (data(,), x1, x2, y1, y2, zplane)TplotData draws the topographic map of a set of data points. You must pass a collectionof z values in the data(,) array. They will be taken as points evenly spaced over the inter-val x1 to x2 and y1 to y2, and the contour map will be drawn appropriately in the planedefined by z = zplane.

In general, you should have at least 10 elements in each dimension of data for the T-plotto look good. Figure 40.21 shows TplotData and ZbarData in action.

SetMesh3 (xmesh, ymesh)SetMesh3 controls the number of sampling points used for Zmesh, Zbar, and Tplot. Thexmesh and ymesh parameters control the number of sampling intervals in the x and ydirections respectively.

For example, if xmesh = 10 and ymesh = 15, TopoPlot divides the map into 150 rectangleswhen drawing the contours. As these numbers get higher, your maps will get more accu-rate– but will take longer to compute. Values between 10 and 30 are usually a good com-promise.

If either number is less than 1, SetMesh3 uses 1 instead.

AskMesh3 (xmesh, ymesh)AskMesh3 is the opposite of SetMesh3. It returns the current number of samplingintervals.

Contour Plots 37

01/01

Page 39: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

SetZlines3 (n)SetZlines3 controls the number of contour lines used in Zplot or Splot. Larger values ofn give finer drawings but take longer to compute and display.

If n is less than 2, SetZlines3 uses 2 instead.

AskZlines3 (n)AskZlines3 is the opposite of SetZlines3. It returns the current number of contour lines.

SetZseg3 (n)SetZseg3 controls the number of line segments used to draw one contour line in Zplot orSplot. Larger values of n give finer drawings but take longer to compute and display.

If n is less than 1, SetZseg3 uses 1 instead.

AskZseg3 (n)AskZseg3 is the opposite of SetZseg3. It returns the current number of intervals usedwhen drawing a contour line.

SetTlines3 (n)SetTlines3 controls the number of topographic contour lines used in Tplot. For instance,n = 8 gives 8 dividing lines between the lowest and highest points on the map. Largervalues of n give more detail but can be harder to read.

If n is less than 1, SetTlines3 uses 1 instead.

AskTlines3 (n)AskTlines3 is the opposite of SetTlines3. It returns the current number of topographiccontour lines.

SetBarSize3 (x, y)SetBarSize3 controls the “footprint” of the bars used for Zbar and ZbarData. The x andy parameters control the proportion of the x-y graphing rectangle that will be used.

For example, if x = 1 and y = .1, then the resulting bars will be long and thin. The entirex interval will be used, so bars will touch each other along the x direction. Only a smallfraction of each y interval will be used, so the bars will be thin in that direction.

Bars sizes are preset to .6 in each direction. If either number is less than .1 or greaterthan 1, SetBarSize3 will use .1 or 1 instead.

38 3-D Graphics Toolkit

01/01

Page 40: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

AskBarSize3 (x, y)

AskBarSize returns the current “footprint” of the bars used for Zbar and ZbarData. It’sthe opposite of the SetBarSize3 routine.

SetBarColor3 (a$, b$, c$)SetBarColor3 controls the colors used for the sides of bars drawn by Zbar or ZbarData.You pass three colors, one for each of the three visible sides.

Each color can be a name such as “red.” Or it can be a number such as “3.” Most flexibly,you can pass the null string as a color. Then the Zbar routines will use AskColor3 to findthe color for this size. Thus you can set a bar’s color depending on its height.

The colors are preset to “0” so the bars are drawn in the background color. (The Zbar rou-tines also frame the edges of the bars, so the bars are visible.)

AskBarColor3 (a$, b$, c$)AskBarColor3 returns the current colors used for shading bars. It’s the opposite of theSetBarColor3 routine.

SetColor3(s$)SetColor3 controls the coloring used for Zmesh, Zplot, Splot, and TopoPlot. It lets youshow different altitudes in different colors. The parameter s$ indicates the dividinglines between colors. A typical color scale might be:

“red [0] blue [1] green”

This means that all z values ≤ 0 should be shown in red. Values ≤ 1 should be shown in blue.And all other values should be shown in green. Roundoff error is always lurking in com-puters so you may want to fudge dividing values a little — use [0.1] instead of [0] etc.

The colors can be True BASIC color names, such as “red” or “yellow,” or can be color num-bers such as “1” or “25.”

If you pass the null string, the function plotting routines go back to using the currentcolor for the graph. See the Topo3 program for an example.

Exceptions:43 Bad color scale: xxx

AskColor3(s$)AskColor3 returns in s$ the last color scale you’ve used. If you haven’t called SetColor3yet, it returns ““.

Contour Plots 39

01/01

Page 41: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

Oblique ProjectionsThis section describes how to get “oblique” projections. These are special forms of par-allel projections that change the projection direction so that it’s no longer perpendicularto the view plane.

Cavalier and cabinet projections are two common kinds of oblique projections, and the3-D Graphics Toolkit gives them special support.

Cavalier3 Set a cavalier projection.Cabinet3 Set a cabinet projection.Oblique3 Set an oblique projection.

Using Oblique ProjectionsOblique projections are, in a sense, distortions of parallel “head-on” views. The camerafaces one side of an object, but the resulting image also shows another side and the topor bottom. Figure 40.22 illustrates.

Figure 40.22. Oblique Projections — The Project3 Program.

Before you use any oblique projection, set up the camera so that only one face of the view-ing volume is visible — that is, so that the view plane is parallel to one side of the view-ing volume. Otherwise the results look ugly and are hard to decipher.

40 3-D Graphics Toolkit

01/01

Page 42: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

A Note on Windows...If you refer back to Figure 40.8, you’ll see that oblique projections display the image ona different part of the view plane than do “head-on” parallel projections.

The routines described in this section automatically change the view plane window sothat it shows the new, oblique image. You’ll notice, though, that the new windowcoordinates are not “nice” numbers, and that the origin no longer lies at the center ofthe window.

...And a Note on Aspect RatiosFinally, all these routines assume that your current window on the screen has a 1:1aspect ratio — that is, that a square drawn in the window would look square on thescreen. In general, your current window will not have a 1:1 aspect ratio, and so angleswill not come out precisely.

To correct the aspect ratio, juggle either the horizontal or vertical window coordinatesuntil the result looks right.

Cavalier3 (angle)Cavalier3 changes the current parallel projection direction to make a cavalier projec-tion. The current reference point and camera position are unchanged but the projectiondirection is altered so that it’s no longer perpendicular to the view plane.

The angle must be given in degrees; for example, 90 gives a right angle. (Remember thatyour current window’s aspect ratio may distort angles; see the beginning of this sectionfor advice.)

! Show off a cavalier projection.!library “3dlib”call ParaWindow(0, 1, 0, 1, 0, 1)call Cavalier3(45)call MarkedCubeend

Exceptions:40 Can’t do this with perspective view.

Cabinet3 (angle)Cabinet3 changes the current parallel projection direction to make a cabinet projection.The current reference point and camera position are unchanged, but the projectiondirection is altered so that it’s no longer perpendicular to the view plane. See Cavalier3above for information about the angle.

Oblique Projections 41

01/01

Page 43: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

! Show off a cabinet projection.!library “3dlib”call ParaWindow(0, 1, 0, 1, 0, 1)call Cabinet3(45)call MarkedCubeend

Exceptions:40 Can’t do this with perspective view.

Oblique3 (angle, xratio, yratio)Oblique3 gives access to a general oblique projection. As with the Cavalier3 andCabinet3 routines, you must pass the angle for the oblique projection (in degrees). Youmust also pass an xratio and yratio which control how the z dimension appears to beshifted on the view plane.

Cavalier3 passes 1 for both the xratio and yratio. Cabinet3 passes 1/2 for both. In gen-eral, the bigger you make the ratios, the “deeper” the result looks. The smaller you makethem, the “shallower” it looks. The xratio controls the horizontal shifting of depth; theyratio controls its vertical shifting.

(Remember that your current window’s aspect ratio may distort angles; see the begin-ning of this section for advice.) The angle will also be distorted if you give different num-bers for xratio and yratio.

! Show a shallow marked cube.!library “3dlib”call ParaWindow(0, 1, 0, 1, 0, 1)call Oblique3(45, .3, .3)call MarkedCubeend

Exceptions:40 Can’t do this with perspective view.

42 3-D Graphics Toolkit

01/01

Page 44: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

Scaled ViewsThese routines create scaled perspective and parallel windows.

ScalePersWindow Create scaled perspective window.ScaleParaWindow Create scaled parallel window.

What is Scaling?The PersWindow and ParaWindow routines, described in earlier sections, treat each ofthe x-y-z dimensions equally. That is, if you define a viewing volume which is 100 unitsby 1 unit by 1 unit, it will look like a long, thin rod.

Sometimes you need to independently scale each dimension; you want the 100 x 1 x 1 vol-ume to look like a cube rather than a long, thin rod.

ScalePersWindow and ScaleParaWindow are like PersWindow and ParaWindow exceptthat they automatically scale each dimension. The viewing volume will always look likea cube on your screen. Figure 40.23 illustrates the Scale3 program on your disk; itshows an unscaled and scaled view of a 10 x 10 x 1 volume.

Figure 40.23. Scaled vs. Unscaled Views — The Scale3 Program.

ScalePersWindow (x1, x2, y1, y2, z1, z2)ScalePersWindow works exactly like PersWindow except that it creates a scaled view ofthe viewing volume. The viewing dimensions will be normalized so they all appear to bethe same length.

Oblique Projections 43

01/01

Page 45: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

ScalePersWindow is appropriate for perspective views of some volume which has verydifferent measures used along the x, y, and z axes. See the Scale3 program for an example.

Exceptions:33 3-D window minimum = maximum.

ScaleParaWindow (x1, x2, y1, y2, z1, z2)ScaleParaWindow works exactly like ParaWindow, except that it creates a scaled viewof the viewing volume. The viewing dimensions will be normalized so they all appear tobe the same length.

ScaleParaWindow is appropriate for parallel views of some volume which has very dif-ferent measures used along the x, y, and z axes.

Exceptions:33 3-D window minimum = maximum.

44 3-D Graphics Toolkit

01/01

Page 46: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

Advanced Viewing RoutinesThis section describes advanced routines that let you independently manipulate thecamera angle, distance, view plane normal, and “up” direction. Since it’s tricky toproperly coordinate these related parameters, beginners should probably stick to theSetCamera3 routine which gives an easy interface to them.

However, advanced users may wish to set the parameters separately for various specialeffects.

SetRefPt3 Set reference point.SetViewPlane3 Set view plane normal.SetDistance3 Set viewing distance.SetScale3 Set scale for flat image.SetCP3 Set center of perspective.SetProj3 Set projection plane normal.SetUp3 Set “up” direction.

AskRefPt3 Ask reference point.AskViewPlane3 Ask view plane normal.AskDistance3 Ask viewing distance.AskScale3 Ask scale for flat image.AskCP3 Ask center of perspective.AskProj3 Ask projection plane normal.AskUp3 Ask “up” direction.

SetRefPt3 (x, y, z)SetRefPt3 sets the new reference point for viewing. It does not change the view planenormal, viewing distance, or any other related parameter.

If you want to change all these parameters together, try the SetCamera3 routine. It lets youset the camera position and then picks plausible values for all three related parameters.

Exceptions:38 View plane is behind center of projection.

SetViewPlane3 (dx, dy, dz)SetViewPlane3 sets a new view plane normal, that is, changes the direction in which theview plane is tilting.

This routine can give lots of different errors. “View plane normal is zero” means that dx,dy and dz are all zero — hence no direction has been given. “Can’t set view plane alongnormal” means that you’re trying to adjust the view plane so that it intersects the refer-

Advanced Viewing Routines 45

01/01

Page 47: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

ence point. “View plane is behind center of projection” probably means that you’ve gotthe view plane pointing away from the reference point.

Exceptions:34 View plane normal is zero.35 Can’t set view plane along normal.38 View plane is behind center of projection.

SetDistance3 (d)SetDistance3 sets the viewing distance, i.e., the distance from the reference point to theprojection plane. It does not affect the view plane normal, and so keeps the same “cam-era angle” and simply moves the camera closer to, or farther from, the reference point.

SetDistance3 normalizes the resulting image so it always appears the same size on yourscreen. (Thus it has no effect for parallel views, and simply changes the degree of per-spective for perspective views.) To make the image larger or smaller, use SetScale3.

Exceptions:38 View plane is behind center of projection.42 Viewing distance is zero.

SetScale3 (h, v)SetScale3 controls the scale of the flat image displayed on your screen. The two param-eters h and v control horizontal and vertical scaling, respectively.

By default, both horizontal and vertical scales are set to 1. This gives a clear picturewhere every part of the 3-D image is visible. To magnify the image, pass numbersgreater than 1. To shrink the image, pass numbers less than 1. For example:

CALL SetScale3(2,1.5)

expands the flat image by a factor of 2 horizontally and 1.5 vertically.

SetCP3 (x, y, z)SetCP3 sets a new center of perspective for perspective views. It does not move the cam-era at all.

Exceptions:38 View plane is behind center of projection.41 Can’t do this with a parallel view.

46 3-D Graphics Toolkit

01/01

Page 48: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

SetProj3 (dx, dy, dz)SetProj3 changes the direction of the parallel projection lines. (Hence it can only be usedwith parallel projections.) The direction is specified as an x-y-z vector.

By default, projection lines leave the reference point and strike the view plane at a rightangle. However, you may change this angle as you wish, so long as the projection linesare not parallel to the view plane.

The view plane itself is not affected by SetProj3. Because the projection lines are nolonger coming at the same angle, the projected image will appear to shift along the viewplane as you change the projection lines’ direction. In fact, the image may shift outsideof the current viewing window and no longer be visible.

See the 3-D Theory section for a brief description of the effects of changing projection linedirections.

Exceptions:36 Parallel projection direction is zero.37 Projection is parallel to view plane.40 Can’t do this with perspective view.

SetUp3 (dx, dy, dz)SetUp3 controls the “camera rotation.” In other words, it controls how the projectedimage is rotated to appear on the computer’s screen. By default, the 3-D GraphicsToolkit arranges the image so that the x axis is horizontal and the z axis is vertical, butthis routine lets you change that.

The three arguments dx, dy, and dz are taken as a vector which describes the camera’snew orientation.

In the simplest cases, CALL SetUp3(1,0,0)

makes the x axis vertical, CALL SetUp3(0,1,0)

makes the y axis vertical, and CALL SetUp3(0,0,1)

makes the z axis vertical. If you use -1 instead of 1, the result will be upside down.

If you try to arrange the camera so the view plane intersects the reference point, you getthe “Can’t set view plane along normal” error.

Exceptions:35 Can’t set view plane along normal.39 View up direction is zero.

Advanced Viewing Routines 47

01/01

Page 49: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

AskRefPt3 (x, y, z)AskRefPt3 returns the current coordinates (x, y, z) of the reference point.

AskViewPlane3 (dx, dy, dz)AskViewPlane3 returns the current “view plane normal” in dx, dy, and dz. These num-bers will have been normalized to make a unit vector; however, the direction of the vec-tor is unchanged from that which you set by SetViewPlane3.

AskDistance3 (d)AskDistance3 returns the current viewing distance in d.

AskScale3 (h, v)AskScale3 returns the current horizontal and vertical scaling factors. If you haven’tcalled SetScale3, both numbers will be 1.

AskCP3 (x, y, z)AskCP3 returns the current center of perspective in x, y, and z. It gives an error if thereis no center of perspective — i.e., you are using a parallel projection.

Exceptions:41 Can’t do this with a parallel view.

AskProj3 (dx, dy, dz)AskProj3 returns the current parallel projection line direction in dx, dy, and dz. Thesenumbers will have been normalized to make a unit vector but the direction of the vectoris unchanged from that which you set by SetProj3.

Exceptions:40 Can’t do this with perspective view.

AskUp3 (dx, dy, dz)AskUp3 returns the current “up” direction for the camera in dx, dy, and dz. These num-bers will have been normalized to make a unit vector but the direction of the vector isunchanged from that which you set by SetUp3.

48 3-D Graphics Toolkit

01/01

Page 50: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

Sample ProgramsYour disk includes a selection of sample programs to help you understand how to use the3-D Graphics Toolkit. They’re ready to go; just call them up and run them.

Cube3Cube3 displays the unit cube in a perspective view. It runs in an infinite loop asking youto supply a new “camera” location and displaying the view from that location.

Camera positions like (3, 4, 5) give a fairly bland view of the cube. Try moving the cam-era right to the edge of the cube to see how distorted the cube can look if the camera’s tooclose to the object. Move far away and watch how the perspective effect begins to growless.

Move the camera inside the unit cube — say, to (.7, .7, .7) — and see how things lookwhen you draw lines behind the camera. Since the 3-D Graphics Toolkit does not cliplines behind the camera, they appear as seemingly random lines drawn across the view-ing surface.

Finally, change PersWindow to ParaWindow and experiment with a parallel projection.Notice that moving closer to the object, or farther away, does not affect parallel views.

Figure 40.24: Cube3 Program

Sample Programs 49

01/01

Page 51: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

House3The House3 program draws a perspective view of a “house.” It uses various graphicsprimitives such as line-drawing, rectangles, and circles.

Figure 40.25: Project3 Program

Project3The Project3 program opens several True BASIC windows and displays various per-spective and parallel views of a house within the windows. It shows how to coordinate 3-D graphics and True BASIC windows.

Unlike the built-in True BASIC graphics, each window does not have its own, indepen-dent 3-D window coordinates. Rather, they all share the same 3-D view. You mustswitch 3-D windows explicitly every time you switch to another True BASIC window.

Oblique3The Oblique3 program opens four True BASIC windows and displays a different par-allel projection in each window. The top two views are both axonometric projections; theleft is “head on” and the right is from above and to one side.

The bottom two views are both oblique projections, taken from the same camera positionas the top left view. The bottom left is a cavalier projection; the bottom right is a cabinetprojection.

50 3-D Graphics Toolkit

01/01

Page 52: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

Figure 40.26: Oblique3 Program

Bars3The Bars3 program displays a three-dimensional bar chart in a perspective view. Ituses the GridZ3 subroutine to get an underlying grid and the Block3 routine to draweach bar.

Notice how Bars3 alters the viewing parameters to get a more dramatic display. Itplaces the camera rather low and then changes the reference point so it’s no longer in thecenter of the row of bars. Finally, it resets the 2-D window coordinates to enlarge theresulting view. (As a result, the image spills off the edges of the screen.)

Blocks3The Blocks3 program is somewhat like Bars3 except that it displays a cluster of blockslaid out over a grid. The image resembles a city block seen from the air.

Blocks3 uses a “painter’s algorithm” to give a realistic view of the blocks. In less fancywords, it draws the rearmost blocks first, then nearer blocks. Thus the blocks in fronthide the blocks behind.

Zmesh3The Zmesh3 program plots a perspective image of a rather peculiar F(x,y). It uses a veryfine mesh setting so be patient!

Sample Programs 51

01/01

Page 53: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

Zplot3The Zplot3 program shows off the Zplot subroutine. It plots the image of a photogenicfunction as seen in perspective from a certain camera position. Then it lets you set a newcamera position, and displays the function from that angle.

Notice how the Zplot subroutine will automatically switch between x and y contourlines, depending upon the camera location.

Zsplot3The Zsplot3 program shows off the Splot subroutine. It also shows how various “tricky”functions — which aren’t defined over an entire rectangle — can be handled with theZplot subroutine. See the Contour Plots section for more information.

Topo3The Topo3 program shows the topographic map for a complicated function with twobumps. It also shows a Zplot of the function to make the topographic map clearer.

In addition, Topo3 uses SetColor3 to draw different heights in different colors. Thisaccentuates the features of the function’s surface.

Zdata3The Zdata3 program shows a ZplotData image of a large number of data points. If youhave enough patience, you might change the program to use ZmeshData or ZbarDatainstead. (Both are slower than ZplotData.)

Zbar3The Zbar3 program shows a ZbarData plot of a 17 x 17 data set, superimposed atop atopographic plot of the same data.

The two layers have been accentuated by using Block3 to add solid blocks below the layers.

Scale3The Scale3 program shows the difference between a scaled and unscaled view of thesame volume. Both views show a volume that ranges from 0 to 10 in both the x and ydimensions and from 0 to 1 in the z dimension.

Notice that the unscaled view preserves relative sizes, making the result look very shal-low. The scaled view exagerates the z dimension to bring it into balance with the x andy dimensions.

See the Scaled Views section for more information on getting scaled viewing volumes.

52 3-D Graphics Toolkit

01/01

Page 54: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

Making 3-D “Movies”

The Record and PlayBack sample programs let you create and show 3-D “movies.”These movies are created by animation: Record draws a movie one frame at a time andstores the frames in a file on disk. PlayBack reads this file and shows the framesquickly to give the impression of action.

Call up the PLAYBACK program and run it. When it asks for a file name, reply:imagdata.

It will show a pre-recorded movie of the “house” picture. (If your computer cannot han-dle the movie’s recording mode, PlayBack will give an error. If this happens, just callup Record and run it instead. This re-records the movie in your current mode and thenplays that.)

Movies require lots of memory — at least 100 to 200k on most computers — so you maynot be able to run a movie if you do not have large amounts of memory available.

RecordRecord draws a movie frame by frame. To make a new movie, you must rewrite parts ofthe Record sample program. It consists of one main loop which draws new frames fromvarious camera viewpoints. For each frame, it picks a new camera location and drawsthe “house” picture from that camera angle. Then it uses BOX KEEP to grab the frame.Finally it stores the frames in a movie file, ImagData, and chains to PlayBack passingthe file name. Then PlayBack shows the movie.

PlayBackPlayBack shows a movie. It opens a movie image file, reads all the frames into mem-ory, and then displays the frames one after another. It shows the film as a “loop” so thatit goes back to the first frame after showing the last one.

Note how PlayBack includes a PROGRAM statement. This way, it can receive themovie file name if some other program (such as Record) chains to it. Otherwise it sim-ply asks the user for a movie file name.

PlayBack delays about .05 seconds after showing each frame. Otherwise the moviegoes too fast.

Making 3-D “Movies” 53

01/01

Page 55: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

The Movie File FormatMovie files, such as ImagData, are stored as True BASIC record files. They containmore than movie frames. The first record contains the following items in a packedformat:

• Number of frames.• Frame’s screen xmin, xmax, ymin, ymax.• Recording mode

The remaining records are all movie frames. This format is a little more general than isneeded for these simple 3-D movies. But it allows later expansion to more advancedmovie systems.

This format is different from Version 1.0 movie files. We’ve had to add the recording modesince some computers cannot play back movies recorded in different modes. For instance,IBM PCs with Hercules cards can’t play back the standard IBM PC graphics mode.

If You Want to Experiment More...Movies require a great deal from your computer. A simple movie, like the one on yourdisk, needs a lot of memory and processing speed to run. The size of the frames, and thenumber of frames, have been carefully chosen to fit in a reasonable amount of memoryand run without too much flicker. On computers with “modes,” we’ve chosen the graph-ics mode that requires the least amount of memory for each frame.

Nevertheless, some computers can handle bigger movies and show them faster. Youmay want to experiment with the frame sizes and number of frames to see how thingswork on your computer. Just adjust the window size and number of frames in Recordand then run it.

Remember that PlayBack pauses for .05 seconds between each frame. Instead of paus-ing, you can use this time to display a frame from another movie on another part of thescreen. Experiments have shown that the Macintosh Plus, for instance, can play threemovies simultaneously without annoying flicker. (Each movie frame, though, is a bitsmaller than the one used by Record.) You may wish to experiment with running sev-eral 3-D views simultaneously.

Finally, it’s not absolutely essential to keep the entire movie in memory. If you have acomputer with a small memory or want to show very long movies, you can modifyPlayBack to read frames one by one from disk (rather than read them all intomemory). This makes movies considerably slower but allows much longer and morecomplicated movies.

54 3-D Graphics Toolkit

01/01

Page 56: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

3-D Transformations

This section describes, very broadly, how the 3-D Graphics Toolkit creates projections.This subject is complicated and you should read any of the books listed in the 3-DTheory section if you want to learn more about 3-D projections.

There are two major parts to a 3-D graphics package. One part sets up a view and read-ies all the information for making projections. The other part actually draws images. Ituses the information created by the viewing set-up routines.

The set-up routines take all the information about a viewing position — reference point,camera position, view plane normal, etc. — and encode it into a “transformation matrix.”This is explained at length below. Whenever the viewing parameters are changed, thetransformation matrix must be recomputed.

The drawing routines use this transformation matrix to project 3-D images onto theview plane.

Absolute and Camera Coordinate SystemsTwo different coordinate systems are used in a projection. The first is the “absolute”coordinate system with its origin at (0,0,0). The second is the “camera” coordinate sys-tem with its origin at the camera position.

In the camera coordinate system, the x-y plane acts as the view plane. The z coordinateis simply the distance from the view plane. In this coordinate system, the center of theview plane — the camera position — is at the origin.

The origins of these two systems (reference point and camera position) will never coin-cide. And in general the axes for these two coordinate systems will not coincide. Usuallythey will not even be parallel. Instead, the camera view plane will be at some 3-dimen-sional angle to the absolute coordinate system.

The projection package must first, therefore, transform the absolute coordinates intocamera coordinates. This requires translating the absolute origin to the camera coordi-nate origin and then rotating each axis to bring it into alignment.

Once the 3-D Graphics Toolkit has transformed points from the absolute system to thecamera system, it can draw images on the view plane. For most parallel projections, itcan draw the image’s line by simply ignoring the z dimension (distance from the cam-era). For perspective projections, the package must scale the x-y size by the z coordinateso farther objects appear smaller.

3-D Transformations 55

01/01

Page 57: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

Transformation MatricesInternally, most graphics packages work with transformation matrices. These contain,in a concise form, all the calculations which must be applied to a point to give its pro-jected image. Compare these matrices with their 2-D equivalents shown in Section __).

Translation MatrixThe translation matrix shifts the absolute reference point to the camera position. If dx,dy, and dz are the x, y, and z distances between the reference point and the camera loca-tion, then the translation matrix is:

Translation Matrix

1 0 0 0 0 1 0 0 0 0 1 0 dx dy dz 1

Rotation MatricesOnce the origin has been moved to the camera location, the package must re-orient allthree axes. In general this requires 3 “rotations”: each of the x, y, and z axes must bebrought into line.

Assuming that you need to rotate the axes by angles ax, ay, and az respectively, the threerotation matrices are:

X-axis Rotation Matrix 1 0 0 0 0 cos(ax) sin(ax) 0 0 -sin(ax) cos(ax) 0 0 0 0 1

Y-axis Rotation Matrix cos(ay) 0 -sin(ay) 0 0 1 0 0 sin(ay) 0 cos(ay) 0 0 0 0 1

Z-axis Rotation Matrix cos(az) sin(az) 0 0 -sin(az) cos(az) 0 0 0 0 1 0 0 0 0 1

56 3-D Graphics Toolkit

01/01

Page 58: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

Composition of TransformationsThese transformations could be applied one after another: first the translation, thenthree separate rotations. However, the transformations can also be “composed” into asingle operation — which is much more efficient than performing four operations.

The transformations are composed by multiplying the transformation matrices in order.Thus the final transformation matrix is computed by:

transform = Translate(dx,dy,dz) * RotX(ax) * RotY(ay) * RotZ(az)

This transformation matrix can be computed once the camera position and referencepoint are known. Hence the 3-D Graphics Toolkit computes the matrix once wheneveryou fix the viewing parameters. Then it uses the matrix whenever you display an image.

This toolkit’s MakeViewPlaneTransformation subroutine creates and composes thetransformation matrices.

(For efficiency, the transformation matrix is not kept as an actual True BASIC 4x4matrix but rather as a related set of variables. This removes the small time necessaryfor True BASIC to calculate and check subscripts. And since the last columns of allmatrices are invariably [0, 0, 0, 1], this column is ignored.

It has no effect on the calculations, so why waste time doing useless multiplications andadditions with its elements?)

The Final TouchesAfter translating a point from absolute coordinates to camera coordinates, we mustfinally project it onto the view plane. This is done in different ways for perspective andparallel projections.

Perspective projections must scale the resulting image by the distance from the viewplane. This makes farther objects look smaller. In the camera coordinate system, the zcoordinate is simply the distance from the view plane, so the final perspective transfor-mation is just a division by the z coordinate.

Parallel projections do not scale the image based on distance. In fact, the z coordinate isusually ignored. However, the z coordinate is used for oblique projections, and so thefinal transformation uses the view plane’s “tilt” and the z coordinates to get the projectedimage.

Both of these final transformations can be encoded within the transformation matrix.The 3-D Graphics Toolkit, however, keeps them as separate operations. This toolkit’sTransform subroutine transforms a 3-D point to its 2-D image. It uses the transforma-tion matrix to convert from absolute to camera coordinates and then applies the finaltouches as described in this section.

3-D Transformations 57

01/01

Page 59: Introduction - True BASIC · Introduction The True BASIC 3-D Graphics Toolkit fully supports both perspective and parallel pro- jections with simple and useful defaults that make

58 3-D Graphics Toolkit

01/01