The Cg Tutorial

The Cg Tutorial is now available, right here, online. You can purchase a beautifully printed version of this book, and others in the series, at a 30% discount courtesy of InformIT and Addison-Wesley.

Please visit our Recent Documents page to see all the latest whitepapers and conference presentations that can help you with your projects.







Copyright, Dedications and Foreword

Copyright

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and Addison-Wesley was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals.

The authors and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein.

The publisher offers discounts on this book when ordered in quantity for bulk purchases and special sales. For more information, please contact:

U.S. Corporate and Government Sales
(800) 382-3419
corpsales@pearsontechgroup.com

For sales outside of the U.S., please contact:

International Sales
international@pearsontechgroup.com

Visit Addison-Wesley on the Web: www.awprofessional.com

Library of Congress Control Number: 2002117794

Copyright © 2003 by NVIDIA Corporation

Cover image © 2003 by NVIDIA Corporation

All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. Printed in the United States of America. Published simultaneously in Canada.

For information on obtaining permission for use of material from this work, please submit a written request to:

Pearson Education, Inc.
Rights and Contracts Department
75 Arlington Street, Suite 300
Boston, MA 02116
Fax: (617) 848-7047

Text printed on recycled paper at RR Donnelley Crawfordsville in Crawfordsville, Indiana.

8 9 10111213 DOC 09 08 07
8th Printing, November 2007

Dedication

For my parents and my sister

—P.R.F.

For Deirdre

—M.J.K.

Cg Language Concepts

Arrays

129

Conditional Expressions

119

Flow Control

130

Functions

43

  • Entry Functions

43

  • Internal Functions

44

  • Function Overloading

77

  • Declaring a Function

126

Identifiers

39

Math Expressions

70

Matrices

42

Operators

70

Packed Arrays

41

Parameters

 
  • Uniform Parameters

61

  • Varying Parameters

65

  • Call-by-Result Parameter Passing

81

  • Out Parameters vs. Output Structures

84

Point Sprites

154

Profiles

 
  • Vertex Program Profiles

47

  • Profile-Dependent Errors

49

  • Fragment Program Profiles

54

  • Profile-Dependent Numeric Data Types

73

  • Profile Descriptions

267

Semantics

42

Standard Library Functions

75

  • distance

134

  • dot

117

  • length

80

  • lerp

85

  • max

117

  • normalize

116

  • pow

118

173

  • refract

186

  • sincos

80

  • smoothstep

137

Structures

128

  • Output Structures

38

  • Structure Members

40

Techniques

 
  • Texture Samplers

67

  • Sampler Objects

67

  • Sampling Textures

69

  • Swizzling

113

  • Write Masking

115

  • Controlling Point Size

153

  • Cube Map Textures

170

  • Cube Map Texture Lookups

180

  • Control Maps

181

  • Normal Map Textures

201

  • Normalization Cube Maps

205

  • Projective Texturing

248

  • Querying Projective Textures

253

Type Qualifiers

 
  • uniform

63

  • const

64

Vectors

40

Figures and Plates

Figures

Figure 1-1.

A Snippet of Assembly Language Code

6

Figure 1-2 .

Forces Driving Graphics Hardware Innovation

8

Figure 1-3 .

The Graphics Hardware Pipeline

13

Figure 1-4 .

Types of Geometric Primitives

14

Figure 1-5 .

Standard OpenGL and Direct3D Raster Operations

16

Figure 1-6 .

Visualizing the Graphics Pipeline

17

Figure 1-7 .

The Programmable Graphics Pipeline

17

Figure 1-8 .

Programmable Vertex Processor Flow Chart

18

Figure 1-9 .

Programmable Fragment Processor Flow Chart

20

Figure 1-10 .

Sources of Cg's Technology Heritage

21

Figure 1-11 .

Inspirations for Cg's Development

22

Figure 1-12 .

A Shade Tree Example, Based on Rob Cook's Original SIGGRAPH Paper

24

Figure 1-13 .

How Cg Fits into a Standard Cg Application

30

Figure 1-14 .

Digital Content Creation Applications That Use Cg and CgFX

32

Figure 1-15 .

How CgFX Fits into a Standard Application

33

Figure 2-1 .

The Flow of Semantic Inputs and Outputs for C2E1v_green

45

Figure 2-2 .

Compiling and Loading a Cg Program into the GPU

52

Figure 2-3 .

Locating Error Lines in an Integrated Development Environment

56

Figure 2-4 .

A 2D Triangle for Rendering

57

Figure 2-5 .

Rendering a Triangle with C2E1v_green and C2E2f_passthrough

58

Figure 2-6 .

A 2D View of Clip Space

59

Figure 2-7 .

Primitives Rendered with C2E1v_green and C2E2f_passthrough Require 2D Clipping

59

Figure 3-1 .

Rendering a Gradiated 2D Triangle with C3E2v_varying and C2E2f_passthrough

66

Figure 3-2 .

Querying a Texture

68

Figure 3-3 .

Rendering a Textured 2D Triangle with C3E2v_varying and C3E3f_texture

70

Figure 3-4 .

C3E4v_twist Results with Different twisting Parameter Settings

80

Figure 3-5 .

Improving the Fidelity of C3E4v_twist by Increasing Tessellation

82

Figure 3-6 .

Creating a Double-Vision Effect with C3E5v_twoTextures and C3E6f_twoTextures

84

Figure 4-1 .

Coordinate Systems and Transforms for Vertex Processing

90

Figure 4-2 .

The Effect of Modeling Transformations

93

Figure 4-3 .

The Effect of the Viewing Transformation

94

Figure 4-4 .

The Effect of the Projection Matrix

96

Figure 4-5 .

Optimizations for Transforming to Clip Space

97

Figure 5-1 .

Different Lighting Models

102

Figure 5-2 .

The Emissive Term

104

Figure 5-3 .

Rendering the Emissive Term

104

Figure 5-4 .

The Ambient Term

105

Figure 5-5 .

Rendering the Ambient Term

105

Figure 5-6 .

Diffuse Light Scattering

106

Figure 5-7 .

The Diffuse Term

106

Figure 5-8 .

Rendering the Diffuse Term

106

Figure 5-9 .

Calculating Diffuse Lighting

107

Figure 5-10 .

The Specular Term

108

Figure 5-11 .

Rendering the Specular Term

108

Figure 5-12 .

Examples of Different Shininess Exponents

108

Figure 5-13 .

Calculating the Specular Term

109

Figure 5-14 .

Putting the Terms Together

110

Figure 5-15 .

Per-Vertex Lighting Results

120

Figure 5-16 .

The Effects of Tessellation on Lighting

121

Figure 5-17 .

Comparing Per-Vertex and Per-Fragment Lighting

122

Figure 5-18 .

Specifying a Spotlight Cut-Off Angle

135

Figure 5-19 .

Vectors for Calculating the Spotlight Effect

135

Figure 5-20 .

Specifying Inner and Outer Cones for a Spotlight

136

Figure 5-21 .

The Effect of Adding Inner and Outer Spotlight Cones

137

Figure 5-22 .

A Graph of the smoothstep Function

138

Figure 6-1 .

Making an Object Bulge

144

Figure 6-2 .

A Pulsating Alien

145

Figure 6-3 .

A Particle System

149

Figure 6-4 .

A Point Size Function

154

Figure 6-5 .

Converting Points to Point Sprites

155

Figure 6-6 .

A Particle System with Point Sprites

155

Figure 6-7 .

Key Frames for an Alien

157

Figure 6-8 .

An Example of Key-Frame Blending

157

Figure 6-9 .

Various Interpolation Functions

160

Figure 7-1 .

Texture Images for a Cube Map

170

Figure 7-2 .

Environment Mapping

172

Figure 7-3 .

Calculating the Reflected Ray

173

Figure 7-4 .

Reflective Environment Mapping

175

Figure 7-5 .

Refractive Environment Mapping

183

Figure 7-6 .

Snell's Law

184

Figure 7-7 .

Refraction into an Environment Map

185

Figure 7-8 .

Multiple Refractions vs. One Refraction

185

Figure 7-9 .

Understanding Chromatic Dispersion

190

Figure 7-10 .

The Fresnel Effect and Chromatic Dispersion

191

Figure 8-1 .

A Height Field Image for a Brick Bump Map

203

Figure 8-2 .

A Bump-Mapped Brick Wall with Different Light Positions

204

Figure 8-3 .

Using Cube Maps to Normalize Vectors

207

Figure 8-4 .

Consistent Texture-Space Bump Mapping vs. Inconsistent Object-Space Bump Mapping

217

Figure 8-5 .

Per-Vertex Texture Space Bases

218

Figure 8-6 .

A Tessellated Torus

219

Figure 8-7 .

Procedural Generation of a Torus from a 2D Grid

222

Figure 8-8 .

Two Bump-Mapped Brick Tori Rendered with C8E6v_torus and C8E4f_specSurf

224

Figure 8-9 .

The Same Triangle Exists in Object Space and Texture Space

225

Figure 9-1 .

Adding Uniform Fog to a Scene

234

Figure 9-2 .

Fog Particles May Affect Light Traveling from Point A to Point B

235

Figure 9-3 .

Toon Shading

242

Figure 9-4 .

A Continuous Function vs. a Step Function

244

Figure 9-5 .

Encoding a Step Function in a 1D Texture

245

Figure 9-6 .

Projective Texturing

249

Figure 9-7 .

Transformations for a Conventional Camera vs. Those for a Projector

250

Figure 9-8 .

Using Shadow Mapping to Add Shadows to a Scene

256

Figure 9-9 .

The Shadow Mapping Depth Comparison

257

Figure B-1 .

The Parts of the Cg Runtime API

285

Plates

The 31 plates listed here can be found in the color insert bound into the center of the book.

Plate 1 .

Cg Shaders in Maya 4.5 Using the Maya Cg Plug-in

Plate 2 .

Bead Shapes Rendered with Maya and Cg on the NVIDIA Quadro FX

Plate 3 .

Discreet 3ds max 5 and the 3ds max Cg Plug-in

Plate 4 .

The 3ds max Cg Plug-in and Connection Editor

Plate 5 .

Softimage|XSI v.3.0 Integrating Cg

Plate 6 .

Creating a Double Vision Effect

Plate 7 .

Combining the Ambient, Diffuse, and Specular Lighting Terms

Plate 8 .

Six Texture Images Combined to Form a Cube Map

Plate 9 .

Reflective Environment Mapping

Plate 10 .

Refractive Environment Mapping

Plate 11 .

The Fresnel Effect and Chromatic Dispersion

Plate 12 .

A Grayscale Height Field Converted to a Range-Compressed Normal Map

Plate 13 .

Bump Mapping a Textured Polygonal Mesh

Plate 14 .

Nonphotorealistic Rendering

Plate 15 .

The Dawn Character, Driven by Shaders for the Skin's Surface, Skeletal Skinning, and Shape Blending

Plate 16 .

NVIDIA Time Machine Demo

Plate 17 .

NVIDIA Dancing Ogre Demo

Plate 18 .

Yeti's Gun Metal Game, Using Cg for Advanced Visual Effects

Plate 19 .

Iritor Online, Using Cg Shaders

Plate 20 .

Procedural Wood Shader

Plate 21 .

Depth of Field

Plate 22 .

Dynamic Reaction Diffusion Textures

Plate 23 .

Relief Texture Mapping

Plate 24 .

Bump Reflection Mapping

Plate 25 .

Detail Normal Maps

Plate 26 .

Water Interaction

Plate 27 .

A Procedural Terrain Demo

Plate 28 .

Realistic Fresnel Reflection Effects

Plate 29 .

The NVIDIA Cg Browser Interface

Plate 30 .

A Mechanical Model with a Gooch Cg Shader Applied

Plate 31 .

Using CgFX to Apply Multiple Shaders to a Ray Gun Model

 

Examples

Example 2-1.

The C2E1v_green Vertex Program

38

Example 2-2.

The C2E2f_passthrough Fragment Program

53

Example 3-1.

The C3E1v_anyColor Vertex Program

62

Example 3-2.

The C3E2v_varying Vertex Program

65

Example 3-3.

The C3E3f_texture Fragment Program

67

Example 3-4.

The C3E4v_twist Vertex Program

79

Example 3-5.

The C3E5v_twoTextures Vertex Program

83

Example 3-6.

The C3E6f_twoTextures Fragment Program

85

Example 3-7.

The C3E7f_twoTextures Fragment Program

86

Example 4-1.

The C4E1v_transform Vertex Program

97

Example 5-1.

The C5E1v_basicLight Vertex Program

111

Example 5-2.

The C5E2v_fragmentLighting Vertex Program

124

Example 5-3.

The C5E3f_basicLight Fragment Program

125

Example 5-4.

The C5E4v_twoLights Vertex Program

131

Example 5-5.

The C5E5_computeLighting Internal Function

132

Example 5-6.

The C5E6_attenuation Internal Function

133

Example 5-7.

The C5E7_attenuateLighting Internal Function

135

Example 5-8.

The C5E8_spotlight Internal Function

136

Example 5-9.

The C5E9_dualConeSpotlight Internal Function

139

Example 5-10.

The C5E10_spotAttenLighting Internal Function

139

Example 6-1.

The C6E1v_bulge Vertex Program

145

Example 6-2.

The C6E2v_particle Vertex Program

152

Example 6-3.

The C6E3v_keyFrame Vertex Program

159

Example 6-4.

The C6E4v_litKeyFrame Vertex Program

161

Example 6-5.

The C6E5v_skin4m Vertex Program

166

Example 7-1.

The C7E1v_reflection Vertex Program

177

Example 7-2.

The C7E2f_reflection Fragment Program

180

Example 7-3.

The C7E3v_refraction Vertex Program

187

Example 7-4.

The C7E4f_refraction Fragment Program

188

Example 7-5.

The C7E5v_dispersion Vertex Program

193

Example 7-6.

The C7E6f_dispersion Fragment Program

195

Example 8-1.

The C8E1v_bumpWall Vertex Program

205

Example 8-2.

The C8E2f_bumpSurf Fragment Program

206

Example 8-3.

The C8E3v_specWall Vertex Program

208

Example 8-4.

The C8E4f_specSurf Fragment Program

209

Example 8-5.

The C8E5v_bumpAny Vertex Program

216

Example 8-6.

The C8E6v_torus Vertex Program

223

Example 9-1.

The C9E1f_fog Fragment Program

240

Example 9-2.

The C9E2v_fog Vertex Program

240

Example 9-3.

The C9E3v_toonShading Vertex Program

247

Example 9-4.

The C9E4f_toonShading Fragment Program

248

Example 9-5.

The C9E5v_projTex Vertex Program

254

Example 9-6.

The C9E6f_projTex Fragment Program

254

Example 9-7.

The C9E7v_screenAlign Vertex Program

260

Example 9-8.

The C9E8f_tint Fragment Program

260

Example 9-9.

The C9E9f_a_over_b Fragment Program

261

Example 9-10.

The C9E10f_a_in_b Fragment Program

262

Example 9-11.

The C9E11f_a_out_b Fragment Program

262

Example 9-12.

The C9E12f_a_dissolve_b Fragment Program

262

Example C-1.

A Sample CgFX File

295

Tables

Table 1-1.

Features and Performance Evolution of Selected NVIDIA GPUs, by Generation

12

Table 2-1.

Cg Vertex Profiles

47

Table 2-2.

Cg Fragment Profiles

55

Table 3-1.

Cg Sampler Types

68

Table 3-2.

Precedence, Associativity, and Usage of Operators

72

Table 3-3.

Data Types for Various Profiles

75

Table 3-4.

Selected Cg Standard Library Functions

76

Table 5-1.

Application-Specified Data for the Graphics Pipeline

112

Table 6-1.

Variables in the Particle Equation

151

Table 7-1.

Application-Specified Parameters for Per-Vertex Environment Mapping

176

Table 7-2.

Indices of Refraction

184

Table 7-3.

The C7E5v_dispersion Program Parameters

192

Table E-1.

Mathematical Functions

302

Table E-2.

Geometric Functions

307

Table E-3.

Texture Map Functions

308

Table E-4.

Derivative Functions

310

Table E-5.

Debugging Function

310

 

Equations

Equation 3-1.

2D Rotation

81

Equation 4-1.

Converting Between Nonhomogeneous and Homogeneous Positions

91

Equation 6-1.

Particle Trajectory

150

Equation 6-2.

Linear Interpolation

158

Equation 7-1.

Vector Reflection

173

Equation 7-2.

Snell's Law

184

Equation 7-3.

An Approximation of the Fresnel Equation

189

Equation 8-1.

A Rotation Matrix Formed by Tangent, Binormal, and Normal Column Vectors

215

Equation 8-2.

Cross-Product Relationships Between Tangent, Binormal, and Normal Vectors

215

Equation 8-3.

Parametric Equations for a Torus

219

Equation 8-4.

Partial Derivatives of the Parametric Torus

220

Equation 8-5.

The Normal of a Surface Expressed in Terms of Its Parametric Inverse Gradients

221

Equation 8-6.

The Tangent, Binormal, and Normal on a Surface

221

Equation 8-7.

Plane Equation Coefficients for (x, s, t) Plane for a Single-Textured Triangle

225

Equation 8-8.

Object-Space Partial Derivatives for a Texture-Space Triangle in Terms of the Texture Coordinates

226

Equation 9-1.

Uniform Fog

238

Equation 9-2.

The Sequence of Transformations for Projective Texturing

252

 

Foreword

Real-time computer graphics hardware is undergoing a major transition, from supporting a few fixed algorithms to being fully programmable. At the same time, the performance of graphics processors (GPUs) is increasing at a rapid rate—even greater than that of CPUs—because GPUs can effectively exploit the enormous parallelism available in graphics computations. These improvements in GPU flexibility and performance are likely to continue in the future, and will allow developers to write increasingly sophisticated and diverse programs that execute on the GPU.

Until recently, most GPU programs were written in assembly language, but history has shown that developers make the most creative and effective use of programmable hardware when they have the opportunity to program in a high-level language. Our goal in designing Cg was to provide developers with the same flexibility and performance available in assembly language, but with the expressiveness and ease-of-use of a high-level language. The C language has demonstrated enormous success in achieving these goals on the CPU, and so we chose C's syntax and philosophy as the starting point for defining Cg. In particular, this choice gave us confidence that the Cg language would be able to implement any GPU program, rather than restricting developers to a predefined framework designed specifically for shading computations.

Cg also builds on ideas and lessons learned from earlier work in computer graphics. My personal interest in programmable graphics hardware was inspired by the PixelFlow project at the University of North Carolina and, in particular, by the shading language compiler that Marc Olano and others built for PixelFlow. In many respects, the most direct predecessor to Cg was the real-time programmable shading system that Kekoa Proudfoot, Pat Hanrahan, I, and others built at Stanford for single-chip GPUs. The knowledge that we acquired from building the Stanford system was crucial to the design of Cg. Offline movie rendering has relied on programmable shading for much longer. The RenderMan language designed by Pat Hanrahan at Pixar served as a major source of inspiration for Cg, particularly in the choice of Cg's built-in functions.

The desire to create one GPU programming language that would be widely supported for both the OpenGL and Direct3D APIs led us to collaborate with Microsoft on the design of Cg. Microsoft's implementation of the language is called HLSL, and it is shipped as part of DirectX 9. At Microsoft, Craig Peeper and Loren McQuade were particularly influential in the design of the language. The examples in this book work equally well with HLSL and Cg.

Designing and implementing Cg in less than a year was possible only because we had a large and highly talented team of people working together. Two individuals made particularly unique contributions. Steve Glanville's extensive compiler and language expertise was crucial to the Cg design effort, and he implemented most of the front end of the first version of the Cg compiler. Kurt Akeley's experience as a system designer was invaluable throughout the project.

In this book, Randy and Mark have assembled a series of Cg tutorials that introduce Cg while simultaneously describing many of the real-time shading techniques supported by modern GPUs. By integrating these two sets of concepts within one collection of tutorials, this book enables you to experience the fun of writing and experimenting with your own GPU programs. Enjoy the journey!

Bill Mark

Cg Language Lead Designer

Assistant Professor

The University of Texas at Austin

Preface

Once upon a time, real-time computer graphics was all about vertices, triangles, and pixels. In fact, it still is. However, the level at which a programmer controls the processing and appearance of these graphics primitives has advanced considerably. Until a few years ago, programmers had to rely on the CPU to process all the transformation and rasterization algorithms needed to produce computer-generated images. Over time, hardware engineers executed these algorithms via specialized, high-performance 3D graphics hardware. Rather than implement the algorithms directly, programmers learned to access the hardware-provided graphics functionality through standard 3D programming interfaces, such as OpenGL (developed by Silicon Graphics [SGI]) and Direct3D (developed by Microsoft). At first, such costly 3D graphics hardware appeared only in high-priced UNIX workstations and flight simulators. Now, through the miracle of Moore's Law, the benefits of graphics hardware acceleration have been bestowed on low-cost PCs and game consoles.

Although the performance gained by employing dedicated graphics hardware to execute the brute-force tasks of transforming vertices, rasterizing triangles, and updating pixels far exceeded the performance possible just with CPU programming, real-time 3D programmers gave up a considerable measure of control in exchange for this speed. Developers were limited to using a fixed-function palette of graphics operations that the hardware could handle. Sometimes a skilled and dedicated programmer could coax the graphics programming interface and hardware to accomplish something beyond the ordinary, but this was usually hard, time-consuming work.

While graphics hardware engineers were advancing the real-time performance of their specialized pixel-pushing hardware, off-line computer graphics software packages such as Pixar's PhotoRealistic RenderMan were changing the look of movies and television with amazing computer-generated special effects. The pre-recorded nature of movies and most television content makes these media well suited for offline rendering. Computer-generated images for film and video are not rendered in real time but instead carefully constructed frame by frame in hours, days, or weeks using standard general-purpose CPUs. The advantage of using general-purpose CPUs is that rather than settle for hard-wired hardware algorithms, programmers and artists can use the CPU to create any effect they might imagine. What these so-called offline rendering systems lack in relative speed, they make up in rendering quality and realism.

The flexibility and generality of offline rendering systems are the key features that have been missing from preceding generations of 3D graphics hardware. In other words, what was lost was programmability.

Realizing this limitation, computer graphics architects have designed a new generation of graphics hardware that permits an unprecedented degree of programmability. Now, many of the programmable shading techniques that are employed so successfully in offline rendering can enter the realm of real-time graphics.

Developers of offline rendering systems created a type of specialized computer language known as a shading language to express the graphics operations required to make surfaces look the way artists intend. A shading language for programmable graphics hardware provides the same sort of functionality but in the context of real-time graphics hardware. Graphics programmers and artists benefit from such a high-level programming language in much the same way that conventional programmers do from C++ or Java. Using a high-level language for graphics hardware automates the process of translating the programmer's intent into a form that the graphics hardware can execute.

This book is about Cg, the premier language for programmable graphics hardware. NVIDIA developed Cg in close collaboration with Microsoft. Cg is the most portable and productive way for you to unleash the power within programmable graphics hardware. This book is a tutorial to teach you how to write Cg programs.

Our Intended Audience

We tried to write this book in a way that makes it valuable to both novices and advanced readers. If you're new to the world of programmable graphics, this book should give you a firm foundation on which to build. If you encounter a word or concept that is foreign to you and not sufficiently explained, consult the "Further Reading" section at the end of each chapter.

The main audience for this book is 3D game and application programmers, managers of such projects, real-time 3D artists, and computer graphics students—or anyone else interested in learning about the state of the art in real-time rendering. You do not have to be an experienced programmer to learn Cg from this book, though you should be relatively familiar with programming language concepts. If you are familiar with C or one of its derivatives, such as C++ or Java, Cg will be very approachable. Cg programs are relatively short, often less than a page, so even an artist or novice programmer can get the gist of Cg from this tutorial and learn to write interesting Cg programs.

Computer graphics programming involves math. Understanding basic algebra and trigonometry will help you appreciate several sections. You should also be familiar with the math behind basic computer graphics vertex transformation and lighting models. You do not need to know OpenGL or Direct3D, but familiarity with either programming interface is very helpful. All of the Cg examples described work with either OpenGL or Direct3D unless otherwise noted. Some examples that require advanced Cg functionality may not work on older graphics processors.

The Book's Structure

Chapter 1 introduces Cg. Each chapter that follows is a short tutorial that presents specific Cg concepts and techniques. The tutorials build upon each other, so we recommend reading the chapters in order.

This book gets you started but does not contain everything you will eventually want to know about Cg. This tutorial complements other documentation (such as the Cg Toolkit User's Manual: A Developer's Guide to Programmable Graphics) included with the Cg Toolkit. Please consult the user's manual and other Cg documentation for further information.

Formatting Conventions

Various elements in this book are specially formatted for easier reading. Code samples are written in the Courier font on a light reverse highlight. Variables and keywords are in bold Courier in the text, and key concepts are italicized.

In addition, we use icons to identify special topics, as shown here.

Trying the Examples

We've designed the accompanying software framework so that you can get straight to work, even if you don't know anything about OpenGL, Direct3D, C, or C++. Our goal is to isolate the Cg language and allow you to experiment freely with it. Of course, as you move toward starting a real-world application with Cg, your project will probably require some combination of OpenGL, Direct3D, C, and C++.

The accompanying software framework allows you to try out the various Cg examples in the book without worrying about graphics APIs, C, or C++ code. The latest versions of the applications are free to download via the book's companion Web site. The software on the accompanying CD works only on the Windows platform, but versions for Linux and Macintosh systems are available online. Appendix A explains how to download the latest versions of Cg and the accompanying tutorial application.

The tutorial application makes it easy for you to tweak the book's examples, to see how changing a particular Cg example can immediately affect the rendered 3D result. If you can, have a computer that supports Cg nearby to try out the examples. With our software, you just write Cg programs without worrying about the particulars, such as loading 3D models and textures. When you want to know all the gory details, examine the source code, all of which is freely available for download, so you can see how Cg interfaces with C++ and OpenGL or Direct3D. The Cg Toolkit also comes with several simple examples that you can learn from.

The end of each chapter includes suggested exercises that you can work on to explore Cg further.

Acknowledgments

We would like to thank our many colleagues at NVIDIA who contributed to Cg and helped us with this book. Bill Mark, Steve Glanville, Mark Kilgard, and Kurt Akeley worked to define the original Cg language in 2001 and 2002. David Kirk, Jensen Huang, Dwight Diercks, Matt Papakipos, and Nick Triantos recognized the need for a high-level language for graphics processors and provided the resources necessary to make Cg a priority and a reality in just over a year's time. Geoff Berry, Michael Bunnell, Chris Dodd, Cass Everitt, Wes Hunt, Craig Kolb, Jayant Kolhe, Rev Lebaredian, Nathan Paymer, Matt Pharr, Doug Rogers, and Chris Wynn developed the Cg compiler, Standard Library, and runtime technology. Sim Dietrich, Ashu Rege, and Sébastien Dominé worked on the original CgFX technology. Chris Seitz gave us a great deal of support in all aspects of the project, helping out in ways that are too numerous to list, but without which this book would not exist. John Spitzer provided the clear foresight, as well as the essential resources, for Cg's development, and gave us the backing from his team to make this book possible. Sanford Russell's contagious motivation helped to get this book started. Cyril Zeller created the handy tutorial framework that accompanies this book and contributed the material for Appendix B. Sim Dietrich shared his knowledge of CgFX in Appendix C. Kevin Bjorke lent his insight by writing the compositing section of the advanced chapter. Teresa Saffaie, Catherine Kilkenny, and Debra Valentine reviewed our writing in an effort to make it clear. Caroline Lie, Spender Yuen, Dana Chan, Huey Nguyen, and Steve Burke lent their creativity and imagination to design and beautify the book's cover, figures, and artwork. NVIDIA's demo team (Curtis Beeson, Dan Burke, Joe Demers, Eugene d'Eon, Steve Giesler, Simon Green, Daniel Hornick, Gary King, Dean Lupini, Hubert Nguyen, Bonnie O'Clair, Alexei Sakhartchouk, and Thant Tessman, under the direction of Mark Daly) contributed several of the color plates.

We are also grateful to Jason Allen, Geoff Berry, Michael Bunnell, Sim Dietrich, Chris Dodd, Gihani Fernando, Simon Green, Larry Gritz, Eric Haines, Wes Hunt, Gary King, Craig Kolb, Jayant Kolhe, Eric Lengyel, Cameron Lewis, Gilliard Lopes, Viet-Tam Luu, Kurt Miller, Tomas Akenine-Möller, Russell Pflughaupt, Matt Pharr, John Spitzer, Nick Triantos, Eric Werness, Matthias Wloka, Cyril Zeller, and our anonymous reviewers for their invaluable comments in the review process. Each set of comments helped to make the book clearer and more accurate.

Microsoft and NVIDIA collaborated to agree on the syntax and semantics of a standard hardware shading language. The DirectX 9 High-Level Shading Language and Cg are the same language because of this effort. We particularly appreciate the work of Craig Peeper, Loren McQuade, Dave Aronson, Anuj Gosalia, Chas Boyd, and Mike Toelle.

We acknowledge the pioneering research on hardware shading languages conducted at the University of North Carolina and Stanford University. Obviously, Pixar's RenderMan Shading Language provided a great deal of inspiration for NVIDIA's efforts to develop a real-time language for mass-market graphics hardware. Ken Perlin's work on the Pixel Stream Editor, not to mention his early Cg compiler testing, deserves recognition as well.

On the hardware front, we acknowledge the fundamental work of Erik Lindholm and Henry Moreton, who architected the user-programmable vertex processing engine inside NVIDIA's GeForce3 GPU. OpenGL's and Direct3D's support for general programmable vertex processing, and hence Cg's support for the same, are indebted to this work.

The hard work and dedication of NVIDIA's architecture, hardware, and software engineers to deliver ever faster and ever more programmable graphics processors was and still is the overriding justification for Cg. We acknowledge the efforts of all the engineers at NVIDIA who strive to make real-time programmable shading a reality for everyone.

We thank the Addison-Wesley production team for making this book a reality. We particularly thank Chris Keane for manhandling our manuscript into shape.

Finally, we thank the thousands of Cg developers for their feedback, bug reports, patience, and enthusiasm.


Copyright

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and Addison-Wesley was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals.

The authors and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein.

The publisher offers discounts on this book when ordered in quantity for bulk purchases and special sales. For more information, please contact:

U.S. Corporate and Government Sales
(800) 382-3419
corpsales@pearsontechgroup.com

For sales outside of the U.S., please contact:

International Sales
international@pearsontechgroup.com

Visit Addison-Wesley on the Web: www.awprofessional.com

Library of Congress Control Number: 2002117794

Copyright © 2003 by NVIDIA Corporation

Cover image © 2003 by NVIDIA Corporation

All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. Printed in the United States of America. Published simultaneously in Canada.

For information on obtaining permission for use of material from this work, please submit a written request to:

Pearson Education, Inc.
Rights and Contracts Department
75 Arlington Street, Suite 300
Boston, MA 02116
Fax: (617) 848-7047

Text printed on recycled paper at RR Donnelley Crawfordsville in Crawfordsville, Indiana.

8 9 10111213 DOC 09 08 07
8th Printing, November 2007

Developer Site Homepage

Developer News Homepage



Developer Login

Become a
Registered Developer




Developer Tools

Documentation

DirectX

OpenGL

GPU Computing

Handheld

Events Calendar



Newsletter Sign-Up

Drivers

Jobs (1)

Contact

Legal Information



Site Feedback