Game Graphics Programming - Free

3y ago
53 Views
5 Downloads
9.30 MB
673 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Carlos Cepeda
Transcription

GAME GRAPHICSPROGRAMMINGALLEN SHERRODCharles River MediaA part of Course Technology, Cengage LearningAustralia, Brazil, Japan, Korea, Mexico, Singapore, Spain, United Kingdom, United States

Game Graphics Programming 2008 Course Technology, a part of Cengage Learning.Allen SherrodALL RIGHTS RESERVED. No part of this work covered by the copyrightherein may be reproduced, transmitted, stored, or used in any form or byany means graphic, electronic, or mechanical, including but not limited tophotocopying, recording, scanning, digitizing, taping, Web distribution,information networks, or information storage and retrieval systems, exceptas permitted under Section 107 or 108 of the 1976 United States CopyrightAct, without the prior written permission of the publisher.Publisher and General Manager,Course Technology PTR:Stacy L. HiquetAssociate Director of Marketing:Sarah PanellaManager of Editorial Services:Heather TalbotMarketing Manager: Jordan CaseySenior Acquisitions Editor: Emi SmithProject Editor: Kate ShoupFor product information and technology assistance, contact us atCengage Learning Customer & Sales Support, 1-800-354-9706For permission to use material from this text or product,submit all requests online at cengage.com/permissionsFurther permissions questions can be emailed topermissionrequest@cengage.comAll trademarks are the property of their respective owners.Library of Congress Control Number: 2007935957Technical Reviewer: Michael DugganISBN-13: 978-1-58450-516-7CRM Editorial Services Coordinator:Jen BlaneyISBN-10: 1-58450-516-8Copy Editor: Ruth SaavedraCourse Technology25 Thomson PlaceBoston, MA 02210USAInterior Layout: Jill FloresCover Designer: Mike TanamachiCD-ROM Producer: Brandon PenticuffeISBN-10: 1-58450-615-6Cengage Learning is a leading provider of customized learning solutions withoffice locations around the globe, including Singapore, the United Kingdom,Australia, Mexico, Brazil, and Japan. Locate your local office at: international.cengage.com/regionIndexer: Valerie Haynes PerryCengage Learning products are represented in Canada by Nelson Education, Ltd.Proofreader: Michael BeadyFor your lifelong learning solutions, visit courseptr.comVisit our corporate website at cengage.comPrinted in the United States of America1 2 3 4 5 6 7 11 10 09 08

DEDICATIONThis book is dedicated to my friends and family, who have always believedin me and wished me well. This is also dedicated to you, the reader, forhonoring me by showing your support.

ACKNOWLEDGMENTSI would like to thank my friends and family for supporting me in my efforts to get into the field of game development and to make somethingout of my life that I can enjoy and be proud of. The path I’ve taken hasnot been an easy one, but it is one that I believe in and one that I willsucceed in.I would like to give thanks to Jenifer Niles, who was the first to giveme a chance after receiving the proposal for my first book, Ultimate GameProgramming with DirectX and for also being the first one to bring up andinitiate the opportunity for me to write this book on game graphics. I alsowant to give many thanks to Heather Hurley, Emi Smith, JenniferBlaney, Lance Morganelli, Kate Shoup, and the rest of the men andwomen of Charles River Media/Course Technology PTR/Cengage Learning for working so hard to make all of this possible.Also, I would like to thank you, the reader, for purchasing this book.I hope you have as much fun reading it as I had writing it.

ABOUT THE AUTHORAllen Sherrod, a DeVry University graduate in the Computer InformationSystems program, has authored games and graphics-related books including Ultimate Game Programming with DirectX (first and second editions), Ultimate 3D Game Engine Design and Architecture, and Data Structures for GameDevelopers. Allen is also the host of www.UltimateGameProgramming.com.He has written for Game Developer magazine and Gamasutra.com, and is thefounder of Re-Inventing Games & Graphics, Inc.

CONTENTSINTRODUCTIONxviiPART 1I N T R O D U C T I O N T O G AME G R A P H I C S1CHAPTER 1I N T R O D U C T I O N T O G AME G R A P H I C S3Computer Graphics in the MediaGraphics in PrintGraphics in Movies and TVComputer Graphics in Video Games2D Graphics3D GraphicsRasterization and the Rendering PipelineXNAAbout This BookPurpose of This BookPrerequisites and Prior KnowledgeTools Used in This BookSummaryChapter Questions455668912131414162021CHAPTER 22D A N D 3D G R A P H I C SBits and BytesMemory BitsMemory BytesHexadecimal ValuesColor RangesLow-Dynamic-Range ColorsHigh-Dynamic-Range ColorsAdditional Color Information232425262729292931

Contents2D GraphicsSpritesTiled Images and Backgrounds3D GraphicsThe Z BufferShading SurfacesGeometry and PrimitivesLinesPolygonsTrianglesConvex and Concave PolygonsSpheres and BoxesAdditional Geometric ObjectsLoading GeometryMathematics Used in Computer GraphicsVectors, Vertices, and lusionsQuaternion RotationsSummaryChapter QuestionsChapter ExercisesCHAPTER 3RAY TRACINGRay Tracing in Computer GraphicsForward Ray TracingBackward Ray TracingTracing PrimitivesTracing SpheresTracing PlanesTracing TrianglesTracing Additional PrimitivesImplementing Ray TracingMathematics for Ray TracingData Structures for Ray TracingThe Ray 1636466666869707175787981838585869196

viiiGame Graphics ProgrammingTracing RaysStoring Rendering Results to External FilesThe Ray Tracer’s Main Source FileReal-Time Ray TracingRay Tracing on Multi-Core ProcessorsRendering FarmsRay Tracing on the GPURay Tracing HardwareAdditional Ray Tracing TopicsSummaryChapter QuestionsChapter ExercisesCHAPTER 4RASTERIZATIONSoftware RenderingCPU Software RenderingRasterizing PrimitivesClippingScan-Line ConversionCreating, Clearing, and Displaying the CanvasDrawing PixelsDrawing LinesDrawing PolygonsRendering BuffersSecondary BuffersThe Depth BufferTertiary BuffersStencil BuffersAdditional Rasterization TopicsTransformation and SpacesBack-Face CullingOpenGLDirect3D 9 and 10Direct3D 9 DemoDirect3D 10SummaryChapter QuestionsChapter 1156156162168169170

ContentsCHAPTER 5ixPROGRAMMABLE SHADERS171Shaders in Computer GraphicsTypes of ShadersLow-Level ShadersWorking with Low-Level ShadersHigh-Level ShadersOpenGL’s GLSLOverview to GLSLSetting Up and Using GLSLGLSL Example ShaderDirect3D’s HLSLSemanticsShaders, Techniques, and PassesSetting Up and Using HLSLHLSL Example ShaderAdditional Shader Technologies and ToolsNVIDIA’s CgPixar’s RenderManSummaryChapter 3211211212212213PART 2SHADING AND SURFACES215CHAPTER 6M APPING S U R F A C E S217Texture Mapping in GamesColor FormatsImagesImage CompressionWorking with TGA ImagesWorking with DDS ImagesTexture Mapping in Graphics APIsTexture CoordinatesTexture Filtering and MipmapsOpenGL Texture Mapping in ShadersDirect3D 9 Texture Mapping in ShadersDirect3D 10 Texture Mapping in ShadersTexture CompressionColor Map CompressionDXTC Normal Map Compression3Dc 257259261

xGame Graphics ProgrammingA8L8 FormatUsing DDS Compressed Textures in ShadersSummaryChapter QuestionsChapter ExercisesCHAPTER 7262263267267268A D D I T I O N A L S URFACE M A P P I N G269Alpha MappingImplementing Alpha Maps in OpenGLImplementing Alpha Maps in Direct3DCube MappingImplementing Cube Mapping in OpenGLImplementing Cube Mapping in Direct3DReflectionsImplementing Reflection Mapping in OpenGLImplementing Reflection Mapping in Direct3DRefractionsImplementing Refraction Mapping in OpenGLRender TargetsOpenGL Frame Buffer ObjectsDirect3D 9 Render TargetsDirect3D 10 Render TargetsImage FiltersLuminance FilterSepia FilterAdditional Texture Mapping TechniquesBillboardsSuper-SamplingDynamic Cube MappingSummaryChapter QuestionsChapter 9321322323328333334334337337338339PART 3D I R E C T A N D G LOBAL I LLUMINATION341CHAPTER 8LIGHTING AND MATERIALS343Lighting OverviewLighting in Computer GraphicsTypes of Light Sources344345345

ContentsPer-Vertex and Per-Pixel LightingLight ModelsLighting TermsMaterialsImplementing LightingLambert DiffusePhongBlinn-PhongExtensions to Per-Pixel LightingBump MappingCreating Bump Map TexturesImplementing Bump MappingNormal MappingParallax MappingAdditional Lighting TechniquesPoint LightsBloomLens FlareLight ShaftsSummaryChapter QuestionsChapter ExercisesCHAPTER 9ADVANCED LIGHTING AND SHADOWSShadows in GamesReal-Time Versus Preprocessed ShadowsPopular Types of ShadowsShadow ImpostersProjection ShadowsRendering Projected ShadowsThe Shadow MatrixShadow VolumesFinding the Silhouette EdgesRendering the Shadow VolumeShadow MappingRendering with the Shadow MapSoft ShadowsLight MappingCalculating Light Map CoordinatesCalculating Lumels of a Light 4406407408410411411413

xiiGame Graphics ProgrammingDeferred ShadingCreating the G-Buffer for Deferred ShadingRendering with the G-BufferSummaryChapter QuestionsChapter ExercisesC H A P T E R 10416416417418419420G LOBAL I LLUMINATION T E C H N I Q U E S421Overview of Global IlluminationDirect Lighting versus Indirect LightingAmbient OcclusionAlternative Method for Calculating Ambient OcclusionBent NormalImplementing Ambient OcclusionSSAOPath TracingExtending the Ray Tracing AlgorithmRadiosityCalculating RadiosityForm FactorsImplementing RadiosityPhoton MappingThe kd-TreeCalculating Photon MapsApplying Photon Maps to a Ray-Traced ScenePrecomputed Radiance TransferOverview of Spherical HarmonicsCalculating Spherical Harmonics DataSpherical Harmonics Un-ShadowedSpherical Harmonics ShadowedSpherical Harmonics Inter-ReflectedSummaryChapter QuestionsChapter 7437438438439439440441443443444444445

ContentsxiiiPART 4SPECIAL EFFECTS447C H A P T E R 11S P E C I A L E F F E C T S : H IGH D YNAMIC R A N G E449Overview of HDRWhat Is HDR?Implementing HDRCreating Floating-Point Buffers and Rendering HDR DataTone MappingHDR Special Effects and Additional TopicsBloomStreaksDynamic Tone MappingSummaryChapter QuestionsChapter ExercisesC H A P T E R 12SPECIAL EFFECTS: ADDITIONAL EFFECTSBlurringDepth of FieldDepth-Based BlurringMotion BlurFast Motion BlurGeometry-Based Motion BlurPixel-Based Motion BlurParticle SystemsPoint MassesBillboards and Point SpritesSparksFireSmokeAdditional Particle EffectsParticle System DemoAdditional EffectsWeapon EffectsDynamic Decals on SurfacesSummaryChapter QuestionsChapter 82484484485

xivGame Graphics ProgrammingPART 5RENDERING NATURE487C H A P T E R 13S KY AND T E R R A I N R E N D E R I N G489Sky RenderingSky PlanesSky BoxesSky DomesCloudsTerrainsBrute Force Rendering TerrainsHeight Map TerrainsTerrain GenerationTerrain Box FilteringTexturing TerrainsTerrain PatchesAdditional TopicsTerrain DemoSummaryChapter QuestionsChapter ExercisesC H A P T E R 14WATER RENDERINGExamining Water in Modern GamesGoldeneye 007: Nintendo 64Perfect Dark: Nintendo 64Dragonball Z Budokai Tenkaichi 2: Nintendo WiiHalf-Life 2 Lost Coast: PCCrysis: PCBioShock: PC and Xbox 360Additional Water EffectsOptimizationsUnderwater RenderingAudio UnderwaterWater Splashes and InteractionWater Particle SystemsWater 9519520520521521

ContentsWater Rendering DemoSummaryChapter QuestionsChapter Exercisesxv522522522523PART 6O P T I M I Z A T I O N S A N D C ONCLUSIONS525C H A P T E R 15OPTIMIZATION527Culling GeometryFar Plane CullingBack-Face CullingFrustum CullingOcclusion CullingScene and Space PartitioningBSP TreesPotential Visibility SetsOctreesPortals and SectorsContinuous Level-of-DetailAdditional Scene Partitioning TechniquesGeometry InstancingAdditional Optimization TechniquesDynamic BranchingState ManagementSummaryChapter QuestionsChapter ExercisesC H A P T E R 16C ONCLUSIONSA Look BehindGame MathematicsRay TracingRasterizationAdvancements in Lights and ShadowsRendering People and Nature RealisticallyA Look ForwardData Structures and AlgorithmsGame Engine Design and ArchitectureFinal 557558559560562563564564566566567568569569570571

xviGame Graphics ProgrammingAPPENDIX AANSWERS TO CHAPTER QUESTIONSChapter 1 AnswersChapter 2 AnswersChapter 3 AnswersChapter 4 AnswersChapter 5 AnswersChapter 6 AnswersChapter 7 AnswersChapter 8 AnswersChapter 9 AnswersChapter 10 AnswersChapter 11 AnswersChapter 12 AnswersChapter 13 AnswersChapter 14 AnswersChapter 15 AnswersAPPENDIX BC O M P I L I N G T H E S AMPLE S OURCE C O D ECompiling on Win32Compiling on MacCompiling on LinuxAPPENDIX CRECOMMENDED RESOURCESRecommended ToolsRecommended BooksRecommended WebsitesAPPENDIX DOBJ L O A D E RThe File FormatLoading TokensLoading the OBJ FileGenerating 621

INTRODUCTIONOVERVIEW TO THIS BOOKTo say that the graphical imagery in video games is very important to thegames industry is a bit of an understatement. The graphics in games areso important that they often can make or break a game’s success. It is truethat all other aspects of a game are important, but the visuals are at timesthe main selling point along with game play, brand recognition, and soforth. This has been true for a long time in the games industry, where 3Dgames have been known for their visuals.In this book, we will examine many graphical techniques that are usedin the games industry to create cutting-edge, modern applications. Thegraphics used in games are real-time computer graphics. This means a lot ofthe information discussed in this book also applies to other graphicalrelated industries that use either real-time or non-real-time graphics, butour focus will be primarily on video games. Since this book focuses ongame graphics, we will examine many different real-time techniques aswell as some non-real-time techniques that can be preprocessed and usedin games, which is very common in video games today.By the time you reach the end of this book, you will have a firm understanding of many of the more popular effects and techniques used inmodern video games and how to implement them. This book discusses alot of theory and makes heavy use of both pseudo code and illustrationsto help make it easier for you to learn the information regardless of whatprogramming language, graphical tools, and so on you choose to use.There will also be C code samples throughout this book, but the information provided is generally not specific to any one language or tool.

xviiiGame Graphics ProgrammingWHAT’S DIFFERENT ABOUT THIS BOOKThis book takes a detailed look at computer graphics on all levels.Throughout this book, detailed and informative C source code andpseudo code is used to gain an understanding of how the different algorithms and effects are structured and how they are executed to create arendered result. One of the things that makes this book different frommany others on the market is that this book delivers its information in astraightforward manner and in a way that is not dependent on any oneprogramming language, graphical tool, operating system, and so on. Although this book is geared toward programmers, it is impossible to talkabout a book on graphics without talking about art and assets as well.Another feature that makes this book different from the rest is thatthe information is not presented in a manner that assumes you will learna technique or algorithm by reading the author’s code with no further ormore detailed explanation (i.e., explanation of the code but not the“what” or “why”). In programming, there is rarely only one way to dosomething, and in a book like this, it is important to discuss what a technique is, how a technique can be done, optimizations that can be done toimprove its performance, and alternatives, with further discussion of whythe technique exists and detailed explanations of how it works. Code willbe presented after a technique has been thoroughly discussed and hasbeen viewed and examined from many different angles. The code samples are examples of implementation. It is my hope that you will gainenough detailed information before getting to the code that you don’t actually need the code samples to implement the information yourself. Ofcourse, the code samples are there to help and to serve as an example.This book does not focus only on beginner techniques or only on advanced techniques but on game graphics as a whole. Everything fromcomplex lighting and shadowing techniques and algorithms to colors,pixels, and bits are discussed. The biggest question that will be answeredthroughout this book is “Why?”. Why would developers want to use thistechnique? Why is this specific algorithm for this effect better than othersand in what situations? Being able to answer these questions can takeyou a long way toward efficiently and effectively creating stunninggraphical scenes in your games. For many techniques, the specific algorithms and steps taken to create the effect depend on many factors thatmake the choice difficult to determine at times.

IntroductionxixWHO THIS BOOK IS FORThis book is for anyone looking to take their knowledge of computergraphics to a more advanced level. Although this book is pretty lengthy,it does not discuss in great detail everything that a complete beginnerwould need to go from novice to expert, but it does review a bit of information that all readers should not only know but have a firm understanding of. Because this is only one book with a finite size, it is assumedthat you are coming to it with at least some prior knowledge and experience with the fundamentals. Even if this knowledge comes from workingwith OpenGL or Direct3D to draw a few triangles to the screen, it helps tohave some experience.The samples in this book use the C programming language. Theyalso use either OpenGL, Direct3D, or both for graphics rendering, or theyuse ray tracing (using C ) and even, to a degree, software rendering tocreate output. If you have a graphical rendering system and programming language of your choice, you can still get a lot out of this book because the information presented is not dependent on any one of thesetechnologies. The sample code will use them but only as examples of implementation after a technique has been discussed in great detail.This book is for the following: Computer graphics students Computer graphics enthusiasts Programmers who are beginners at computer graphics but not complete novices (i.e., have at least some experience rendering geometricshapes and primitives to a window) Intermediate and advanced computer graphics programmers lookingfor an easy–to-read reference Computer graphics artists (with some knowledge of programming, atleast with programmable shaders) looking for a reference to add totheir library on computer graphicsWHAT YOU WILL NEED TO KNOW FOR THIS BOOKIn this book, it is assumed that you are familiar with a programming language such as C and that you are capable of writing applications forthe operating system and platform of your choice. It is also assumed thatyou have some experience, even if it is not a lot, rendering geometry toa window using OpenGL, Direct3D, or your own rendering routines

xxGame Graphics Programming(e.g., a software rendering system or ray tracer), and it is assumed thatyou have some mathematics background, either high school or university level, as well. Because games rely heavily on mathematics, it is assumed that you are familiar with concepts such a

ing Ultimate Game Programming with DirectX(first and second editions), Ulti-mate 3D Game Engine Design and Architecture, and Data Structures for Game Developers. Allen is also the host of www.UltimateGameProgramming.com. He has written for Game Developer magazine and Gamasutra.com, and is the founder of Re-Inventing Games & Graphics, Inc.

Related Documents:

Graphics API and Graphics Pipeline Efficient Rendering and Data transfer Event Driven Programming Graphics Hardware: Goal Very fast frame rate on scenes with lots of interesting visual complexity Pioneered by Silicon Graphics, picked up by graphics chips companies (Nvidia, 3dfx, S3, ATI,.). OpenGL library was designed for this .

Game board printable Game pieces printable Game cards printable Dice Scissors Directions Game Set Up 1. Print and cut out the game board, game pieces, and game cards. 2. Fold the game pieces along the middle line to make them stand up. 3. Place game pieces on the START square. Game Rules 1. Each player take

3D Game Programming using Microsoft's XNA Game Studio 4.0 Syllabus 17 January 2013 Dr. Kris Stewart CS 583 3D Game Programming for Simulation Prerequisites: CS 310 Data Structures or equivalent programming experience. A useful review of data structures, focused on game development, is available from the XNA Creators Club, online from Bb.

8 9/PC CNC Tool Path Graphics Programming Manual Publication 8520-PM097A-EN-P - September 2001 The control continues to plot tool paths, even if the graphics screen is not visible. The actual display of tool paths is only possible on the graphics screen. When the graphics screen redisplays, any new tool motions appear on the screen.

Foreign exchange rate Free Free Free Free Free Free Free Free Free Free Free Free Free Free Free SMS Banking Daily Weekly Monthly. in USD or in other foreign currencies in VND . IDD rates min. VND 85,000 Annual Rental Fee12 Locker size Small Locker size Medium Locker size Large Rental Deposit12,13 Lock replacement

Evolution of ODS Graphics Early Development of SAS Graphics In the beginning SAS had a less than stellar reputation regarding graphics output. PROC PLOT produced crude raster graphics using a line printer. Then there was SAS/GRAPH and visuals became better. Vector graphics used to produce quality output. Lots of options but too many to learn well (difficult to use “on the fly”).

An Introduction to R Graphics 3 This example is basic R graphics in a nutshell. In order to produce graphical output, the user calls a series of graphics functions, each of which produces either a complete plot, or adds some output to an existing plot. R graphics follows a\painters model,"which means that graphics output occurs in steps,

THE SECRET LANGUAGE OF DESIGNED BY EIGHT AND A HALF BROOKLYN, NY SCIENCE, NATURE, HISTORY, CULTURE, BEAUTY OF RED, ORANGE, YELLOW, GREEN, BLUE & VIOLET JOANN ECKSTUT AND ARIELLE ECKSTUT 15213_COLOR_001-009.indd 3 7/3/13 12:18 PM. Joann Eckstut is a leading color consultant and interior designer who works with a wide range of professionals including architects, developers and manufacturers of .