Tải bản đầy đủ (.pdf) (608 trang)

Introduction to 3d game engine design using directx 9 and c

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (2.25 MB, 608 trang )

Introductionto3DGameEngineDesign
UsingDirectX9andC#
ISBN:1590590813
byLynnThomasHarrison
Apress©2003(422pages)
Thistextshowshowtodevelopacomplete3D
gameengine,writegamesusingC#,DirectX
9,andthe.NETFramework,andgobeyond
simplegraphicstoexploreaudio,userinput,
artificialintelligence,andmultiplayerdesign.
TableofContents
Introductionto3DGameEngineDesignUsingDirectX
9andC#
Introduction
Chapter1 - Overview
Chapter2 - UserInterface
HangingTen—ARideThroughthe
Chapter3 RenderingPipeline
Chapter4 - Basic3DObjects
Chapter5 - Complex3DObjects
Chapter6 - Camera—ThePlayer’sViewoftheWorld
AddingSomeAtmosphere—Lightingand
Chapter7 Fog
ArtificialIntelligence—Addingthe
Chapter8 Competition
Chapter9 - GameAudio—Let’sMakeSomeNoise
Chapter10 - GamePhysics—KeepingItReal
Chapter11 - ToolsoftheTrade


Index


ListofFigures
ListofTables
ListofExamples


BackCover
Introductionto3DGameEngineDesignUsingDirectX
9andC#illustratestheprocessofcreatingasimple
3Dgameengine.Duringthisprocess,authorLynn
HarrisondemonstratesmanyfacetsoftheDirectX9
softwarethroughclear-cutexplanationsandexamples.
Throughoutthecourseofthebook,you'lldevelopan
off-roaddrivinggamethatbringssuchfeaturesas
managementoflargescenes,environmentaleffects,
andphysicsintoplay.Towritethegame,you'lluse
cutting-edgetechnologies—C#andDirectX,andthe
.NETFramework—andyou'llgobeyondsimplegraphics
toexploreaudio,userinput,artificialintelligence,and
multiplayerdesign.
AbouttheAuthor
LynnThomasHarrisonisbothaMicrosoftCertified
SystemsEngineer(MCSE)andMicrosoftCertified
SolutionsDeveloper(MCSD),andiscurrently
employedasaseniorsystemsengineerforDiamond
VisionicsCompany(avisualizationengineering
company).Lynnhasbeenactiveinthesimulationand
graphicsindustriesforover22years.


Introductionto3DGameEngineDesignUsing

DirectX9andC#
LYNNT.HARRISON
Apress™
Copyright©2003byLynnT.Harrison
Allrightsreserved.Nopartofthisworkmaybereproducedortransmitted
inanyformorbyanymeans,electronicormechanical,including
photocopying,recording,orbyanyinformationstorageorretrieval
system,withoutthepriorwrittenpermissionofthecopyrightownerand
thepublisher.
ISBN(pbk):1590590813
Trademarkednamesmayappearinthisbook.Ratherthanusea
trademarksymbolwitheveryoccurrenceofatrademarkedname,weuse
thenamesonlyinaneditorialfashionandtothebenefitofthetrademark
owner,withnointentionofinfringementofthetrademark.
TechnicalReviewer:PatrickDeNardo
EditorialBoard:DanAppleman,CraigBerry,GaryCornell,Tony
Davis,StevenRycroft,JulianSkinner,MartinStreicher,Jim
Sumser,KarenWatterson,GavinWray,JohnZukowski
AssistantPublisher:GraceWong
ProjectManager:TracyBrownCollins
CopyEditor:AmiKnox
ProductionManager:KariBrooks
CompositorandProofreader:KineticPublishingServices,LLC
Indexer:MichaelBrinkman
CoverDesigner:KurtKrames


ManufacturingManager:TomDebolski
DistributedtothebooktradeintheUnitedStatesbySpringer-VerlagNew
York,Inc.,175FifthAvenue,NewYork,NY,10010andoutsidetheUnited

StatesbySpringer-VerlagGmbH&Co.KG,Tiergartenstr.17,69112
Heidelberg,Germany.
IntheUnitedStates:phone1–800-SPRINGER,email<>,orvisit.OutsidetheUnitedStates:
fax+496221345229,email<>,orvisit
.
Forinformationontranslations,pleasecontactApressdirectlyat2560
NinthStreet,Suite219,Berkeley,CA94710.Phone510–549–5930,fax
510–549–5939,email<>,orvisit
.
Theinformationinthisbookisdistributedonan“asis”basis,without
warranty.Althougheveryprecautionhasbeentakeninthepreparationof
thiswork,neithertheauthor(s)norApressshallhaveanyliabilitytoany
personorentitywithrespecttoanylossordamagecausedorallegedto
becauseddirectlyorindirectlybytheinformationcontainedinthiswork.
Thesourcecodeforthisbookisavailabletoreadersat
intheDownloadssection.
Dedication
Tomywife,Gerri,forhersupportandpatienceduringtheprocessof
writingthisbook.Icouldn’thavedoneitwithoutyou.Andalsotomyson,
Mike,whoinheritedmyloveofgamesofalltypes.
AbouttheAuthor
LynnThomasHarrisonisbothaMicrosoftCertifiedSystemsEngineer
(MCSE)andMicrosoftCertifiedSolutionsDeveloper(MCSD)andis
currentlyemployedasaseniorsystemsengineerforDiamondVisionics
Company(avisualizationengineeringcompany).HelivesinBinghamton,
NewYork,withhiswife,Gerri,andson,Michael.Lynnhasbeenactivein


thesimulationandgraphicsindustriesforover22years.
AbouttheTechnicalReviewer

PatrickDenardoisaprojectdirectorandsoftwaretechnicalleadat
UniversalInstruments,Inc.,wherehearchitectsanddevelopsclientserverinternationalizedsoftwarefortheWindowsplatform.Heisa
MicrosoftCertifiedProfessionalandhasaBachelorofSciencedegreein
computersciencefromBinghamtonUniversity.Patrickenjoysreading
computerbooks,playinggolf,andspendingtimewithhiswife,Jennifer,
andtheirdog,Abby.
Acknowledgments
IwouldliketothankallofthegreatpeopleatApressfortheirguidance
alongtheway.IreallyhadnoideawhenIstartedthisbookabout
everythingthatwentintotheprocess.First,thankstoGaryCornelland
DanApplemanfortheirenthusiasminthisprojectandforgettingme
started.AlsothankstoSofiaMarchantandTracyBrownCollinsfor
keepingeverythingorganizedandontrack.Bigthankstomywife,Gerri,
andtomycopyeditor,AmiKnox,whohelpedtranslatemytechie
ramblingsintoEnglish.
Iwouldalsoliketothankmytechnicalreviewer,PatDeNardo.Patnot
onlymadesurethattheinformationpresentedinthisbookwas
technicallycorrect,butalsothattheinformationwasunderstandableto
thosenewtoC#andManagedDirectX.
Lastly,Iwouldliketothankmyfamilyfortheirsupportoverthelast14
months.Toomanyweekendswerespentwithmycomputerratherthan
withthem.GerriandMike,thanksforunderstandingmyneedtodothis.I
wouldalsoliketothankmyparentsforalwaysbelievingmeandraising
metobelieveinmyself.


Introduction
Ihavebeeneducatingmyselfaboutgamedesignand3Dvisualizationfor
manyyears.Mybookshelvesarefullofbooksonprogramming,game
development,andthevariousgraphicalapplicationprogramming

interfaces(APIs).Manybookshavebeenwrittenthatexplaineverypart
ofDirectXorOpenGL.Quiteafewbooksarealsodedicatedtocreating
portionsofagameusingoneorbothofthesetechnologies.
ThebookthatIcouldneverfindwasoneongameenginedesign.I
wantedanobject-oriented,reusablepackageofsoftwarethatwasnot
tightlyintegratedtooneparticulargame.IknewthatIwasn’ttheonly
personinterestedingameenginedesign.Idecidedthat,asIlearnedC#
andmanagedDirectX9andportedmygameenginetothisnew
technology,Iwoulddocumenttheprocess.Thefactthatyouarereading
thisindicatesyousharemyinterestin3Dgameengines.
Ihavekeptthisbookatanintroductorylevel.WhenIinitiallybegan
planningthebook,Iconsideredincludingmoreadvancedtopicssuchas
animation,networkingformultiplayercapability,andtheprogrammable
pipeline(shaders).Iquicklycametotheconclusionthattocoverthat
muchmaterialinanydepthatallwastoomuchforasinglebook.Iam
hopingthatatsomepointinthefutureIwillhavethetimetodoafollowupvolumethatincludestheseandothermoreadvancedareas.
Noonebookcananswerallquestions.Iencourageyoutoextendyour
researchtootherbooksandtheInternetasyouhoneyourdevelopment
capabilities.Thebestresourcesforgettingyourquestionsansweredare
theMicrosoftDirectXnewsgroups.Thereareanumberofnewsgroupsof
interestthatareprefixedwithmicrosoft.public.win32.programmer.directx.
ThenewsgroupdedicatedtoManagedDirectXis
microsoft.public.win32.programmer.directx.managed.Ioftenmonitorthis
newsgroup,andIwillansweranyquestionsthatIcan.
Chapter1:Overview
Thischapterlooksatseveraltypesofgameenginesaswellasthe
distinctionbetweenagameandagameengine.Gameenginedesign


requiresmorethoughtthandohard-codingrenderingandgamelogic

withinthegameitself.Thebenefitisgreaterreuseoftheunderlying
technologyandacleaneroveralldesign.
Chapter2:UserInterface
Agame’suserinterfaceprovidesthemeansofgivingtheplayer
informationandobtainingtheplayer’scommands.Thischapter
investigatesthepresentationofsplashscreens,optionscreens,anda
consolescreen.ItalsolooksattheuseofDirectlnputtoobtainplayer
inputsfromthekeyboard,mouse,andjoysticks.
Chapter3:HangingTen:ARideThroughtheRenderingPipeline
Beforedivingintotheactualrenderingofthree-dimensionalobjects,itis
goodtohaveabasicunderstandingoftherenderingpipeline.This
chapterwalksyouthroughthetypicalstepsinvolvedinthefixed-function
renderingpipeline.Thisincludesthemanipulationofcamerastoprovide
theviewpointinthegame.Italsodescribesabaseclassthatwillbeused
forallrenderedobjects.Theprocessofcullingobjectsandother
techniquesforimprovingperformanceisalsoinvestigated.Theactual
illustrationofthesestepsappearsinChapters4through8.
Chapter4:Basic3DObjects
Thischapteristhefirstoftwochaptersdealingwithrenderingthevarious
typesofobjectsthatareusedwithinagame.Theseobjectsincludea
skyboxforprovidingaviewintothedistance,terrainrenderingtoprovide
asurfacetomoveupon,billboardsforsimplesymmetricalobjects,and
particlesystems.Particlesystemsareanextremelypowerfultoolthat
maybeusedfordynamicsystemsofsmallobjects.Theseincludeflowing
water,fire,fireworks,andblowingsand.
Chapter5:Complex3DObjects
Chapter5isthesecondchapterdedicatedtotherenderingofobjectsfor
games.Theobjectsdescribedinthischapteraremuchmorecomplex,
withmanypolygonsperobject.Thesearereferredtoasmeshobjects
andareusedastheprimarymovingmodelswithinagame.Theclass



usedtoencapsulatemeshesincludesthecapabilitytoadjustthe
complexityofthemeshasafunctionofrangefromthecamerato
improveperformance.
Chapter6:Camera:ThePlayer’sViewoftheWorld
Tocontroltheviewoftheaction,weneedsomethingakintothecameras
usedtofilmamovie.Thischapterillustratesthedesignanduseofa
cameraclassthatmaybeemployedinavarietyofways.Camerasmay
bepositionedatstaticlocationswithinthesceneandfollowobjectsas
theymovepastortheymaybeattachedtothemovingobjects
themselves.Employingmultiplecamerasandincludinglogicwithina
gamecanprovideacinematicflairtothegame.
Chapter7:AddingSomeAtmosphere:LightingandFog
Alloftherenderingperformedbythegameengineupuntilthispointhas
beenunderfullylitandcrystal-clearconditions—conditionsthatareoften
hardtofindintherealworld.Thischapterexploresthefourtypesoflights
thatmaybeusedtoilluminateasceneaswellashowtoconfigurefogto
improvetherealismofagame.Fogmayalsobeusedtodisguise
shortcomingsintheabilitytorenderobjectsatalargedistancefromthe
camera.
Chapter8:ArtificialIntelligence:AddingtheCompetition
Fewgamesaremuchfunwithoutopponents.Althoughitispossibleto
writegamesthatarestrictlymultiplayer,inwhichalloftheopponentsare
human,networkingisoutofthescopeofthisbook.Instead,wewilllook
atthedifferenttypesofartificialintelligencetechniquesthatcanbeused
withinagame.Oneofthesemethodswillbedevelopedaspartofthe
samplegameengineforthebook.
Chapter9:GameAudio:Let’sMakeSomeNoise
Anothermethodtoaddcharactertoagameisthroughtheuseofaudio.

Backgroundmusic,ifchosenproperly,addsmoodtotheplay.This
chaptershowsyouhowtodevelopclassesforthegameenginethat
facilitateplayingsongs.Italsoincludessupportforsoundeffectswithina


game.Playersexpectcertainsoundstocoincidewitheventswithina
game.Ifacarhitsanothercaroratree,theyexpecttohearthecrashas
wellasseeareactionbetweentheobjectsinvolvedinthecollision.
Chapter10:GamePhysics:KeepingItReal
AsImentionedwhentalkingaboutaudio,playersnotonlyexpecttohear
noiseinacollision,butalsotoseeamorephysicalreaction.Chapter10
concentratesonthephysicsinvolvedprimarilywithcars.Thebasic
mathematicsappliedtocarsmayalsobeappliedtomanytypesof
movingobjects.Thischapteralsocoversthephysicsusedforcloth
dynamics.Thistypeofphysicsisusedfornotonlycloth,butalsofor
manytypesofflexibleobjectssuchashairorrope.
Chapter11:ToolsoftheTrade
Thefinalchapterofthebooklooksatacross-sectionoftoolsthatare
usedduringgamedevelopment.Ifyouarejuststartingoutingame
development(orjuststartingoutwithC#),youmayfinditusefultocheck
outthischapterbeforedivingintotherestofthebook.Thefirstportionof
thischapterconcentratesonthedevelopmentenvironmentusedto
compileandtestyoursoftware.Othertopicscoveredinthechapter
includethemanipulationoftheartisticcontentforthegame.Theartistic
contentincludestheaudiofiles,two-dimensionalimages,andthreedimensionalmodels.


Chapter1:Overview
Thisbookiswrittenforpeoplewhomayormaynothaveexperiencewith
3Dgraphicsandwanttolookatthebiggerpictureofgameengine

design.Thisfirstchapterlooksatgameenginesfromabroad
perspective.Thegoalistoprovideanoverviewofgameenginesthatwill
serveasafoundationforthedetaileddiscussionintherestofthebook.
Overthecourseofthebook,wewillexploreeachaspectofgame
enginesandexaminethecorrespondingfeaturesinthesourcecodefor
theexamplegameengineprovidedwiththebook(downloadablefromthe
ApressWebsiteat).Eachchapterfocusesona
majorconceptorsubsetofthegameengine.Severalchaptersare
dedicatedtodifferenttypesofgraphicalrendering,sincedifferent
techniquesareemployedbasedonthecomplexityoftheobjectbeing
rendered.


WhatIsaGameEngine?
Agameengineistheveryheartofanycomputergame.Manytimesthe
engineishighlycoupledtothegameanduniquetothatgame.Aproperly
designedengine,however,ismodular,reusable,andflexibleenoughto
beusedformultiplegamesthataresimilar.Agameengineisgenerally
designedandoptimizedforaparticulartypeofgame.Thesetypes
includefirst-personshooters,real-timestrategygames,andvehicle
simulations,tonameafewofthemostpopular.
Thecommercialgameenginesdescribedhereareeachhighlyoptimized
fortheirrespectivegames,whichwerewrittenbyteamsofhighly
experiencedprofessionalswhospentmanyman-yearsdevelopingthem.
Thesecommercialgamesmustperformwellonawiderangeof
computerhardware.TheyarewrittentouseeitherDirectXorOpenGL
renderingsothatplayersarefreetochoosetheonethatworksbestfor
thevideocardintheirsystem.Thecommercialsoftwareusesadvanced
methodssuchasvertexandpixelshaderswithproprietarycodingin
ordertoprovidetheirrespectivecompanieswithanedgeinthegame

market.

First-PersonShooterGameEngines
First-personshootergameenginesareoftenbasedindoors.Thisplaces
anemphasisonvisualdetailandanimations.Increasedvisualdetail
comesatthecostofmoretexturesandincreasedpolygoncountacrossa
givengamelevel.Tocompensateforthis(whichisnecessarytomaintain
areasonableframerate),mostoftheseenginesrelyonQuadtree,Portal,
orBinarySpacePartition(BSP)culling.Cullingistheprocessof
removingpolygonsfromthescene.(Moredetailonthesecullingmethods
appearsinChapter3.)ExamplesofthisgenreincludeDoomandQuake
(initsmanyversions)fromidSoftwareandHalf-Life(includingthe
extremelypopularCounter-Strikeversion)fromSierra.

Real-TimeStrategyGameEngines


Untilrecently,real-timestrategygameshavebeentwo-dimensional,
sprite-basedgamesthatuseafixedviewpointandcleverlydesigned
spritestogivetheillusionofthreedimensions.Newergamessuchas
EmpireEarthfromSierraandAgeofMythologyfromEnsembleStudios
havebroughtthistypeofgameintothe3Denvironment.Figure1–1
showsascenefromAgeofMythology.


Figure1–1:AscenefromAgeofMythology
Thistypeofgameisgenerallysetoutdoorsandfacesthedauntingtask
ofdisplayingaverylargenumberofobjectsatonetimeaswellasan
expansiveterrain.Thegameenginesforthesegamesuseanaerialview
toreducethenumberofobjectsandtheamountofterrainthatiswithin

theplayer’sview.Thesegamescanalsouseobjectsthataresomewhat
lowerinresolutionthanthosewewouldtypicallyfindinafirst-person
shooter.Sincetheviewpointiskeptatafixeddistancefromtheground,
theplayerdoesn’ttypicallygetcloseenoughtoanobjecttoseethe
detailsthatwouldrequirehigh-resolutionmodeling.

VehicleSimulationGameEngines
Thethirdtypeofgameenginementionedisthevehiclesimulation
category.Thisgroupincludesfirst-personmilitarycombatsimulators
(planes,helicopters,tanks,etc.),racinggames,andotherdrivinggames.
OneexampleofthistypeofgameisComanche4fromNovaLogic.


Sincethesettingforthesegamesisoutdoorsandtheviewangleis
relativelyunconstrained,specialtechniquesarerequiredtomaintaina
playableframerate.Thesetechniquesfallprimarilyintheareasofculling
andlevelofdetail(LOD)toreducethenumberofpolygonsthatmustbe
texturedanddrawn.Oneofthemostcommonmethodsinoutdoor
simulationgamesistomovethefarclippingplanenearertothepointof
view.Thiscausesanypolygonsbeyondtheplanetobeculledfromthe
scene.Anadverseeffectofthisisthattheplayercanseeobjects
appearinganddisappearingatthefarclippingplaneastheviewpoint
moves.Thesolutiontothisproblemisthejudicioususeoffog.Fogor
hazeallowspolygonstofadetotheselectedfogcolorastheyapproach
thefogmaximumdistance(usuallyatorjustshortofthefarclipping
plane).BothLODandprogressivemeshtechnologiesprovidea
mechanismtoreducethenumberofpolygonsinagivenobjectina
controlledmannerasafunctionofrangetotheviewpoint.LOD
techniquesreplacehighlydetailedmodelswithlessdetailedmodelsas
theymovefurtherfromtheeye.Progressivemesh,ontheotherhand,

modifiesasinglemeshbasedonitsrangefromtheeye.
Note Donotconfusegameenginedesignwithgamedesign.The
gameengineistheenablingtechnologybehindthegame.
Gamedesignneedstotakeintoaccountmanyissuesthathave
nothingtodowiththegameengine.Thegameenginesupports
thegamebyprovidingthetoolsthegamedesignerneedsto
translateaconceptorstorylineintoagame.


HowThisBook’sGameEngineProjectDiffers
Thepurposeofthisbookistoillustrateallofthebasiccomponentsofa
gameenginewhiledemonstratinghowtobuildanexamplegameengine
overthecourseofthebook.Youmayexpandtheexamplegameengine
tocreatethegameofyourchoice.Ihavechosentoconcentrateon
renderingusingDirectX9.IfyoupreferOpenGL,Ileaveittoyouasa
codingexercisetosubstituteOpenGLAPIcallsinplaceoftheDirect3D
APIcalls.Thesamebasicrenderingcapabilitiesareprovidedbyboth
APIs.
Discussionsofthegameenginepresentedinthisbookwillnotdelveinto
allofthegreatthingswecandowithvertexandpixelshaders.(Asa
topic,thenewHighLevelShaderLanguageincludedinDirectX9could
fillmostofabookitself.)Norwillweexploreallofthepotentialmethods
ofoptimizingterrainrenderingorcharacteranimation.
Indevelopinganexamplegameenginethroughoutthecourseofthis
book,Iwillconcentratemoreonanobject-oriented,genericapproachto
gameenginedesign.Thisgameengineisnotmeantforuseinthenext
blockbustergametohitthemarket.Instead,myhopeisthat,byproviding
afundamental,yetflexiblegameengine,youwilllearnsomethingnew
youcanuseinyourown3Dgameenginedevelopment.Thisobjectorientedapproachwillproduceamodularenginethatcanbeeasily
modifiedandextendedasyoumoveintomoreadvancedgameengine

components.

TheObject-OrientedApproach
Inordertodevelopaclean,genericdesign,wewilluseobject-oriented
techniquesinthedesignanddevelopmentofthisgameengine.Objectorienteddesignandprogramming(whendoneproperly)providesafinal
systemthatissimple,straightforward,andeasytomaintain.Ihave
designatedtheC#languageastheprogramminglanguageforourgame
engine,becauseitprovidesalloftheobject-orientedfeatureswedesire
forthisproject.


WhyC#?
YoumaybewonderingatthechoiceoftheC#languageforthisgame
engine.AlmosteverygameinrecenthistoryhasbeendevelopedinCor
C++duetoperformanceconsiderations.MicrosofthascreatedtheC#
languageinanattempttobringtherapidapplicationdevelopment(RAD)
aspectofVisualBasictotheC++community.Aspartofthe.NET
initiative,MicrosofthasalsoincreasedtheperformanceandobjectorientednatureofVisualBasic.ItsstatedgoalforDirectX9istoachieve
performancevalueswithinacouplepercentofC++.Thismakesthe
choiceofusingaRADlanguageveryappealing.Thepointthattipsthe
scalesinfavorofC#isthefactthatC#includesafeatureforselfdocumentation.Developingagamethesedaysisusuallyagroupeffort.
Itistherareindividualwhocandevelopacompletegameonhisorher
own.Thismakessharingwell-formattedanddocumentedcodeahigh
priority.Theclean,object-orientedstructureavailablewithC#,combined
withgoodcommentinganddocumentationpractices,canmakethe
differenceinwhetherornotyoumeetyourschedule.


StartingattheBeginning-DefiningaFew
Primitives

Beforeweventureintotheworkingcodeofthisgameengine,wewill
startwithafewofthelow-levelorprimitivedatastructuresthatwewillbe
using.TheC#languagehastwowaysinwhichdataandassociated
methodsmaybedefined.Thefirstisastructure(struct),whichisa
valuetypethatisallocatedonthestackratherthanthemanagedheap.
Thestructuretypesdonothavethepowerandflexibilityfoundinthe
classtype,buttheyaremoreefficientforsmalldataunitssuchasthe
primitivesthatformthefoundationofthegameengine.
ThefirstprimitiveisVector3,asimplestructureconsistingofthree
single-precisionfloating-pointvariables(X,Y,andZ).Thissimple
structureformstheveryfoundationofmuchofthe3Drenderingand
physicaldynamicswithinthegameengine.Wewillusethistypeto
describeeverythingfromeachpointinthree-dimensionalspaceaswell
asthespeed,acceleration,andforcesalongeachaxisforanobject.The
three-dimensionalsystemthatwewilluseinthisgameengineisdefined
withXpositivemovingtotherightofthereferencepoint,Ypositive
movingupfromthereferencepoint,andZpositivemovingforwardfrom
thereferencepoint.Themajorityofthecodefoundinthisbookwilluse
thevectorclassprovidedwithMicrosoftwithDirectX.Therewillbean
exampleinChapter10thatemploysourownimplementationoftheclass
foradynamicslibraryusablebyeitherDirectXorOpenGL.TheC#code
torepresentthisstructureisshowninListing1–1.
Listing1.1:Vector3C#Definition
publicstructVector3
{
publicfloatX=0.0;
publicfloatY=0.0;
publicfloatZ=0.0;
}



Note TheunitsusedinthisgameenginewillallbeintheEnglish
system.Alldistanceswillbemeasuredinfeet.
TheVector3valuescanbereferencedtotwobasiccoordinatesystems.
Thefirstsystemiscalledtheworldcoordinatesystem.Thissystemis
centeredatapointintheworlddatabasechosenbythegameauthor.For
thepurposeofthegameenginedevelopedinthisbook,theoriginofthe
worldcoordinatesystemwillbeatthesouthwestcorneroftheterrain
model.Withthisorigin,theXcoordinateispositivemovingeastandtheZ
coordinateispositivemovingnorth.Theothercoordinatesystemis
referredtoasthelocalcoordinatesystem,orbodycoordinatesystem.
Fortheterrainmodel,thereisnodifferencebetweenthetwosystems.
Foreveryotherobject,thelocalcoordinatesystemisusedinthe
definitionsoftheverticesthatmakeuptheobject.Asyouwillseein
Chapter3,bothofthesecoordinatesystemswillbetransformedto
screencoordinates(two-dimensionalcoordinates)inordertodraw
properlyonthescreen.
Thesecondprimitive,Attitude,isavariationonVector3that
describestherotationaroundeachoftheseaxes.Youwilloftensee
thesereferredtoasEulerangles.Forthesakeofefficiency,allangles
(rotations)arestoredinradians.Thisistheformatrequiredby
trigonometricmathfunctions.Ifweusedegreesindevelopingourgame
engine,itmightbeabitmoreunderstandabletousasprogrammers,but
notworththecomputationalcostrequiredtoconverteachangleevery
timewebuildatransformationmatrix.
ThereareafewtermsrelatedtotheAttitudeprimitiveyouneedtoknow
beforewemoveon.PitchistherotationaroundtheX-axiswithpositive
valuesintheclockwisedirectionwhenlookingfromtheorigin.Yawisthe
rotationaroundtheY-axiswithpositivevaluesinthecounterclockwise
directionwhenlookingfromtheorigin.RollistherotationaroundtheZaxiswithpositivevaluesintheclockwisedirection.Itmayseemstrange

thatyawanglesaredefinedabitdifferentlyfromtheothertwo.Thisis
doneinordertomatchupwithcompassheadingangles.Asyoumay
know,thecompassisdefinedwithzerodegreesasnorth,withangles
increasingintheclockwisedirection.Inoursystem,thatwouldonlybe
truewhilelookingtowardtheaxisorigin.Sinceallofourrotationsare


definedaslookingalongthegivenaxisfromtheorigin,wemustrotatein
theoppositedirectionforyawtomatchcompassangles.TheC#codeto
representthisstructureisshowninListing1–2.
Listing1.2:AttitudeC#Definition
publicstructAttitude
{
publicfloatPitch=0.0;
publicfloatYaw=0.0;
publicfloatRoll=0.0;
}

ThethirdandlastprimitivethatIwilldefinefornowisVertex.This
structureisanextensionoftheVector3structurethatincludes
informationusedintexturemapping.Avertexdefinesapointinthreedimensionalspacethatispartofadefinitionofathree-dimensional
object.Youwillseelaterthatamesh(3Dlingoforthedatadescribinga
three-dimensionalshape)ismadeupofalistofverticeswithadditional
informationabouthowtheyareconnectedandthetexturesthatcover
them.ThefirstcomponentinthestructureisaVector3component
calledPointthatholdsthepositioninthree-dimensionalspaceforthe
vertex.Thenexttwocomponents(TUandTV)arethetwo-dimensional
coordinateswithinatexturemapthatcorrespondstoaparticularvertex’s
positionwithinthetexturemap.Thetexturemapissimplyabitmapthat
describeshowthepixelsatandbetweenverticeswillberendered.Ifany

ofthisseemsconfusing,restassuredthatwewilldiscussthisinmuch
greaterdetailinChapter3aswelookattherenderingpipeline.Wewill
notneedtodevelopthesevertexstructuresourselvesthough.Microsoft
haskindlyprovidedallofthebasicvertexstructuresforusinmanaged
DirectX.TheC#codetorepresentthisstructureisshowninListing1–3.
Listing1.3:VertexC#Definition
publicstructVertex
{
publicVector3Point;


publicVector3Normal;
publicColorDiffuse;
publicColorSpecular;
publicfloatTU=0.0;
publicfloatTV=0.0;
}

ThisisthefirstandmostbasicversionoftheVertexstructure.Laterin
thebook,youwillencountermorecomplexversionsofthisstructure
tailoredforspecificpurposes.Theseotherversionswillsupportfeatures
suchasmultitexturingaswellasnontexturedsurfaces.


Interfaces:TheIntegrationContract
AsIsaidearlier,thiswillbeanobject-orientedgameengine.Traditionally
inC++,multipleinheritancewouldbeusedtoprovideacollectionof
predefinedbehaviorsforthevariousclasseswithintheengine.
Whilethisisapowerfultechnique,itdoeshaveitsdangers.Ifaclass
inheritsfromtwobaseclassesthatdefineattributesormethodswiththe

samename,therewouldbeaproblem.Theduplicatednameswould
“collide”andproduceacompilererror.TheC#languageaddressesthis
problembynotallowingmultipleinheritance.C#classesareallowedto
inheritfromonlyasinglebaseclass.Toprovidethebenefitsofmultiple
inheritancewithoutthedangers,C#usesamechanismcalledan
interface.IfyouarefamiliarwithC++,youcanthinkofaninterfaceasa
purevirtualorabstractbaseclass.AC#interfacemaydefinemethods
andpropertiesbutdoesnotincludetheimplementationofeither.AC#
classmayinheritfromasmanyinterfacesasitneeds.Itisthe
responsibilityoftheinheritingclasstoimplementeachmethodand
propertydefinedbytheinterfacesitinherits.Ifitfailstoprovideamethod
orpropertydefinedinaninheritedinterface,thecompilerwillflagan
error.
Classinstancesmaybequeriedatruntimetodetermineiftheysupporta
giveninterface.Thisallowsustohaveacollectionofobjectsofdifferent
types,iteratethroughthecollection,andcallinterfacemethodsofthose
objectsthatsupporttheinterface.Sinceeachclassprovidesitsown
implementationfortheinterfacemethods,itisfreetoprovidean
implementationthatisuniqueandappropriateforthatclass.Asan
example,let’slookattwoclassesthatimplementaninterfacecalled
IRenderabledeclaringamethodcalledRender.Thisinterfacewillbe
discussedindetailshortly.Fornow,acceptthataclassusesthismethod
inordertodrawtheobjecttothescreenappropriatelyforthecurrent
view.
Forthisexample,wewillassumethatoneobjectisabillboardmadefrom
twotrianglestorepresentatreeandthattheotherobjectistheterrain
model,withhundredsofthousandsoftrianglesforanentireoutdoors
game.Itiseasytoseehowtherequirementsandimplementationofthis



methodmustbedifferentforthesetwoclasses.Thebillboardneedsonly
todrawthetwotrianglesorientedtowardthepointofviewandtexturedto
looklikeatree.Theterrainclass,ontheotherhand,mustfirstdetermine
whichtrianglesarevisible(nocurrenthardwarecanrenderaworldofthis
sizeinrealtimeforeveryframe),transformtheverticesforthetexture
appropriatelyforthecurrentview,anddrawandtexture.
Let’slookataviewofthemoreimportantinterfacesthatwewillusein
thisgameengine.Wewillgetintovariousimplementationsofthese
interfacesasweprogressthroughthebook.Thecodeforthese
interfacesisshowninListing1–4,whichappearslaterinthissection.
ThefirstinterfaceistheIRenderableinterfacementionedpreviously.A
classthatimplementsthisinterfaceisabletorenderanimageofitselfto
thescreenusingtheRendermethod.Theargumentofthismethodisthe
cameradefinitionthatdefinesthecurrentview.Thisisalltheinformation
anyclassimplementingthisinterfacerequirestorenderitself.
Thesecondinterface,ICullable,isimplementedbyanyclassthatmay
notalwaysberenderedtothedisplay.Thisinterfacedefinestwo
properties.Thepropertiesmanagethecullstateoftheobject(whether
theobjectshouldberenderedornot).Thefirstpropertydefinedis
Culled,whichisresponsibleforclearingthecullstateflagtothenot
culledstate.Thesecondpropertyisdefinedasaread-onlyBoolean
variablethatisreadwithaGetmethod,IsCulled.Itisimportantfor
gameefficiencythatanygraphicalobjectsupportthisinterface.As
mentionedearlierwhendiscussingterrain,thenumberoftrianglesinan
objectwouldoverloadthevideocardifnotreducedtoonlythevisible
subset.
ThenextinterfaceistheICollidableinterface.Anyclasswhose
objectmightphysicallycollidewithanotherobjectshouldsupportthis
interface.Thepropertiesandmethodsofthisinterfacesupportthetesting
forcollisionsbetweentwoobjects.Theinterfacespecifiesseveral

propertiesthatexposetheobject’sgeometryinseverallevelsofdetail.In
orderforthisinterfacetowork,bothobjectsinvolvedmustsupportthe
interface.ThefirstpropertyisaVector3propertycalled


CenterOfMass.Thispropertydefinesthelocationofthecenterofthe
objectinworldcoordinates.Thesecondpropertyoftheobjectis
BoundingRadius.Thisvaluedefinesaspherearoundtheobject—the
smallestpossiblespherecenteredonthecenterofmassthatcompletely
enclosestheobject.
ThefirstmethoddefinedbytheinterfaceisCollideSphere,which
takesanobjectreferenceasanargument.Thismethodperformsa
sphericalcollisioncheckbetweenthetwoobjects.Thisisthequickest
collisioncheckpossible,sinceitonlyneedstocheckthedistance
betweenthetwoobjectsagainstthesumoftheboundingradiiofthetwo
objects.Thisisalow-fidelitycollisioncheck,asitispossibletoreporta
falsepositiveifthetwoobjectsareclosetogetherwithoutanyofthe
polygonalfacesintersectingorcomingintocontact.Ifneitherofthe
objectsistheplayer’smodel,andbotharefarenoughfromtheviewpoint
orotherwiseoutofview,thismightbesufficient.Otherwise,wewould
normallyproceedtousingthesecondmethodofthisinterface.This
method,CollidePolygon,takesthreeVector3variablesas
arguments.Themethodiscalledforeachpolygoninoneofthemodels
untilacollisionisdetectedorallpolygonshavereturnedafalseBoolean
value.Asyoucansee,thisisfarmorecomputationallyexpensive.
Unfortunately,wemustgotothisextentifwewant100percent
confidenceinthecollisiontest.
ThenextinterfacethatwewilllookatistheIDynamicinterface.This
interfacesupportsanyobjectthatmovesorchangesastimeprogresses.
Onlyonemethodisdefinedforthisinterface:Update.Theonly

argumenttothismethodisafloating-pointvariablecontainingthe
numberofmillisecondssincetheobjectwaslastupdated.Thisusesthe
methodforintegrationofthepositionandattitudeoftheobject,thestep
totheproperframeofananimation,orboth.Thepropertiesofthe
interfacearerelatedtothephysicaldynamics,whichIwilladdressin
detailinChapter10.
ThefinalinterfacethatwewilldiscussfornowisITerrainInfo.Any
classthatmaybequeriedforinformationabouttheterrainimplements
thisinterface.Thisinformationisvitalforanyobjectthatmovesalongor


overthesurfaceoftheterrain.Thefirstmethodforthisinterfaceis
HeightOfTerrain,whichreturnstheY-axisvalueoftheterrainatthe
suppliedlocationinmeters.Bypreventinganobjectfrommovingbelow
thisvalue,theobjectstaysonthesurfaceratherthandroppingthrough.
Thesecondmethod,HeightAboveTerrain,isanextensionofthefirst
methodthatreturnsthedifferencebetweentheY-axisvaluepassedinas
partofthelocationandtheheightoftheterrainatthatpoint.Thismethod
isimportantforobjectsthatareinflightabovetheterrainandstrivingnot
tocollidewiththesurface.ThenextmethodisInLineOfSight,which
returnsapositive(true)valueifthereisanunobstructedlineofsight
betweenthetwopointsthataresuppliedasarguments.Thefinalmethod
oftheinterface,GetSlope,isusedbyanyobject(suchasaground
vehicle)tomatchitsattitudewiththatoftheslopeitisrestingupon.As
youcanseeinthecodeinListing1–4,thismethodacceptsthelocation
inquestionandtheheadingoftheobjectmakingthecall.Theheading
allowsthemethodtoreturnanattitudethatisrotatedtomatchthe
object’sheading.
Listing1.4:InterfaceDefinitions
publicinterfaceIRenderable

{
voidRender(Cameracam);
}
publicinterfaceICullable
{
boolCulled{set;}
boolIsCulled{get;}
}

publicinterfaceICollidable
{
Vector3CenterOfMass{get;}
floatBoundingRadius{get;}
boolCollideSphere(Object3Dother);
boolCollidePolygon(Vector3Point1,Vector3Point2,Vector


}
publicinterfaceIDynamic
{
voidUpdate(floatDeltaT);
}

publicinterfaceITerrainInfo
{
floatHeightOfTerrain(Vector3Position);
floatHeightAboveTerrain(Vector3Position);
boolInLineOfSight(Vector3Position1,Vector3Position2);
AttitudeGetSlope(Vector3Position,floatHeading);
}



×