THE WAITE GRO U-P. YOUR OWN LD INCLUDES SAMPLE FLIGHT fe] SY]LV]Wy AND DEMOS LONI DRA SIMULATOR USING 00P MICHAEL RADTKE CHRISTOPHER LAMPTON of \ Press™ Waite Group A Division of Sams Publishing Corte Madera, (A Publisher: MitchellWaite Editor-in-Chief: Charles Drucker Acquisitions Editor:Jill Pisoni Editorial Director:John Crudo ManagingEditor: Andrea Rosenberg Content Editor: Harry Henderson CopyEditor: Tynan Northrop Technical Reviewer: André LaMothe Production Director:Julianne Ososke Production Manager: Cecile Kaufman Cover Design: Sestina Quarequio Cover Illustration: © Westlight Chapter Opener Art: © Westlight Hlustrations: Ben Long, Larry Wilson Production: Christi Fryday,Judith Levinson © 1996 byThe Waite Group, Inc.® Published by Waite Group Press", 200 Tamal Plaza, Corte Madera, CA94925. Waite Group Press™ isa division ofSams Publishing, Waite Group Press™ isdistributedto bookstores and book wholesalers by Publishers GroupWest, Box8843, Emeryville, CA94662,1- 800-788-3123 (in California 1-510-658-3453). All rights reserved. No part ofthis manual shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, desktop publishing, recording, or otherwise, withoutwritten permission from the publisher. No patent liabili- tfbyroooimsk,atshtsehuemuspeedubowfltihisthheerreiasnnpfodecrmtaauttotiohtnohrecauossnseutamoifnteehdenohinerrfeeoisrnpm.onastiiboinlityconfotarineerdrorhseroerin.omWishsiiloense.veNryeitphreerciasutiaonnyhlaiasbibleiteyntaasksuemneidntfhoerpdraempaagraestionresouftlthinigs All terms mentioned in this book thatareknowntobe trademarks, registered trademarks, or service marks are listed below. Inaddition, termssuspected ofbeing trademarks, registered trademarks, or service marks have been appropriately capitalized. Waite Group Press™ cannotattest to the accuracy ofthis information. Use ofa term in this book shouldnotbe regarded as affecting the validity ofany trade- mark, registered trademark, or service mark. The Waite Group isa registered trademark ofThe Waite Group, Inc. Waite Group PressandThe Waite Group logo aretrademarksofThe Waite Group, Inc. Apple, Apple 11, and Macintosh are registered trademarksofApple Computer Inc. Amiga isa registered trademark of Amiga Corporation. Atari is a registered trademark ofAtari Corporation. Atari 800 and Atari ST are trademarks of Atari Corporation. Borland and Borland C++are registered trademarksof Borland International, Inc. Chuck YeagersAirCombatisatrademarkof Electronic Arergtsi.sterCeodmmtroaddoermeark64oifs aEletcrtardoenmicarkArtos.fAF-m1i9gaSteCaoltrhporFaitgihotner.isDr.aDtorabdb'esmJoaurkrnaolfisMaicrtoraPdroesmearSkofotwfaMrei,lleIrnc.FrFeeamlcoann, 3I.n0c.anEdleTctertornisicarAerttsradise-a marks of Spectrum Holobyte. Flight Simulator, Flight Simulator 2,and Flight Simulator 4are trademarks of SubLOGIC. IBMisa registered trademark of International Business Machines, Inc. Jetfighter 11isa trademarkofVelocity Development. LucasArts Games isa trademark ofLucasArts Entertainment Company, a subsidiary ofLucasfilm Ltd. MegaortressisatrademarkofPacific. MicroProse isa registered trade- mark of MicroProse Software, Inc. Microsoft isa registered trademarkof Microsoft Corporation. Microsoft Flight Simulator isatrademark ol Microsoft Corporation. Secret Weapons ofthe Luftwaffeisatrademarkof LucasArts Games. Sierra Dynamix isatrademarkofSierra On- line. Spectrum Holobyte isa trademark of Sphere, Inc. TRS-80 Model1isa trademark ofRadio Shack, a division of Tandy Corporation. Velocity isatrademarkofVelocity Development. All other productnamesare trademarks, registered trademarks, or service marks of their respective owners, Printed in the United States ofAmerica 96907989910987654321 Library of Congress Cataloging-in-Publication Data Radtke, Michael. Build your own flight sim inC++/ Michael Radtke, Chris Lampton. p. cm. Rev. ed. of: Flights offantasy. 1993. Includes bibliographical references and index. ISBN: 1-57169-022-0 : $39.99 1. Flight simulators--Computer programs. 2. C++(Computer program language) 1. Lampton, Christopher. IL. Lampton, Christopher. Flights offantasy. 111.Title. TL712.5R32 1996 794.8' 75--dc20 69-11089 CIP Dedication Tothecontinued free exchange of ideas on the net. th ‘Message from Publi WELCOME TO OUR NERVOUS SYSTEM is Some people say that the World Wide Web a graphical extension of the information superhighway, just a network ofhumansand machines sending each other long lists ofthe equivalent ofdigitaljunk mail, it I think ismuch mor than that. To metheWeb is nothingless than the nervous sys- tem of the entire planet—mnot just a collection of computer brains connected together, but more like a billion sili neurons entangled and recirculating electro-chemical sig- nals of information and data, each contributing to the birth of another CPU and another Web site. Think ofeach person’ haildisk connectedat onceto every other hard disk on earth, driven by human navigators searching like Columbus for the New World. Seen this way the Web is more ofasuper el tity, a growing, living thing, controlled by the universal human will to expand, to bemore. Yet, unlike a purposeful business plan with rigid rules, the Web expandsiin a nonlineat, unpredictable, creative way that echoes natural evolution. tobe part ofthissy ev 0experience,likeanervein the body, the flow food chain ofthe mind. Your mind. Even more, e ative juices into this rich wine oftechnology. ends ney to any topic from convenience of your own screen. Right now we are focusing on computerto but the stars are the limit on the Web. If you are interested indise finding out more about the Waite ¢ 200 Tamal Plaza < me email with your comments andLwill be happy to HOMEEHVEREEReRFIEDIS respond. Being a prog myself, T love to talk [EEESECaEllS about technology and find : t what our readers are 4I1C5 92T4 R2576 fax looking for. [email protected] Sincerely, ner ETEeH NEw, http: //www.waite.com/waite Mitchell Waite, C.E.O. and Biblisher CREATING THE HIGHEST QUALITY COMPUTER BOOKS IN THE INDUSTRY Waite Group Press Waite Group New Media || el . > Fr i i Come Visit rt ie WA E CO M ER g y IF 1 —WelcometotheWaiteGroupPreassWorldWideWanSite. a“TheWideGmoupPeesi&Horter otabooks Fefi»e Press zeaeSg emt Wa=ite Group mer eaSn A Bement 0S World WEil de Web Si-te wveodtaopsAOYoffoordUT Sennmarete Sh OsEamppCRaOTrEsOiReTTreIPPSocEomoVArRAt(oe0fYMde)Re45 epr Now find all the latest information on Waite Group books at our newWeb eresspAseut site, http://www.waite.com/waite. You'll findan online catalog where you can examine and order any title, review upcoming books, and send email Bto our authors and editors. Ouir FTP site has all ynou need to updateyour book: the a latest program listings, errata sheets, most recent versions of Fractint, POV Ray, Polyray, DMorph, and all the programs featured inour books. So download,talk to Aus, ask questions,Ron http://www.waite.com/waiteA. L The New Arrivals Roomhas all our new books listed by month. Just dlick fora description, Index, Tableof Contents, and linksto authors. The Backlist Room hasallour hookslisted alphabetically. | LT TR EO you'll interact withWaite HEIRNE ETTTa About WEP Links to Cyberspace get you in touchTwith oEther EEE POTCL Links to Cyberspace] and other interesting (IRC The FTPsite contains all 111 Subject OTROTRATGAT RNR [ie IOTdE pages which show description, Index, The Order Roomis where of Contents, and linksto authors. (youecann oerder anyofour World Wide Web: http://www.waite.com/waite Gopher: gopher.waite.com FTP: ftp.waite.com About the Authors Michael Radtke has worked with Waite Group Press for three years in various capacities: technical editor, program- mer and bug shooter. He holds a degree in both Human Organizational Processes and Mathematics from Montclair State University in New Jersey. Involved in software devel- opment since 1982, he has programmed and/or designed various shrink-wrapped software products for entertain- ment, home productivity, and business. When he is not programming, brainstorming, or pulling someones leg, he plays piano for his own enjoyment. Christopher Lampton is the author ofmore than 80 books for readers young and old. These include 20 books on microcomputers and computer programming, including introductory books on BASIC, Pascal, and assembly language programming, and four books on computer graphics and animation programming. He has also written books on topics as diverse as biotechnology, airline safety, underwater archaeology, sound, astronom=y, dinosaurs, the origin of the universe, and predicting the course ofepi- demics. He holds a degree in broadcast communications from the University of Maryland, College Park, and has worked both as a disk jockey and as a produceroftelevision commercials for a Maryland TV station. When he is not writing, programming, or indulging in his hobby as a fanatic computer gamer, he serves as Associate Sysop (system oper- ator) of the Game Publishers Forums (GAMPUB) on the CompuServe Information Service. He is also the author of Waite Group Presss Flights of Fantasy, Nanotechnology Playhouse, and Gardens of Imagination. . . .... Contents | Chapter 1: A Graphics Primer ........ 1 . . Chapter 2: The Mathematics of Animation . . . . .........o......o...o... 23 ............. 57 Chapter 3: Paintingin256 Colors. . . 101 Chapter 4: Making It Move. . . ................... Chapter 5: Talking to the Computer... 123 ... 163 Chapter 6: AllWired Up . oo ................... Chapter 7: From Two Dimensions to Three . . . . 213 .............. 249 Chapter 8: Polygon-Fill Graphics. . . 291 Chapter 9: Faster and Faster. . . . . . .... Chapter 10: Hidden Surface Removal ............. ....... 319 . . . . 355 Chapter 11: Polygon Clipping . . . . ............ 391 Chapter 12: Advanced Polygon Shading .. . . 443 Chaptero13: The View System . e...... Chapter 14: Fractal Mountains and Other Types of Scenery. . . . 475 oe 513 Chapter 15: Sound Programming. . . ...................... 543 Chapter 16: The Flight Simulator. .. . . . Chapter 17: The Three-Dimensional Future. . . . ................... 595 Appendix A: Flying the Build Your Own Flight Sim in C++ Flight Simulator . 607 .. . 615 Appendix B: Bibliography . . Appendix C: Adding Music to the Flight Simulator . . . ............ 617 627 INARX vii . || . - ; .... Contents Table of - gre = ire = a Chapter 1: A Graphics Primer The Descendants of Fligh,tSimo.ulatofr...,.......... .. Pie 1 GephicsapigGam0es. opal T. T 4 a0ae nn 5 SWtverus Graphics ooLLoLLat0ER 6 teProgammensView ey acsaan eLeam 6 ISRO VOR LLLcDL ee 8 EM aapnicImprove Ta Np MadesGslare,. Tcl Ea 8 9 «vr The MeRmeosroyhutCioonmapnadctiCoonl..o.r D«epothv... 0. Ee Ea BAee da 1120 Bits, tes and BinaLry.a..LLLLeLlhT 12 MeO AddIesses . . ooc, E Tne eee 14 Porting atMemory.Lo0 L a ge 15 NEBRERd FAC... HOWEmMapE Woork.sLaonL, TUaR pn 16 17 ACaiorBiinep. oo. on meel sJ 18 Mode BhiMemory . ch el Re 19 TheColoiPaidier POSAMMIREIE VOR2. ... =ar = 19 iTe a 20 . ed Chapter 2 The Mathematics of Animation ane 23 . ComespncOaiommes. lie a 26 ERCHen Pane... ..... «0. Sing 27 ........................_ Geometry Meets Algebra mE CodtdiniesontheComputer . .=. ., o.oo(0i, LiL To 0 2318 room Coordindtes to Pot Ofofsets... oso en ole 32 MRR he Ongin, . ool i 33 intheAMdsriedssiDngimMeunltsiipolen.P..ilos, +t. v0hs a de ee Cn 33 34 Shapes, Solids, and Coordinates ........................ . . . 36 viii = . 0 ... te . «oo Table of Contents mmm «Le Three-Dimensional VErtices 38 . . . . . 40 Graphing EQUations. . . . . . . .oo. 4 Solvingthe EQUAtion . . . . . . oe 43 Fractals . ©. Transformations «ot ooo 43 © .«oo Translating and Scaling o.oo 44 . . . ... . . . Rotatingon X,Y, and Z 45 . . . Doing What Comes Virtually. . . . . 47 Degrees versus Radians. .«.«. . . ooooo 48 49 Rotation FOrMUIAS. . . «© vo Matrix AIBEDIa. . «ovoii.i 50 Building Matrices 51 . . . . Multiplying Matrices. 51 . . . Three Kinds of Rotation Matrices «vo 53 o. . . . ... oo «ooo 54 Floating-Point Math . . . . «oe Chapter 3 Painting in 256 Colors ........................... 57 . ... LL. Color Depth versus Resolution. 59 . . . 60 Getting inthe Mode . . . . . 61 Doing It in Assembly Language. . . . . . Assembly Language Pointers 62 . . . . . AGsestteimngblyIt iLntaongauaRgeegisOtedrd.s .«an.d.E.ends. . .o«. . e.oo....e.o.o..... 6634 Passing Parameters to Assembly vLanguage Procedures...v 65 ovo Accessing the Video BIOS . . . «. o.oo 67 Restoring theVideo Mode. ooo 69 . . . . 70 More about BItMAPS . . «+ © ov oe .o..o.. 7 Finding the Bitmap ee . . . . . Drawing Pictures in MEMOTY «oo 72 . . . 73 Clearing the SCrEeN . . +. oo 75 Lots and Lots of Colors «oo . . 76 Setting the Palette. aThe.Default Palette . .. . . . .«o.oo ..oo 77 . . . . . SIOMNG BIMAPS . © + + ve ve eee a 79 «cco 80 Compressing BItmaps. . . . Graphics File Formats. a 82 . . . . Inside @ PONE oovin vcinees ienle bcb eaadahs RiEaBig oe en, 82 APCUSHUGHIIE 83 RRF me