3DProgrammingforWindows®:ThreeDimensionalGraphicsProgrammingforthe
WindowsPresentationFoundation
byCharlesPetzold
Publisher:MicrosoftPress
PubDate:July25,2007
PrintISBN-10:0-7356-2394-5
PrintISBN-13:978-0-7356-2394-1
Pages:448
TableofContents|Index
Overview
TheWindowsPresentationFoundationisakeycomponentof
.NETFramework3.0,whichisapartofWindowsVistaand
availableforWindowsXP.WiththeWindowsPresentation
Foundation,3Dimagescanbedisplayedregardlessofthe
video-displayhardwareontheusersmachine.Focusingon
developinguserinterfaceobjectsorsimpleanimations,this
bookbuildsonareadersknowledgeofWindowsPresentation
Foundationessentialstodemonstratehowtoeffectivelycreate
3DgraphicsforWindows.Yougetthefundamentalinformation
forusingtheWindowsPresentationFoundation3Dapplication
programminginterface(API),aswellasin-depthcoverageof
meshgeometries.
3DProgrammingforWindows®:ThreeDimensionalGraphicsProgrammingforthe
WindowsPresentationFoundation
byCharlesPetzold
Publisher:MicrosoftPress
PubDate:July25,2007
PrintISBN-10:0-7356-2394-5
PrintISBN-13:978-0-7356-2394-1
Pages:448
TableofContents|Index
Copyright
Introduction
Chapter1.Lights!Camera!MeshGeometries!
Three-DimensionalCoordinates
PointsinSpace
IntroductiontoVectors
Definingthe3DFigure
LightsandCamera
TheViewport3DandItsConstituents
VariationsinCodeandMarkup
FieldsofView
DefiningFlatRectangles
Defining"Solid"Figures
BalancingLightSources
TheOrthographicProjection
WhyNotSharetheVertices?
Transparency
SortingOuttheClasses
Chapter2.TransformsandAnimation
AnimationWithoutTransforms
ManipulatingCollections
TheTransform3DClass
TheTranslationTransform
ShareableModels
TheScaleTransform
CombiningTranslationandScaling
HowtoBuildaChair
Chapter3.Axis/AngleRotation
TheRotationTransform
CombiningRotationandOtherTransforms
IntroductiontoHit-Testing
AnimatingtheAxis
Chapter4.LightandShading
LessonsinIllumination
VectorMathematics
DiffuseMaterialandItsProperties
SpotLightandPointLight
Chapter5.TextureandMaterials
GradientBrushes
TileBrushes
SpecularandEmissiveMaterials
Chapter6.AlgorithmicMeshGeometries
TriangulationBasics
TriangulationResources
DerivingfromModelVisual3D
ThePetzold.Media3DLibrary
Chapter7.MatrixTransforms
LinearTransforms
AffineTransformsandBeyond
CameraTransforms
Chapter8.Quaternions
TheConvenienceofComplexNumbers
HamiltonandQuaternions
WhyAreQuaternionsSoWeird?
TheQuaternionStructure
QuaternionsandRotation
Low-LevelQuaternionRotation
QuaternionsandRotationMatrices
SLERPandAnimation
Chapter9.ApplicationsandCuriosa
ControlTemplates
3DVisualizationofData
MimickingRealWorldObjects
InteractiveMouseTracking
Printingin3D
Anaglyphs
AbouttheAuthor
AdditionalResourcesforDevelopers
VisualBasic2005
VisualC#2005
WebDevelopment
DataAccess
SQLServer2005
OtherDeveloperTopics
MoreGreatDeveloperResources
DeveloperStepbyStep
DeveloperReference
AdvancedTopics
Index
Copyright
PUBLISHEDBY
MicrosoftPress
ADivisionofMicrosoftCorporation
OneMicrosoftWay
Redmond,Washington98052-6399
Copyright©2008byCharlesPetzold
Allrightsreserved.Nopartofthecontentsofthisbookmaybe
reproducedortransmittedinanyformorbyanymeanswithout
thewrittenpermissionofthepublisher.
LibraryofCongressControlNumber:2007928771
PrintedandboundintheUnitedStatesofAmerica.
123456789QWT210987
DistributedinCanadabyH.B.FennandCompanyLtd.
ACIPcataloguerecordforthisbookisavailablefromtheBritish
Library.
MicrosoftPressbooksareavailablethroughbooksellersand
distributorsworldwide.Forfurtherinformationabout
internationaleditions,contactyourlocalMicrosoftCorporation
officeorcontactMicrosoftPressInternationaldirectlyatfax
(425)936-7329.VisitourWebsiteat
www.microsoft.com/mspress.Sendcommentsto
Microsoft,MicrosoftPress,DirectX,IntelliSense,Internet
Explorer,VisualStudio,Win32,Windows,andWindowsVista
areeitherregisteredtrademarksortrademarksofMicrosoft
CorporationintheUnitedStatesand/orothercountries.Other
productandcompanynamesmentionedhereinmaybethe
trademarksoftheirrespectiveowners.
Theexamplecompanies,organizations,products,domain
names,e-mailaddresses,logos,people,places,andevents
depictedhereinarefictitious.Noassociationwithanyreal
company,organization,product,domainname,e-mailaddress,
logo,person,place,oreventisintendedorshouldbeinferred.
Thisbookexpressestheauthor'sviewsandopinions.The
informationcontainedinthisbookisprovidedwithoutany
express,statutory,orimpliedwarranties.Neithertheauthors,
MicrosoftCorporation,noritsresellers,ordistributorswillbe
heldliableforanydamagescausedorallegedtobecaused
eitherdirectlyorindirectlybythisbook.
AcquisitionsEditor:BenRyan
ProjectEditor:ValerieWoolley
TechnicalEditor:TechnicalReviewer:KennScribner;TechnicalReviewse
ContentMaster,amemberofCMGroup,Ltd.
EditorialandProductionServices:Publishing.com
BodyPartNo.X13-82451
Introduction
MicrosoftWindowsVistaisthefirstversionofWindowstohave
built-insupportforthree-dimensionalgraphics.This3D
graphicssupportisintegratedwiththeMicrosoftWindows
PresentationFoundation(WPF),theclientapplication
programminginterface(API)thatwasintroducedin2006as
partoftheMicrosoft.NETFramework3.0.Although.NET3.0is
automaticallyincludedinWindowsVista,youcanalsoinstallit
underMicrosoftWindowsXPwithServicePack2orWindows
Server2003withServicePack1.
Thisbookshowsyouhowtowriteprogramstargetingthe3D
graphicsAPIoftheWindowsPresentationFoundation—or"WPF
3D,"asitisknowntoitsfriends.Thisbookisessentiallya
comprehensiveexaminationofvirtuallyalltheclassesand
structuresinthe.NETnamespace
System.Windows.Media.Media3D,withplentyofcodeand
markupexamples.
TheRoleofWPF3D
WPF3Disnotintendedforgraphics-intensivepoint-of-view
games;norisitsuitableforproducingthenextbig-screenepic
featuringthree-dimensionalrodentsorogres.Programmers
whowanttopursuethosetypesofapplicationsmightbe
happierlookingatMicrosoftDirectXratherthanWPF3D.
WPF3Disinsteadintendedtogiveprogrammerstheabilityto
integrate3DintotheirclientWindowsapplications.Thisuseof
enhancedgraphicsmightbeassubtleasfashioningacontrol
thathasa3Dappearance,orusing3Dtodisplaycomplex
information,ormimickingreal-worldobjects(suchasbooks).
ThelastchapterofthisbookhassomeexamplesofWPF
applicationsincorporating3DthatIhopewillinspireyou.
AlthoughWPF3Disnotintendedforcomplexgamesormovies,
itisdefinitelybuiltforanimation.WPFincludesanextensive
animationAPIandyoucanusethatAPIwithyour3Dgraphics.
InthisbookIbegindemonstratinganimationinChapter2,
"TransformsandAnimation,"andIneverletup.Somewhat
relatedtoanimationisdatabinding.Youcanmoveortransform
3Dfiguresbybindingthemtocontrolssuchasscrollbars—
anotherofmyfavoriteactivitiesinthisbook.
AlthoughWPF3DrunsonbothWindowsVistaandWindowsXP
with.NET3.0installed,youdon'tgetexactlythesamefeatures.
EvenonWindowsVista,thequalityof3Dgraphicsisdependent
onthevideoboardyouhaveinstalledinthecomputer.Avideo
boardwithabetteron-boardgraphicsprocessingunit(GPU)
canaccomplishsomefeatsthataretooslowtobedoneentirely
insoftware.WPFgraphicscapabilitiesarecategorizedby"tiers"
thataredescribedonthisWebpage:
/>Inparticular,onlywithaTier2videoboardinstalledunder
WindowsVistadoyougetanti-aliasingin3D.(Anti-aliasingis
theuseofshadesofcolortominimizethestark"staircase"
effectcausedbyusingdiscretepixelstorepresentcontinuous
linesorsurfaces.)Inthegrandschemeofthings,anti-aliasing
mightnotsoundlikeanimportantfeature,butitmakesabig
differencewhen3Dgraphicsareanimated.
Youmightwanttogetanewvideoboardforyourforaysinto
3Dgraphics,butifyou'rewritingapplicationsforotherusers,
youmightalsowanttobeawareofthelimitationsthatsomeof
yourusersmayexperiencewhentheyrunyourprograms.
YourBackground
Inwritingthisbook,Ihaveassumedthatyoualreadyhave
experienceprogrammingfortheWindowsPresentation
FoundationusingtheC#programminglanguageandthe
ExtensibleApplicationMarkupLanguage(XAML)thatwas
introducedaspartof.NET3.0.
Ifyou'reabeginningprogrammer,Irecommendthatyoulearn
C#firstbywritingconsoleprograms,whicharecharacter-mode
programsthatrunintheCommandPromptwindow.Mybook
ProgrammingintheKeyofC#:APrimerforAspiring
Programmers(MicrosoftPress,2003)takesthisapproach.
Ifyou'reaprogrammerwhohasapreviousbackgroundinCor
C++buthasnotyetlearnedaboutprogrammingforthe.NET
FrameworkwithC#,youmightwanttobeginwithmyshort
book.NETBookZero:WhattheCorC++ProgrammerNeeds
toKnowAboutC#andthe.NETFramework.Thebookisfree
andisavailableforreadingordownloadingfromthefollowing
pageofmyWebsite:
/>Ifyou'refamiliarwithearliermanifestationsof.NETbuthaven't
yettackled.NET3.0,WPF,andXAML,mybookApplications=
Code+Markup:AGuidetotheMicrosoftWindowsPresentation
Foundation(MicrosoftPress,2006)isacomprehensivetutorial.
SeveralaspectsofWPFprogrammingaremorecrucialfor3D
thanothers.Theseare:
XAMLsyntax,includingdatabindingandresources.
Dependencyproperties.
Animationandstoryboards.
Two-dimensionalbrushes.
IfyouareanexperiencedWPFprogrammerbutyoupreferto
codeinMicrosoftVisualBasic.NEToranother.NET-compliant
language,Icanonlytellyouthatmanyoftheprogramming
examplesinthisbookareinXAMLratherthanC#.Learningat
leasttoreadC#codeandmentallytranslateitintoyour
preferredlanguagehasbecomeavitalskillin.NET
programming.
Three-dimensionalgraphicsprogrammingnecessarilyinvolves
mathematics,butI'vetriedtopresumeaminimumof
backgroundknowledge.Forexample,I'veprovidedrefreshers
onvectors,matrixalgebra,andimaginarynumbers,butI've
assumedthatyouhavenopreviousknowledgeofquaternions.
However,Idowantyoutocometothisbookwithabasic
facilitywithtrigonometry.Idon'tneedyoutoreelofflistsof
commontrigonometricidentities,butyoushouldhaveagood
workingknowledgeofangles,radians,sines,cosines,and
tangents.Ifyouknowwithoutthinkingtoohardthatthereareπ
radiansin180degrees,thatthesineof90degreesequals1,
thatthecosineofzerodegreesalsoequals1,andthatthe
tangentof45degreesequals1aswell,youshouldbeingood
shape.
SomeoftheWPF3Dclassesarespecificallyintendedtoinsulate
youfromheaviermathematicsgoingonunderthecovers.
Consequently,Icoverthoseclassesearlyinthebook.Notuntil
relativelylateinthebookdoIgetintothemoremathematicsladentopicsofmatrixtransformsandquaternions.Depending
onyourambitionsandaspirationsregarding3Dgraphics
programming,youmightfindthesechapterschallengingor
altogethertooscary.Booksaregreatforconflictslikethat
because:
Youcanskipsomethingifyoudon'twanttobotherwithit
justnow.
Youcancomebackandreadsomethinglater—perhaps
morethanonce.
Myobjectiveistohelpyou,nottortureyou.
SystemRequirements
Tocompileandruntheprogramsdescribedinthisbook,you'll
need:
WindowsVista,WindowsXPwithServicePack2,or
WindowsServer2003withServicePack1.
The.NETFramework3.0.Thisisincludedaspartof
WindowsVista;forWindowsXPorWindowsServer2003
youcandownloadithere:
/>familyid=10CC340B-F857-4A14-83F5-25634C3BF043
The.NETFramework3.0SoftwareDevelopmentKit(SDK),
availableasaDVDimagehere:
/>familyid=7614FE22-8A64-4DFB-AA0C-DB53035F40A0
orasaWebinstallhere:
/>familyid=C2B1E300-F358-4523-B479-F53D234CDCCF
MicrosoftVisualStudio2005StandardEditionor
ProfessionalEdition.
VisualStudioExtensionsfor.NET3.0,availablehere:
/>familyid=F54F5537-CC86-4BF5-AE44-F5A1E805680D
Intheory,youdon'tneedVisualStudiotocompileandrunWPF
applications.The.NETFramework3.0SDKincludesa
command-lineprogramnamedMSBuildthatbuildsWPF
applicationsfromC#project(.csproj)files.However,Visual
StudiocertainlymakesWPFdevelopmenteasier.
ThevariouslinksI'velistedfordownloadingthe.NET
Framework,theSDK,andtheVisualStudioextensionsareall
directlyaccessiblefromthe3DpageofmyWebsite:
/>Gototheheading"UsingtheBook."Underthatheadingyou'll
alsofindalinktoanEmptyProjectfileforusewithVisual
Studio2005,whichisanapproachtoWPFprogrammingthatI
prefer.(Infact,writingyourowncoderatherthanlettingVisual
Studiogeneratecodeforyouissometimesknownas"Petzold
style.")
Atthetimeofthiswriting,thenextversionofVisualStudio
(currentlycode-namedOrcas)isavailableinabetaversion.
Orcasincorporatesthe.NETFramework3.5andthe.NET
Framework3.5SDK,anddoesnotrequireany"extensions."As
Orcasbecomesmorewidelyavailable,I'llhaveinformation
aboutusingitonthe3DpageofmyWebsite.
ForwritingandexperimentingwithstandaloneXAMLfiles,you
canuseXAMLPad,whichisincludedwiththeSDK,ormyown
XamlCruncher,whichyoucaninstallfromtheWPFpageofmy
Website:
/>Inparticular,XamlCruncher2.0letsyouloadDLLfilesintothe
applicationdomain.ThesefilesarethenaccessibletotheXAML
fileyou'redeveloping.
CodeSamples
Allthecodesamplesshowninthisbook(andsomethatare
mentionedbutnotshowninthesepages)canbedownloaded
fromthebook'scompanioncontentpagemaintainedby
MicrosoftPressatthefollowingWebsite:
/>Purchaseofthisbookgivesyouaroyalty-freelicensetouseany
codesamples(ormodifiedcodesamples)youmightfinduseful
inyourownprograms,includingcommercialsoftware.(That's
oneofthepurposesofthisbook.)However,youcannot
republishthecodesamples.(That'swhythey'recopyrighted.)
ObviouslyIcan'tguaranteethatthesourcecodeisapplicable
forspecificpurposesoreventhatitworksright.(That'swhyit's
free.)
Ifyoupagethroughthisbook,you'llnoticethatithasanumber
ofpictures.Someoftheseare"screenshots"takenofthe
samplecoderunningunderWindowsVista.Butothersare
diagramsandfiguresthathelpexplaintheconceptsI'm
discussing.Alltheseotherdiagramsandfigureswerecreated
withXAMLfiles.ThenameoftheparticularXAMLfileis
indicatedinitalicsundereachofthesefigures.Youcanfind
theseXAMLfilesintheFiguresdirectoryofthedownloadable
code.RunningsomeoftheseXAMLfilesrequiresloadingthe
Petzold.Media3Dlibrary(whichI'lldescribeshortly)into
XamlCruncher2.0.
Petzold.Media3DandOtherTools
Thedownloadablecodeforthisbookalsoincludessourcecode
foradynamic-linklibrarynamedPetzold.Media3D.dllthat
containssomeclassesthatmightbehelpfulinyour3D
programming.Ifyou'rerunningXamlCruncher2.0,youcanload
thisDLLintotheprogram'sapplicationdomainandaccessit
fromXAMLfilesthatyoucreate.
MorerecentversionsofthePetzold.Media3Dlibraryare
availablefordownloadingfromthe3DpageofmyWebsite:
/>Purchaseofthisbookgivesyouaroyalty-freelicensetoinclude
thisDLLwithyourownprograms,includingcommercial
software.Youcanalsouseanyofthesourcecode(including
modifiedversionsofthesourcecode)incompilationsofyour
ownprograms.However,Irequestthatyoudonotdistribute
modifiedversionsofthelibraryitself.Ifyou'dliketoenhance
thelibraryinsomeway,dosobyderivingfromtheclassesin
thelibrary.Ialsoaskthatyoudonotdistributeanyofthe
sourcecodethatcontributestothislibrary,eitherinamodified
orunmodifiedstate.
ThePetzold.Media3DlibraryisonlyoneofseveralWPF3D
librariesavailabletotheprogrammer.Inparticular,theWPF3D
teamatMicrosofthasputtogethera3DToolslibraryavailable
here:
/>TheWPF3Dteammaintainsablogthatoftencontainsessential
informationhere:
/>
SupportforThisBook
Everyefforthasbeenmadetoensuretheaccuracyofthisbook
andthecompanioncontent.Ascorrectionsorchangesare
collected,theywillbeaddedtoaMicrosoftKnowledgeBase
article.
MicrosoftPressprovidessupportforbooksandcompanion
contentatthefollowingWebsite:
/>
QuestionsandComments
Ifyouhavecomments,questions,orideasregardingthisbook
orthecompanioncontent,orifyouhavequestionsthatarenot
answeredbyvisitingthesitespreviouslymentioned,please
sendthemtoMicrosoftPressviae-mailat:
orviapostalmailat:
MicrosoftPressAttn:3DProgrammingforWindowsEditor
OneMicrosoftWay
Redmond,WA98052-6399
PleasenotethatMicrosoftsoftwareproductsupportisnot
offeredthroughtheseaddresses.
Author'sWebSite
Informationspecifictothisbookcanbefoundonthispageof
myWebsite:
/>Informationaboutmyotherbooks,aswellasablogand
miscellaneousarticles,canbeaccessedfromthehomepageof
myWebsite.
SpecialThanks
GraphicsprogramminginWindowshasalwaysespecially
appealedtome.Inyearsgoneby,Ibeganwritingbooksabout
Windowsgraphicsprogramming—andevenoneaboutgraphics
programmingfortheOS/2PresentationManager—but
somethingelsealwayscameupandthesebookswerenever
completed.(Twocoversoftheseabandonedbookscanbeseen
atthebottomoftheBookspageofmyWebsite.)
Theprospectofwritingabookabout3Dgraphicsprogramming
forWindowswasveryexciting.AfterIbeggedtowritethis
book,myagentClaudetteMooreandMicrosoftPress
AcquisitionsEditorBenRyanhelpedmakeitreality.Thankyou
verymuch!
ApparentlyProjectEditorValerieWoolleyandTechnicalEditor
KennScribnerweresufficientlyrecoveredfromtheexperience
ofworkingwithmeonApplications=Code+Markupthatwe
wereabletoreunitethe"team"forthisbook.Iamvery
thankfulfortheirtirelessworktohelpmakethisabookwecan
holdupwithpride.
Positionedatthevanguardintheconstantbattletoprevent
civilizationfromdegeneratingintochaosandbrutalityarecopy
editors.TheyhelpkeeptheEnglishlanguagecleanfromthe
evilsofsplitinfinitives,danglingparticiples,mismatchedtenses,
andthepassivevoice.Iamforevergratefultothediligenceof
mycopyeditorBeckaMcKayinfixingmyproseandhelpingme
writewithasmuchclarityaspossible.
EricSinkandLarrySmithgraciouslyvolunteeredtoreadraw
draftsofthisbook,andIamfortunatetheydidnotalsoaskme
topayforthepsychiatriccounselingundoubtedlyvitaltotheir
recoveryfromtheexperience.Theirfeedbackandtypodetectionskillswereinvaluable.
MyfriendsatMicrosoftcontinuetobegenerouswiththeir
knowledgeandwisdom.Fromthe3DteamIthankDaniel
Lehenbauer,JordanParker,AdamSmith,GregSchechter,and
PeterAntal.Ihavealsobenefitedgreatlyfromthe
encouragementofStephenToub,PabloFernicola,TimSneath,
andPaulScholz.
Ine-mailsandblogentries,LarryO'Brien,RobHill,andNathan
Dunlaphavegivenmeadviceandlessons.Theinspirationfor
theStatePopulationAnimatorprogramcamefromadiscussion
withNeilDevadasan.
And,ofcourse,verymuchloveandthanksgotoDeirdre,who
hashelpedmakethepastdecadetheverybestyearsofmylife.
CharlesPetzold
NewYorkCityandRoscoe,NewYork
December2006–June2007
Chapter1.Lights!Camera!Mesh
Geometries!
Inthischapter:
Three-DimensionalCoordinates
8
PointsinSpace
9
IntroductiontoVectors
11
Definingthe3DFigure
15
LightsandCamera
19
TheViewport3DandItsConstituents
22
VariationsinCodeandMarkup
25
FieldsofView
29
DefiningFlatRectangles
33
Defining"Solid"Figures
37
BalancingLightSources
39
TheOrthographicProjection
43
WhyNotSharetheVertices?
46
Transparency
48
SortingOuttheClasses
50
EversinceartistsoftheUpperPaleolithicerabeganadorning
cavewallswithimagesofhuntersandtheirprey,peoplehave
strivedtodepictthree-dimensional,real-worldobjectsontwodimensionalsurfaces.Ournewspapers,magazines,books,
museums,scratchpads,photoalbums,movietheatres,video
libraries,andcomputersarefilledwiththeresults.
Humanperceptionissoattunedtothethreedimensionsofthe
realworldthatweareeasilypersuadedtoacceptevensimple
drawingsasrepresentingactualobjects.This,forexample,is
obviouslyjustageometriccircle:
Circle.xaml
Butaddalittleshading,anditbecomesaball:
Ball.xaml
Youdon'tneedany3Dprogrammingtodisplaysuchaball:The
interiorofacircleissimplycoloredwithaRadialGradientBrush.
Thecolorvariesfromredontheedges(renderedasgrayonthe
page)towhiteatthepointspecifiedbytheGradientOrigin
property.SettheGradientOriginoff-centertosuggestalight
sourcefromtheupperleft,whichhasbecomeaconventionin
on-screencomputergraphics.
Thefollowingobjectisdepictedsolelybyitsedges,andyetitis
easilyrecognizable:
SolidCube.xaml
Althoughwecan'tseetheentireobject,onlyextremeskeptics
wouldsuggestthatthebackpartoftheobjectismuchdifferent
fromthefront.Analternativeversionoftheclassiccubeshows
alltheedges:
HollowCube.xaml
Oureyesandbrainstillwanttoseethisasacube,butthey
can'tdecidewithanyassurancewhichsideisintheforeground
andwhichisinthebackground.Rationallywecanacknowledge
thatthefigureismerelytwosquareswiththeircorners
connected,butthisinformationbarelyaffectswhatweclearly
perceive.
Wesomuchwanttoseethree-dimensionalobjectsinsimple
drawingsthatevensomethingasimpossibleasthisobject
seemsoddlyreal:
DevilsPitchfork.xaml
ThatmonstrosityissometimesknownastheDevil'sPitchfork,
andforgoodreason.I'veoftenbeentemptedtotrytobuild
suchanobject,andthere'salwayspartofmynon-rationalbrain
thatinsistsitcanbedone.
AsculptureinEastPerth,Australia,hasmanagedtomimicthe
famoustrianglenamedaftermathematicianRogerPenrosebut
devisedearlierbySwedishartistOscarReutersvärd:
PenroseTriangle.xaml
ThatAustraliansculptureonlyseemstoachievethisimpossible
designwhenviewedfromtwospecificlocations.Other
impossiblestructurescanbefoundintheworksofDutch
graphicartistM.C.Escher,whosetoyingswiththeconventions
oftwo-dimensionalrepresentationsofthree-dimensionalfigures
havedelightedprogrammersandothertechiesformany
decades.
Whatisthisfigure?
OrthographicSquareCuboidOutline.xaml
Mathematicianswouldrecognizeitasasquarecuboid.Acuboid
isasolidwithsixrectangularfacesthatjoinatrightangles,
whereoppositesidesareequalindimension.Iftwoofthese
oppositesidesaresquare,thefigureisasquarecuboid.Ifall
sixsidesaresquare,thefigureissimplyacube.
Now,whatisthisfigure?
PerspectiveSquareCuboidOutline.xaml
Thetemptationistosaythatthisisalsoasquarecuboid,
becausethatisprobablythesimplestexplanation.Infact,this
isactuallyamorerealisticviewofasquarecuboidthanthefirst
rendition.Aseveryoneknows,objectsfartherfromtheeyelook
smaller,aphenomenonknownasforeshorteningorperspective.
Inreallife,thesquareatthefarendoftheobjectwouldappear
smallerthanthesquareintheforeground.
Theclassificationofthesecondlongobjectasasquarecuboid
certainlydoesn'tnegatetheearlierverdictonthefirstobject.
It'sjusttwodifferentwaysofrepresentingthree-dimensional
figuresonflatsurfaces.Inmathematicstextbooksor
engineeringdrawings,theversionwithoutperspectivewould
surelybeconsideredpreferable.(Ofcourse,youhaveto
maintainacertainamountoftrustthatyouaren'tbeing
deliberatelydeceived:thefirstofthetwofiguresmighthavea
largerbackendreducedinsizebyaperspectiverendition,while
thesecondobjectcouldreallyhaveasmallerbackend.)
Anymethodtorenderathree-dimensionalfigure—beitreal,
imaginary,orhypothetical—onatwo-dimensionalsurfaceis
knownasaprojection.Thefirstsquarecuboidwasrendered
withatypeofprojectionknownasorthographicprojection,
fromtheGreekwordorthosforstraight.(Hence,orthogonal
meansperpendicular,orthodonticsmeansstraightteeth,
orthopedicsmeansstraightlegs,andorthodoxymeans"straight
beliefs.")Thefigureisprojectedontoaviewingplaneby
imaginarylinesthatarerightanglestotheplane:
OrthographicProjection.xaml
Somedistortionmightbepresent—inthiscasethetotalheight
ofthefigureisnotrepresentedbytheprojection—butthemost
importantcharacteristicoftheorthographicprojectionisthe
preservationofparallellines.Linesthatareparallelinreallife
areparallelontheprojection.Ofcourse,theviewofthethreedimensionalobjectisdifferentdependingonthelocationofthe
projectionplane.Technicaldrawingsgenerallyuseseveral
orthographicprojectionstoshowviewsofanobjectfrom
severalsides.Orthographicprojectionsonparallelplanesare
identical.
Incontrasttoorthographicprojectionisperspectiveprojection,
whichisbasedontheworkingsofthehumaneye.Theeyeisa
complicatedmechanism,ofcourse,butforourpurposesmight
beapproximatedbyapinholecamera.Inapinholecamera,all
thelightfromafigurecomesthroughatinyholeandstrikesa
planesurface,ontowhichthefigureisprojectedupsidedown.
VisualProjection.xaml
Thelightrayspassingthroughthepinholedonotstrikethe
planeatuniformanglesastheydointheorthographic
perspective.Lightraysfromobjectsthatarefartherfromthe
pinhole(suchasthetwoprojectionlinesatthetopofthis
figure)comethroughthepinholeatamoreacuteangletoeach
otherthanforobjectsclosertothepinhole,resultinginthe
familiarforeshorteningeffect.
Thehumaneyeandaregularcameraworkmuchlikeapinhole
camera,exceptthatthepinholeisreplacedwithalens.By
refractingraysoflighttowardafocalpoint,thelensprovidesa
largeraperturethanapinholeandallowsmorelighttogetin.
Thedownsideisthatthelenscannotfocusalldistancesequally.
Butthisisn'tquiterelevantforthediscussion.
Asyoumovetheprojectionplaneclosertothepinhole,the
imagegetssmaller,andasyoumoveitfartheraway,theimage
getslarger.Buttheproportionsamongpartsoftheimage
remainthesame.However,ifyoumovethepinholecloserto
theobject,theprojectedfrontoftheobjectgetslargerin
relationtotheback,andperspectiveisexaggerated.Ifyoupull
thepinholefartherback,thedifferenceinsizebetweenthe
foregroundandbackgrounddecreases.
Inthehumaneyeandthecamera,theimageontheplaneis
upsidedown.Partiallytoavoidupside-downimagesindiagrams
suchasthese,theperspectiveprojectionisusuallydrawnlike
this:
PerspectiveProjection.xaml
Thepinholehasbeenreplacedwithafocalpoint,andthe
projectionplaneisnowbetweenthefocalpointandtheobject.
Butit'sreallythesamegeometry.Asyoumovetheprojection
planebetweenthefocalpointandtheobject,theprojected
imagegetslargerorsmaller,buttheproportionsremainthe
same.Movethefocalpointclosertotheobject,andthe
perspectiveisexaggerated.Movethefocalpointfartherback,
andtheperspectiveisdecreased.Ifyoumovethefocalpointto
infinity,theperspectiveprojectionbecomestheorthographic
projection.
TheMicrosoftWindowsPresentationFoundation(WPF)threedimensionalgraphicsclasslibrary(whichI'lloftenabbreviateas
WPF3D)performsallthemathematicsnecessarytoprojecta
three-dimensionalfigureontoatwo-dimensionalsurfacesuch
asacomputerscreenoraprinterpage.You,theprogrammer,
canselectthetypeofprojectionyouwantbychoosingoneof
theclassesthatderivefromtheabstractCameraclass.The
Cameraclassanditsderivatives,likealmostallWPF3Dclasses,
aredefinedinthe.NETnamespace
System.Windows.Media.Media3D.Thetwoclassesnamed
OrthographicCameraandPerspectiveCameraperformthe
necessarytransformationsfortheorthographicandperspective
projection.WPF3DalsoincludesaMatrixCameraclassfor
advancedpurposesthatcanperformarbitrarytypesof
projectionsofthree-dimensionalobjectsontotwo-dimensional
surfaces,butIwon'tbediscussingthatoptionuntilChapter7,
"MatrixTransforms."
Ofcourse,acameraisuselesswithoutsomethingtopointitat,
sousuallythefirststepincreatingathree-dimensionalscenein
WPF3Distodescribeafigureinthree-dimensionalspace.
Three-DimensionalCoordinates
WPF3Dusesatraditionalthree-dimensionalcoordinatesystem,
generallypicturedsomethinglikethis:
Axes.xaml
Thethreeaxesmeetatanorigin.IncreasingvaluesofXareto
theright;increasingvaluesofYareupward;increasingvalues
ofZcomeoutofthecomputerscreenandtowardtheviewer.
Thisisknownasaright-handcoordinatesystem:Ifyoupoint
theforefingerofyourrighthandinthedirectionofincreasingX
valuesandthemiddlefingerpointstoincreasingYvalues,your
thumbpointstoincreasingZvalues.
Isaidthatthediagramshowshowthecoordinatesystemis
"generallypictured"becauseitreallydependsonhowyouview
it.Youcouldviewitfromalldifferentdirections.Indeed,ifI
orientedthediagramsothattheZaxispointedexactlytoward
theviewer,theaxiswouldbevisibleonlyasapoint.The
importanceoftheright-handruleisthis:Basedonthedirection
ofanytwoaxes,youcanalwaystellhowthethirdisoriented
byapplyingtherule.
Justasthetwoaxesofthetraditionaltwo-dimensional
Cartesiancoordinatesystemdividetheplaneintofour
quadrants,threeplanesinthethree-dimensionalcoordinate