ShaderX2: Shader Programming Tips & Tricks with DirectX 9 Edited by Wolfgang F. Engel Wordware Publishing, Inc. LibraryofCongressCataloging-in-PublicationData ShaderX2:shaderprogrammingtipsandtrickswithDirectX9/editedby WolfgangF.Engel. p. cm. Includesbibliographicalreferencesandindex. ISBN1-55622-988-7(paperback,companionCD-ROM) 1. Computergames--Programming. 2. Three-dimensionaldisplaysystems. I.Title:ShaderXsquared. II. Engel,WolfgangF. QA76.76.C672S482003 794.8'16693--dc22 2003018871 CIP ©2004,WordwarePublishing,Inc. AllRightsReserved 2320LosRiosBoulevard Plano,Texas75074 Nopartofthisbookmaybereproducedinanyformorbyanymeans withoutpermissioninwritingfromWordwarePublishing,Inc. PrintedintheUnitedStatesofAmerica ISBN1-55622-988-7 10 9 8 7 6 5 4 3 2 1 0308 CrystalReportsisaregisteredtrademarkofCrystalDecisions,Inc.intheUnitedStatesand/orothercountries. NamesofCrystalDecisionsproductsreferencedhereinaretrademarksorregisteredtrademarksofCrystalDecisionsorits Screenshotsusedinthisbookremainthepropertyoftheirrespectivecompanies. Allbrandnamesandproductnamesmentionedinthisbookaretrademarksorservicemarksoftheirrespectivecompanies. Anyomissionormisuse(ofanykind)ofservicemarksortrademarksshouldnotberegardedasintenttoinfringeonthe propertyofothers.Thepublisherrecognizesandrespectsallmarksusedbycompanies,manufacturers,anddevelopersasa meanstodistinguishtheirproducts. Thisbookissoldasis,withoutwarrantyofanykind,eitherexpressorimplied,respectingthecontentsofthisbookandany disksorprogramsthatmayaccompanyit,includingbutnotlimitedtoimpliedwarrantiesforthebook’squality,performance, merchantability,orfitnessforanyparticularpurpose.NeitherWordwarePublishing,Inc.noritsdealersordistributorsshallbe liabletothepurchaseroranyotherpersonorentitywithrespecttoanyliability,loss,ordamagecausedorallegedtohavebeen causeddirectlyorindirectlybythisbook. All inquiries for volume purchases of this book should be addressed to Wordware Publishing,Inc.,attheaboveaddress.Telephoneinquiriesmaybemadebycalling: (972)423-0090 Contents Preface vii AbouttheAuthors ix Introduction xix SectionI—GeometryManipulationTricks 1 UsingVertexShadersforGeometryCompression 3 DeanCalver UsingLookupTablesinVertexShaders 13 CarstenWenzel TerrainGeomorphingintheVertexShader 18 DanielWagner 3DPlanetsontheGPU 33 JesseLaeuchli ClothAnimationwithPixelandVertexShader3.0 40 KristofBeets CollisionShaders 58 TakashiImagire DisplacementMapping 73 TomForsyth SectionII— RenderingTechniques 87 RenderingObjectsasThickVolumes 89 GregJames Screen-alignedParticleswithMinimalVertexBufferLocking 107 O’dellHicks HemisphereLightingwithRadiosityMaps 113 ShawnHargreaves iii Contents GalaxyTextures 123 JesseLaeuchli TurbulentSun 127 JesseLaeuchli Fragment-levelPhongIllumination 131 EmilPersson SpecularBumpMappingonPre-ps_1_4Hardware 149 MatthewHalpin VoxelRenderingwithPS_3_0 161 AaronBurton SimulatingBlendingOperationsonFloating-pointRenderTargets 172 FrancescoCarucci RenderingVolumesinaVertex&PixelProgrambyRayTracing 177 EliZ.Gottlieb NormalMapCompression 185 JakubKlarowicz DropsofWaterandTextureSprites 190 SylvainLefebvre AdvancedWaterEffects 207 KurtPelzer EfficientEvaluationofIrradianceEnvironmentMaps 226 Peter-PikeJ.Sloan PracticalPrecomputedRadianceTransfer 232 Peter-PikeJ.Sloan AdvancedSkyDomeRendering 240 MarcoSpoerlandKurtPelzer DeferredShadingwithMultipleRenderTargets 251 NicolasThibieroz Meshuggah’sEffectsExplained 270 CarstenWenzel LayeredCarPaintShader 293 JohnIsidoro,ChrisOat,andNatalyaTatarchuk MotionBlurUsingGeometryandShadingDistortion 299 NatalyaTatarchuk,ChrisBrennan,AlexVlachos,andJohnIsidoro iv Contents SimulationofIridescenceandTranslucencyonThinSurfaces 309 NatalyaTatarchukandChrisBrennan Floating-pointCubeMaps 319 ArkadiuszWaliszewski StereoscopicRenderinginHardwareUsingShaders 324 ThomasRued Hatching,StrokeStyles,andPointillism 340 KevinBuchinandMaikeWalther LayeredFog 348 GuillaumeWerle DenseMatrixAlgebraontheGPU 352 ÁdámMoravánszky SectionIII—SoftwareShadersandShaderProgrammingTips 381 SoftwareVertexShaderProcessing 383 DeanP.Macri x86Shaders–ps_2_0ShadersinSoftware 396 NicolasCapens SoftD3D:ASoftware-onlyImplementationof Microsoft’sDirect3DAPI 413 OliverWeichhold NamedConstantsinShaderDevelopment 432 JeffreyKiel SectionIV—ImageSpace 437 AdvancedImageProcessingwithDirectX9PixelShaders 439 JasonL.Mitchell,MarwanY.Ansari,andEvanHart NightVision:FrameBufferPost-processingwithps.1.1Hardware 465 GuillaumeWerle Non-PhotorealisticPost-processingFiltersinMotoGP2 469 ShawnHargreaves ImageEffectswithDirectX9PixelShaders 481 MarwanY.Ansari UsingPixelShaderstoImplementaMosaicEffectUsing CharacterGlyphs 519 RogerDescheneauxandMauriceRibble v Contents MandelbrotSetRendering 526 EmilPersson Real-TimeDepthofFieldSimulation 529 GuennadiRiguer,NatalyaTatarchuk,andJohnIsidoro SectionV—Shadows 557 SoftShadows 559 FlavienBrebion RobustObjectIDShadows 580 SimDietrich ReverseExtrudedShadowVolumes 587 RenaldasZioma SectionVI—3DEngineandToolsDesign 595 ShaderAbstraction 597 TomForsyth Post-ProcessFunwithEffectsBuffers 614 TomForsyth ShadersunderControl(CodecreaturesEngine) 625 OliverHoeller ShaderIntegrationintheGamebryoGraphicsEngine 631 ScottSherman,DanAmerson,ShaunKime,andTimPreston VertexShaderCompiler 650 DavidPangerl ShaderDisassembler 667 Jean-SebastianLuce Index 675 vi Preface AfterthetremendoussuccessofDirect3DShaderX:VertexandPixelShaderTips andTricks,Iplannedtodoanotherbookwithanentirelynewsetofinnovative ideas,techniques,andalgorithms.Thecallforauthorsledtomanyproposalsfrom nearly80peoplewhowantedtocontributetothebook.Someoftheseproposals featuredintroductorymaterialandothersfeaturedmuchmoreadvancedthemes. Becauseofthelargeamountofmaterial,Idecidedtosplitthearticlesintointro- ductorypiecesthataremuchlongerbutexplainalotofgroundworkandarticles thatassumeacertaindegreeofknowledge.Thisidealedtotwobooks: ShaderX2:Introductions&TutorialswithDirectX9 ShaderX2:ShaderProgrammingTips&TrickswithDirectX9 Thefirstbookhelpsthereadergetstartedwithshaderprogramming,whereas thesecondbook(thisone)featurestipsandtricksthatanexperiencedshader programmerwillbenefitfrom. AswithDirect3DShaderX,JavierIzquierdoVillagrán([email protected]) preparedthedraftsforthecoverdesignofbothbookswithin-gamescreenshots fromAquanox2,whichwerecontributedbyIngoFrick,thetechnicaldirectorof MassiveDevelopment. Anumberofpeoplehaveenthusiasticallycontributedtobothbooks: WessamBahnassi AndreChen MuhammadHaggag KennethL.Hurley EranKampf BrianPeltonen MarkWang Additionally,thefollowingShaderX2authorsproofreadseveralarticleseach: DeanCalver NicolasCapens TomForsyth ShawnHargreaves JeffreyKiel HunYenKwoon MarkusNuebel MichalValient OliverWeichhold vii Preface Thesegreatpeoplespentalotoftimeproofreadingarticles,proposingimprove- ments,andexchanginge-mailswithotherauthorsandmyself.Theirsupportwas essentialtothebookdevelopmentprocess,andtheirworkledtothehighquality ofthebooks.Thankyou! AnotherbigthankyougoestothepeopleintheMicrosoftDirect3Ddiscus- siongroup(http://DISCUSS.MICROSOFT.COM/archives/DIRECTXDEV.html). Theywereveryhelpfulinansweringmynumerousquestions. AswithDirect3DShaderX,thereweresomedrivingspiritswhoencouraged metostartthisprojectandholdonthroughthesevenmonthsittooktocomplete it: DeanCalver(Eclipse) JasonL.Mitchell(ATIResearch) NatashaTatarchuk(ATIResearch) NicolasThibieroz(PowerVR) CarstenWenzel(Crytek) Additionally,IhavetothankThomasRuedfromDigitalArtsforinvitingmetothe VisionDaysinCopenhagen,Denmark,andforthegreattimeIhadthere.Iwould liketothankMatthiasWlokaandRandimaFernandofromnVidiaforlunchatGDC 2003.Ihadagreattime. Asusual,thegreatteamatWordwaremadethewholeprojecthappen:Jim Hill,WesBeckwith,HeatherHill,BethKohler,andPaulaPricetookoverafterI sentthemhundredsofmegabytesofdata. TherewereothernumerouspeopleinvolvedinthisbookprojectthatIhave notmentioned.Iwouldliketothankthemhere.Itwasapleasureworkingwithso manytalentedpeople. Specialthanksgoestomywife,Katja,andourdaughter,Anna,whospenta lotofeveningsandweekendsduringthelastsevenmonthswithoutme,andto myparents,whoalwayshelpedmetobelieveinmystrength. —WolfgangF.Engel P.S.:PlansforanupcomingprojectnamedShaderX3arealreadyinprogress.Any comments,proposals,andsuggestionsarehighlywelcome([email protected]). viii About the Authors DanAmerson DangraduatedfromNorthCarolinaStateUniversityin2001withabachelor’s degreeincomputerscience.Duringhisundergraduatestudies,hefocusedonarti- ficialintelligenceresearchforautomatedcameracontrolandpositioning.After graduation,DanjoinedNDLinlate2001toworkontheNetImmerseandGame- bryoengines.Heworksprimarilyonconsolerenderingtechnologiesandmost recentlyservedasleadprogrammerfortheGamebryoshaderdemoEturnum. MarwanY.Ansari([email protected]) Marwanisamemberofthe3DApplicationResearchGroupatATIResearch.He receivedamaster’sdegreeincomputersciencefromtheUniversityofIllinoisat Chicagoandabachelorofsciencedegreeincomputerscienceandmathematics fromDePaulUniversity.PriortomovingtoATI’s3DApplicationResearchGroup, heworkedonOpenGLdriversforNumberNineVisualTechnologybeforejoining ATI’sDigitalTVgroup.InadditiontohisimagespacecontributionstoShaderX2, MarwanhasalsocontributedtoGameProgrammingGems4andspokenabout real-timevideoprocessingusingshadersattheGameDevelopersConference. KristofBeets([email protected]) Kristoftookhisfirststepsinthe3Dworldbyrunningatechnical3Dfansite,cov- eringtopicssuchasthedifferencesbetweentraditionalandtile-basedrendering technologies.Thisinfluencedhiselectricalengineeringstudiesinsuchawaythat hewrotehisthesisaboutwaveletcompressionfortexturesinDirect3D,apaper thatwontheBelgianBarcoPrize.Hecontinuedhisstudies,obtainingamaster’s degreeinartificialintelligence,whileworkingasatechnicaleditorforBeyond3D andwritingvarioustechnicalarticlesabout3Dhardware,effects,andtechnology. Asafreelancewriterhewrotethe“FSAAExplained”documentfor3DfxInterac- tivetoexplainthedifferencesbetweenvarioustypesoffull-screenanti-aliasing. Thisdocumentresultedinafull-timejobofferat3Dfx.Currentlyheisworkingas adeveloperrelationsengineerforPowerVRTechnologies,whichincludes researchintonewgraphicalalgorithmsandtechniques. FlavienBrebion([email protected]) FlavienhashadapassionforvideogamessincehegotanAmstradCPCattheage of12.Hestillrememberstypinginhundred-pagelistingsjusttoseeasmallsprite appearon-screen.HestudiedcomputingscienceattheUniversityofNantes, France,wherehegraduatedwithbothbachelor’sandmaster’sdegreesin2000. Hehasalsodonealotofresearchanddevelopedmanysmallgamesandrendering enginesonhisown.CurrentlyheworksatVRcontext,avirtualrealitycompany ix