Professional Documents
Culture Documents
y HistoryofOpenGL
y Understandingthebackwardcapabilitiesandsomeofthe
Understandingtheback wardcapabilitiesandsomeofthe
uglinessinthecurrentspecification.
y HistoryofShadingLanguages
y HistoryofGraphicsHardware
Hi fG hi H d
y Understandwherewecamefromandwhysomeofthe
literature/websourcesmaynolongerbevalid.
RogerCrawfis y AppreciatemodernStreambasedArchitectures.
TheOhioStateUniversity y ReviewofOpenGLandbasicComputerGraphics
y TheOpenGL1.0pipelineandtheOpenGL3.0pipeline
TheOpenGL1 0pipelineandtheOpenGL3 0pipeline
y TheOpenGLShadingLanguage GLSL
y Simplemodelviewerapplication(lab1)
y ImplementingaTrackballinterface y ReviewandMidterm
y FrameBufferObjects y TheGPUvs.theCPU
y Multitexturinganda3DPaintapplication(lab2) y Performancetrends
y EnvironmentMapping y VirtualMachineArchitecture(DirectX10)
y NormalandDisplacementMapping y SpecificHardwareImplementations
y Lab3. y ATIRadeon9700
y nVidiatimelineandtheG80architecture.
nVidiatimelineandtheG80architecture
y XBox360.
y FutureTrends
y Mixedcores
y IntelsLarrabee
y Lab3specification(multiplerendertargetsand y FinalProjectspecifications
geometryshaders) y Aliasing
y Hierarchicalzbufferandzculling y FourierTheory
y Shadowalgorithms y Fullscreenantialiasing
y Planarshadows
Pl h d y Texturefilteringandsampling
y Ambientocclusion
y Shadowmapfiltering
y Shadowvolumes
y Shadowmaps
y Aliasingandprecisionissues
y OpenGLinamultithreadingcontext y Nonphotorealisticrendering
y Highperformancerendering y Volumerendering
y Frustumculling y Specialtopics
y Clipmapping y AnimationandSkinning
y Prerequisites
y CSE581 orknowledgeofOpenGLandbasiccomputer y RealTimeRenderingby
graphics(linearalgebra,coordinatesystems,light
hi (li l b di t t li ht TomasAkenineMoller,
TomasAkenineMoller
models). EricHainesandNaty
y Goodprogrammingskills(C/C++/C#)
p g g ( ) Hoffman(3rd edition)
y InterestedinComputerGraphics:
y Lovegraphicsandwanttolearnmore
y Bewillingtolearnthingsbyyourselfandtryoutcoolstuff
z OpenGLShading z AdvancedGraphics
LanguagebyRandiJ. ProgrammingUsing
Rost,Addison Wesley
Rost,AddisonWesley OpenGLbyTom
p y
McReynoldsandDavid
z TheOrangeBook
Blythe(Publisher:Morgan
Kaufmann/Elsevier)
y Threelabsandonefinalproject: 50%
y Threeindividuallabs
y 3DGamesI/IIbyAlan y Smallteamproject(gradversusundergrad)
S ll j ( d d d)
WattandFabio y Midtermexam: 20%
Policarpo,Addison
p
y Finalexam:
Fi l 20%
%
Wesley
y Misc 10%
y OpenGLProgramming
y homeworkorquiz
G id (O
Guide(OpenGL2.0),
GL )
y classattendance
AddisonWesley
y SIGGRAPHTutorialsand
papers
y Advancedrealtimerenderingalgorithms(GPUbased) y Graphicsrendering
y WewilluseOpenGLastheAPI youneedtoknow pipeline Application
pp
howtoprogramOpenGL (ifnot,youneedtolearnby y Geometryprocessing
yourself) y Rasterization
Geometry
Rasterizer
Image
y ProgrammableShaders
y Visibilityandocclusion
y Advancedtexture cullingtechniques
g q
mappingalgorithms y Selectedadvancedtopics
y Perspectivecorrection y Levelofdetail
y Bumpmapping
B i y Nonphotorealistic
Non photorealistic
y Environmentmapping
rendering
y Volumerendering
y Antialiasing y SkinningandAnimation
Ski i dA i i
y Geometry
y Textures
y Shadowalgorithms
y AlllabsaretobedoneonMicrosoftWindowsmachines y Pre1992
y 2DGraphics GTK
usingVisualStudio2008inC++orC#.
y 3D IRISGL,ANSI/ISOPHIGS,PEX
y 1992 OpenGL1.0
y YouwillneedaDirectX10classgraphicscard(nVidia y PHIGSkiller
Ge o ce 8800 o bette , o
GeForce8800orbetter,orATIRadeon2400orbetter).
Radeo 400 o bette ). y ControlledbytheARB(ArchitectureReviewBoard)
y 1995 OpenGL1.1
y TextureObjects
y GraphicsLab CL112DhasseveralPCswithnVidia y VertexArrays 3DGraphicsstarttoflourish
p
GeForce8800GTXcards.Thesemachinesarereservedfor y 1998 OpenGL1.2 onthePCataboutthistime
thegraphicscourses,sokickotherstudentsout. y 3DTextures
y ImagingSubset
y Note:Dr.Parent
Note:Dr ParentsAnimationProjectcourseisalsothis
sAnimationProjectcourseisalsothis
y 1998 OpenGL1.2.1
quarterandtheyneedtoaccesstosomeofthemachines y ARBextensionmechanism
y thathaveMayainstalled. y MultitexturingARBextension
y 2000 OpenGL1.3 y 2004 OpenGL2.0
y Multitexturing y ProgrammableShaders
y TextureCombiners(Yuck!) y MultipleRenderTargets
y Multisampling y PointSprites
y Compressedtexturesandcubemaptextures y NonPowerofTwoTextures
y 2001
2001 OpenGL1.4
OpenGL1 4 y 2006
2006 OpenGL2.1
OpenGL2 1
y DepthTextures y ShaderLanguage1.2
y PointParameters y sRGBTextures
y Variousadditionalstates
V i dditi l t t y 2008 OpenGL3.0
y 2003 OpenGL1.5 y Deprecationmodel!
y OcclusionQueries y FrameBufferObjects
y Texturecomparisonmodesforshadows y ShaderLanguage1.3
y VertexBuffers y TextureArrays
y ProgrammableShadersintroducedasanARBextension.
g y KhronosGroupcontrolled
p
Texture y RenderMan
Map y Cg
Combine
Li ht
Light verticesinto
i i
Depthtest
y HLSL
triangle,
Transform Texturemap,
Convertto
Finalcolor
Alphatest y GLSL1.0
Project fragments, Blending
IInterpolate
l y GLSL1.2
GLSL1 2
Vertex Triangle Fragment Raster Frame y Automaticintegertofloatconversion
Shader Setup Shader Operations buffer y Initializersonuniformvariables
y Centroidinterpolation
y GLSL1.3
y Integersupport
y Texelaccess(avoidsampler)
y Texturearrays
y ShadeTreesbyRobertCook(SIGGRAPH1984) y Stillheavilyusedinfeaturefilmproductions.
y Usesatreestructuretodeterminewhatoperationsto y Entirecareersfocusedaroundshaderdevelopment.
perform.
y ReallytookoffwithPerlinsandPeacheysNoise
functionsandshadingresultsatSIGGRAPH1985.
functionsandshadingresultsatSIGGRAPH1985
[Proudfoot2001]
y CgwasdevelopedbynVidia y OpenGLsbelatedentry.
y HLSLwasdevelopedbyMicrosoft y Wewillstudythisinmoredepthshortly.
y Theyworkedverycloselytogether.Assuchthereislittle
Theyworkedverycloselytogether Assuchthereislittle
differencebetweenthetwolanguages.
y Differenceisintheruntime.
structVERT_OUTPUT{
float4position:POSITION;
float4color:COLOR;
};
VERT_OUTPUTgreen(float2position:POSITION)
{
VERT_OUTPUTOUT;
OUT position
OUT.position =float4(position 0 1);
=float4(position,0,1);
OUT.color =float4(0,1,0,1);
returnOUT;
}
y Therehavebeenmanyothershadinglanguages, y EarlyHistory
targetingdifferentcapabilities. y FlightSimulators EvansandSutherland
y Sh y CAD
CAD Workstations
Workstations SGI,DEC,HP,Apollo
SGI DEC HP Apollo
y Visualization
y Brooks
y Stellar(1989?)
y CUDA y Ardent
Ad t
y OpenCL y SGI
y Ashli y Entertainment(Hollywood)
y Cray
C
y CustomHardware PixarImageComputer
y Itisimportanttonote,thatthisearlyexcitementin3D
p y 3
graphicsinthelate1980sandearly1990ssetthestage
forthePCboom.
GenerationI:3dfxVoodoo(1996) GenerationII:GeForce/Radeon7500(1998)
Oneofthefirsttrue3Dgamecards Hardwarebasedtransformationandlighting(TnL)
Addonforastandard2Dvideocard. calculations.
l l
VertextransformationsontheCPU Multitexturingsupport.
Texturemappingandz buffering
Texturemappingandzbuffering. AGPbus
http://accelenation.com/?ac.id.123.2
PCIbusbecomesthebottleneck nVidiacoinsthetermGPU,ATIcounterswiththe
http://accelenation.com/?ac.id.123.5 termVPU(VisualProcessingUnit).
D i d i b b ttl k
Devicedriverbecomesabottleneck
Rasterization Fragment
g Rasterization Fragment
g
Vertex Primitive Frame Vertex Primitive Frame
and and
Transforms Assembly Operations Buffer Transforms Assembly Operations Buffer
Interpolation Interpolation
AGP http://accelenation.com/?ac.id.123.8
Rasterization Fragment
Vertex Primitive Frame
and Rasterization Programmable
Transforms Assembly Operations Buffer Vertex Programmable Frame
Interpolation and Fragment
Transforms Vertex shader
Interpolation Processor Buffer
GPU
Small vertex
AGP GPU
shaders
Texture Memory
GenerationV:GeForce6/X800(2004)
GeForce 7800 GTX GeForce 7900 GTX ATI Radeon X1800 ATI Radeon X1900
Simultaneous rendering to multiple buffers
True conditionals and loops Transistor Count 302 million 278 million 321 million 384 million
T
Texture access b
by vertex shader
h d Die Area 333 mm2 196 mm2 288 mm2 352 mm2
PCI-e bus Core Clock Speed 430 MHz 650 MHz 625 MHz 650 MHz
More memory/program length/texture accesses
# Pixel Shaders 24 24 16 48
GPU is idle
idle, move towards smarter fragments
fragments, rather
than more and more geometry. # Pixel Pipes 24 24 16 16
# Texturing Units 24 24 16 16
Rasterization Programmable #V
Vertex Pi
Pipes 8 8 8 9
Vertex Programmable Frame
and Fragment
Transforms Vertex shader
Interpolation Processor Buffer Memory Interface 256 bit 256 bit 256 bit ext (512 int) 256 bit ext (512 int)
Mem Clock Speed 1.2 GHz GDDR3 1.6 GHz GDDR3 1.5 GHz GDDR3 1.55 GHz GDDR3
Peak Mem Bwdth 38.4 GB/sec 51.2 GB/sec 48.0 GB/sec 49.6 GB/sec
PCI-Express GPU
Texture Memory
Texture Memory
GenerationV:GeForce8800/HD2900(2006) y Normalmapping(Direct3D9)
y RedesignoftheGPU(morelater)
y SupportforDirectX10(morelater)
Suppo t o ect 0 ( o e ate )
y GeometryShader
y Madnesscontinues andyougettobepartofit!
Programmable Programmable
Input Programmable Raster
Geometry Pixel
Assembler Vertex shader Operations
Shader Shader
PCI-Express
Output
Merger
y DisplacementMapping(Direct3D10) y Wherearewenowinthisrapideraofmindblowing
performancewithunleashedcreativity?
y ThelatestnVidiaoffering,theGeForceGTX280,hasupwards
ThelatestnVidiaoffering theGeForceGTX280 hasupwards
of1.4Billiontransistors!
y DirectX10.1hasbeenreleased.
y DirectX11addsthreenewstagesbetweenthevertexshader
andthegeometryshader.
y HullShader
HullShader takesinthecontrolpointsforapatch andtells
thetessellatorhowmuchtogenerate(OnTessellating?).
y Tessellator Fixedfunctionunitthattake
y DomainShader
D i Sh d Posttessellatorshader(OnTessellated?)
P tt ll t h d (O T ll t d?)
y Rumorsofaccesstotheframeanddepthbuffersinthe
future.
y Thenextfewimagesareactuallyalittleold,butshowofftheDirectX10
classhardware.
Thief
AgeofConan
Stormrise
y OpenGLis: y LinearAlgebra
y AlowlevelAPI y CoordinateSystems
y OSindependent
OSi d d y Transformations
y Windowsystemindependent y Projections
y Consortiumcontrolledstandard y Lighting
g g
y Gourandslightingmodelandshading
y GeometryinOpenGLconsistsofpoints,lines,
y Phongslightingmodelandshading
triangles,quadrilateralsandageneralpolygon.
y Note:OpenGL1.5cannotfullyimplementPhonglighting.
Note:OpenGL1 5cannotfullyimplementPhonglighting
y OpenGLallowsfordifferentappearancesthrough y Othermajorlightingmodels
changesinstate settings y TextureMapping
y Currentcolor
l y Parameterization
y Currentnormal y Sampling
y Lightingenabled/disabled y Filtering
A li ti
Application
y Thepipelinediagramdoesnotdotheprocessjustice.
y ThinkofanOpenGLmachineasasimplifiedassemblyline.
Vertex Shader
y ToproducewidgetA:
ToproducewidgetA
transformedverticesanddata
y Stopassemblyline
GeometryShader y Loadpartsintofeedbins
Note:Alloftheshadershave
y S
SetoperationsandstatefortheAsprocessassembly
i d f h A bl
accessto(pseudo)constants
(moreonthislater). y Restarttheassemblyline
Rasterizer y StreamspartsforAthroughtheline
texture F
Fragmentswithinterpolateddata
i hi l dd y ToproducewidgetB:
y Stopassemblyline
Fragment Shader
y Loadpartsintofeedbins
p
pixelcolor,depth,stencil(orjustdata) y SetoperationsandstatefortheBsprocessassembly
Compositor y Restarttheassemblyline
y StreamspartsforBthroughtheline
p g
Display
y Inreality,therearethreesimultaneousassemblylines 1. TheVertexShader
runningatthesametime.SimilartoplantAproduces y Takesinasinglevertexandassociateddata(called
pistons,PlantBproducesenginesandPlantC
i t Pl tB d i dPl tC attributes
tt ib t normal,color,texturecoordinates,etc.).
l l t t di t t )
producescars. y Outputsasinglevertex(3Dpoint)andassociateddata
y Yes,Iambeingabstract.
Yes Iambeingabstract (
(notnecessarilythesamedatafromabove).
y )
y Previousprogrammingtothepipelinerequiredyouto
mapdatatospecificconcreteobjects,soitactually
p p j , y
helpstothinkoftheOpenGLpipelineabstractlyfirst. Vertex Shader
transformedverticesanddata
2. TheGeometryShader 3. TheFragmentShader(PixelShaderinDirectX)
y Takesasinputaprimitive(e.g.atriangle)definedasa y Takesasinputafragment(pixellocation),thedepth
collectionofvertices,anddataassociatedateachvertex.
ll ti f ti dd t i t d t h t associatedwiththefragmentandotherdata.
i t d ithth f t d th d t
y Mayalsohaveaccesstoadjacentprimitivesandtheir y Outputseither:
verticesanddata. y Nothing
g killsthefragment
g
y Outputseither: y AsingleRGBAcolorandadepthvalue
y Nothing killstheprimitive y AcollectionofRGBAcolorvaluesandasingledepthvalue
y Asimilarprimitiveorsetofprimitiveswithassociateddata.
Asimilarprimitiveorsetofprimitiveswithassociateddata y Acollectionofdataandasingledepthvalue
y Acompletelydifferentprimitive(e.g.alinestrip)orsetof y Mayalsoincludeasingleoptionalstencilvalue
primitivesandassociateddata.
Depthwithinterpolateddata
Primitiveanddata
GeometryShader Fragment Shader
Color(s) depth stencil(orjustdata)
Color(s),depth,stencil(orjustdata)
Primitive(s)anddata
y Somekeypointstoconsider/remember: y So,tomakeafunctional
y Ifthewrongpartsarefeedintothesystemthenthe OpenGLShader
Vertex Shader
resultsaremeaninglessortheassemblylinecrashes.
lt i l th bl li h P
Program,weneedto
dt
transformedverticesanddata
y Forexample,ifhexnutboltsareneededandphillips connectthethree
screwsarefeedintothesystemthemanifoldsmayfalloff. GeometryShader
independentshaders
p
y Whatotherresourcesdoesthesystemhaveaccessto? together.
y Somethinglikegreasemaybeconsideredaninfiniteresource Rasterizer
atoneormorestations. y But,theydonot
Fragmentswith
F i h
y Thespecificlocationsofweldingsitesandboltplacement. connect!!! texture
interpolateddata
y HowdowepreventonePlant fromeitherswamping Fragment Shader
anotherplantwithpartsorpreventingitfromrunning pixelcolor,depth,stencil
pixelcolor depth stencil
(orjustdata)
duetolowinventory?
Compositor
Display
TopSecret
p
TopSecret
y TopSecretisnotthepropertermthere,butrather
verttexStream
InitialVertex
List<T>
Transformed
BeyondYour(Current)Control.Icouldhaveput
Stream
<U>>
dataformat
Vertexdata
triangleStreeam
V>
ReProcessed
format
P i iti A
PrimitiveAssemblyandRasterization,butthereare
bl dR t i ti b tth
List<Triangle<
Vertexdataformat
L
List<V
fragmentS
afewmorethingsgoingon.Wewilllookatmore
detailsofthiswhengoevendeeperintothepipeline.
g p pp
Vertex
Shader
Geometry Fragment y IalsousedTriangle inList<Triangle<U>> tomakeit
Shader
Shader clearthattheprimitivetypesdonotneedtomatch
m
vertexStream
Transformed
(thisisC#/.NETsyntaxbtw).
List<U>
gmentStream
List<Prrimitive<V>>
y Fornow,realizethatthedatatypesneedtomatchand
otherthanthat,theshadersareindependent.
th th th t th h d i d d t
frag
trian
TopSecret
RasterOps
TopSecret
y Tomakethingsalittlemoreclearer,letslookataspecific y Ifallwehaveisthestream,thenweneedanewshaderfor
instanceofthetypes.Thisissimilartobasicfixed eachlittletweak.
functionalityforalit material Note thestructsarefor
functionalityforalitmaterial.Note,thestructsarefor y Shaderscanbeparameterized
Sh d b t i d beforetheyareturnedon
b f th t d
illustrationonly. (theassemblylineisrestarted).
class MyShader{
T InitialVertexData
T U TransformedVertexData
U public
bli Color
l BrickColor
i k l { get; set; }
struct VertexNormal { struct VertexColor { public Color MortarColor { get; set; }
public IEnumerable<VertexColor> ProcessStream(IEnumerable<VertexNormal> vertexStream);
Point vertex; Point vertex; }
Vector normal; Color color;
} }
y ProcessStream willusethevaluesofBrickColor and
MortarColor.
V Re
V ReProcessedVertexData D FinalFragmentData
D y WeneedamechanismtocopydatavaluesfromCPU
W d h i t d t l f CPU
struct VertexColor { struct VertexColor {
Point vertex; float depth; memory(mainmemory)toGPUmemory.Wedonotwant
Color color; Color color; toaccessmainmemoryforeveryelementinastream.
} }
y InOpenGLtheseparameterizedvaluesarecalled y TextureMemoryishandledspecially:
uniformvariables. 1. ItisalreadyaGPUresource,soitmakesnosenseto
y Theseuniformvariables/constantscanbeusedwithin copyitover.
it
ashaderontheGPU. 2. Additionalprocessingofthedataisusuallywantedto
p
providewrappingandtoavoidaliasingartifactsthat
pp g g
y SettingthemisdoneontheCPUusingthesetof
areprevalentwithtexturemapping.Thislatterissueis
glUniformAPImethods(morelater). knownastexturefiltering.
y Thenumberandsizeoftheseconstantsis 3 Aswewillsee,texturescanalsobewrittenintoonthe
3. Aswewillsee texturescanalsobewrittenintoonthe
implementationdependent. GPU.Readonlymemorysemanticsallowbetter
y Theyarereadonly(akaconstants)withintheshader.
y y optimizationsthanread/writememoryaccessesina
parallelprocessingscenario.Assuch,texturesareread
onlywhenusedinashader.
y Allthreeshaderscanaccesstexturemaps
Allthreeshaderscanaccesstexturemaps.
y C++/Clike y Firstclass2D4Dvectorsupport:
y Basicdatatypes: y Floatbased:vec2,vec3,vec4
y void useformethodreturnsignatures y Intbased:ivec2,ivec3,ivec4
I b d i i i
y bool Thekeywordstrueandfalseexist(notanint) y Boolbased:bvec2,bvec3,bvec4
y int
int 32bit.Constantswithbase10,base8orbase16.
32 bit Constantswithbase 10 base 8orbase 16 y UnsignedIntbased(1.30):uvec2,uvec3,uvec4
UnsignedInt based(1.30):uvec2,uvec3,uvec4
y float IEEE32bit(asof1.30). y Initializedwithaconstructor
y uint(1.30) 32bit. vec3 eye = vec3(0.0,0.0,1.0);
3 point
vec3 i t = vec3(eye);
3( )
y Variablescanbeinitializedwhendeclared.
Componentwise
y Overloadedoperatorsupport;
int i, j = 45; multiplication
fl
float pii = 33.1415;
1415 vec3
ec3 sum = eeye
e + point;
float log2 = 1.1415f; vec3 product = eye * point;
bool normalize = false; float delta = 0.2f;
uint
u t mask
as = 0xff00ff00 sum = sum + delta;
y Componentaccess: y Firstclassmatrixsupport
y Asinglecomponentofavectorcanbeaccessedusingthedot y Squarefloatbased:mat2,mat3,mat4,mat2x2,mat3x3,
operator(e
. operator(e.g.,eye.xisthefirstcomponentofthevec3).
g eye xisthefirstcomponentofthevec3) mat4x4
t
y Sincevectorsareusedforpositions,colorsandtexture y Nonsquarefloatbased:mat2x3,mat2x4,mat3x2,
coordinates,severalsequencesaredefined:
mat3x4,mat4x2,mat4x3
3 4, 4 , 4 3
y x,y,z,w
y r,g,b,a y Usually,multiplicationiscomponentwise(itisnota
y s,t,p,q dotproductwithvectors).Matricesaretheexception.
y Masking Thesefollowthenormalmathematicalrulesofvector
h f ll h l h l l f
y Canusetheaccessorstomaskcomponents: matrixandmatrixmatrixmultiplication.
y vec2p=eye.ey;
vec2p eye.ey;
y Swizzling
y Canalsochangeorder:eye.yx
y Samplers y GLSLallowsforarraysandstructs
y SamplersareequivalenttoTextureUnits(glActiveTexture).
y Arraysmustbeaconstantlydeclaredsize.
y Youindicatewhattypeoftextureyouexpectinthisslotwith
thesamplertype(23texturetypes!): y Thetypeswithinastructmustbedeclared.
y SAMPLER1D,SAMPLER2D,SAMPLER3D,SAMPLERCUBE,SAMPLER1DSHADOW,
SAMPLER2DSHADOW,SAMPLER1DARRAY,SAMPLER2DARRAY,SAMPLER1DARRAY
SHADOW,SAMPLER2DARRAYSHADOW,SAMPLERCUBESHADOW,INTSAMPLER
, , ,
1D,INTSAMPLER2D,INTSAMPLER3D,INTSAMPLERCUBE,INTSAMPLER1DARRAY,
INTSAMPLER2DARRAY,UNSIGNEDINTSAMPLER1D,UNSIGNEDINTSAMPLER2D,
UNSIGNEDINTSAMPLER3D,UNSIGNEDINTSAMPLERCUBE,UNSIGNEDINT
SAMPLER1DARRAY,orUNSIGNEDINTSAMPLER2DARRAY
y Aruntime(nonfatal)errorwilloccurifthetexturetypeand
Arun time(non fatal)errorwilloccurifthetexturetypeand
indicatedsamplertypearenotthesame.
y DirectX10isseparatingtheconcernsofasamplerfromthat
ofatexture Currentlyeachtextureneedsitsownsampler
ofatexture.Currentlyeachtextureneedsitsownsampler.
y Usedwithbuiltintexturingfunctions(morelater)
y Declaredasuniformvariablesorfunctionparameters(read
only).
only)
y Const y OpenGL3.0
y Usedtodefineconstants
y VaryingandAttributeisbeingdeprecatedinfavorofin,
y Usedtoindicateafunctiondoesnotchangetheparameter
g p
out,centroidinandcentroidout.
t t idi d t id t
y Uniform
y PseudoconstantssetwithglUniformXXcalls.
y Functionparameterscanalsouseaninout attribute.
y Globalinscope(anymethodcanaccessthem). y Centroidqualifierisusedwithmultisamplingand
q p g
y Readonly. ensuresthesamplelieswithintheprimitive.
y Setbeforethecurrentstream(beforeglBegin/glEnd).
y Outvariablesfromvertexshadersandinvariablesfrom
y Attribute f
fragmentshaderscanalsospecifyoneofthefollowing:
t h d l if fth f ll i
y Deprecated Usein inthefuture y Flat nointerpolation
y Theinitialpervertexdata
y Smooth perspectivecorrectinterpolation
y V
Varying
i y Noperspective linearinterpolation
y Deprecated Useout inthefuture
y Indicatesanoutputfromthevertexshadertothefragmentshader
y YoucandefineandcallfunctionsinGLSL. y GLSLdefinesmanybuiltinfunctions,fromsimple
y Norecursion interpolation(mix,step)totrigonometricfunctions,to
y Regularscopingrules
graphicsspecificfunctions(refract,reflect).
hi ifi f ti ( f t fl t)
y Note:Uniformvariablescanbespecifiedatthe
y Almostallofthesetakeeitherascalar(float,int)ora
ffunctionlevel.Theyarestillaccessibletoallroutines.
i l l Th ill ibl ll i vector.
vector
Ifspecifiedintwodifferentcompileunits,theyare y Afullcomplementofmatrixandvectorfunctions.
merged Differenttypesforthesameuniformname
merged.Differenttypesforthesameuniformname y Someofthesimplerfunctionsmaybemappeddirectly
willresultinalinkerror. tohardware(inversesqrt,mix).
y SeethespecificationortheOpenGLShading
p p g
LanguageQuickReferenceGuide formoredetails.
y Alltextureaccessreturna4componentvector,evenif y Otherfunctions:
thetextureisonlyonechannel. y Thefragmentshadercantakethederivativeofanyvalue
y PriortoShadingLanguage1 3 thesewereallfloat soit
PriortoShadingLanguage1.3,thesewereallfloat,soit beinginterpolatedacrossthetriangleusingthedfdxand
b i i t l t d th t i l i th dfd d
returnedavec4. dfdyfunctions.
y Thetexturefunctiontakesasamplerasitsfirstinput,
p p y ThereisabuiltinnoisefunctionforPerlinlikenoise.
andatexturecoordinateasitssecondinput.
y Optionalbias,offsetorLODispossibleinseveralof
thevariants.
thevariants
y Seethespecformoredetails.
y OpenGL3.0addedtheabilitytoinquirethetexture
sizeintexels,accessaspecifictexelandspecifythe
gradienttouseforfiltering.
y Mostofthestatevariablesarebeingdeprecatedin y Special VertexBuiltinvariables
OpenGL3.0
in int gl_VertexID;
gl VertexID; // may not be define in all cases
y Thesevariablesallowashadertocommunicatewith
theoldfixedfunctionalitypipeline. out vec4 gl_Position; // must be written to
y VertexShader y FragmentShader
y Computeprojectedposition y Lookup(sample)thetexturecolor
y Computevertexcolor
C l y Multiplyitwiththebasecolorandsetthefinalfragment
M l i l i i h h b l d h fi lf
y Computevertextexturecoordinates color.
y Note:Thedepthisnotchanged
p g
void main() y gl_FragDepth=gl_FragCoord.z
{
// transform vertex to clip space coordinates
uniform sampler2D texture;
gl Position = gl_ModelViewProjectionMatrix
gl_Position gl ModelViewProjectionMatrix * gl
gl_Vertex;
Vertex;
void main()
// Copy over the vertex color.
{
gl_FrontColor = gl_Color;
vec4 color = texture2D( texture, gl_TexCoord[0].st );
// transform texture coordinates
gl_FragColor = gl_Color * color;
gl TexCoord[0] = gl_TextureMatrix[0]
gl_TexCoord[0] gl TextureMatrix[0] * gl
gl_MultiTexCoord0;
MultiTexCoord0;
}
}
y Somethingstonote: y OK,wecandefinethesekernels,buthowdowetell
1. Thereisamain()forboththevertexandthefragment thesystem(OpenGL)tousethem?
shader
h d y TwonewobjectsinOpenGL
2. Thereisnoconceptofthestream y ShaderRoutine acompilationunit
33. Datacannotbesharedbetweeninstances y ShaderProgram alinkedunit
4. Thereislittletonodifferencebetweenthebuiltin y Settingupyourshaderprogramthentakesafewsteps:
stateanduserdefineduniformvariables. 1. Createobjecthandlersforeachroutine.
2
2. Loadthesourceintoeachroutine
Loadthesourceintoeachroutine.
y Thesearereallykernels.Thereareappliedtothe
3. Compileeachroutine.
stream(similartotheSelect clauseinLINQorSQL).
4. Createobjecthandlerfortheshaderprogram
class MyShader{
public Color BrickColor { get; set; }
5. A
Attacheachroutinetotheprogram
h h i h
public Color MortarColor { get; set; }
public IEnumerable<VertexColor> ProcessStream(IEnumerable<VertexNormal> vertexStream,
6. Linktheprogram
}
Func<VertexNormal,VertexColor> kernel); 77. Usetheprogram
p g
y LetslookatsomeofmyC#codefordoingthis.Below
aresomeofthepertinentsnippets. 1 namespace OhioState.Graphics
2 {
namespace OhioState.Graphics 3 /// <summary>
{ 4 /// Represents a shader program used for rendering.
/// <summary> 5 /// </summary>
/// This interface represents a shader routine; 6 public interface IShaderProgram
/// </summary>
</ > 7 {
public interface IShaderRoutine 8 /// <summary>
{ 9 /// Make the shader active.
/// <summary> 10 /// </summary>
/// Get or set shader content. 11 /// <param
p name="panel">The
p <typeparamref
yp p name="IRenderPanel"/>
/// </summary> 12 /// for the current context.</param>
string ShaderContent { get; set; } 13 void MakeActive(IRenderPanel panel);
/// <summary> 14 /// <summary>
/// Compile the shader. 15 /// Deactivate the shader.
/// </summary>
</ > 16 /// </summary>
/// <param name="resourceManager">Resource manager.</param> 17 void Deactivate();
/// <returns>Whether or not compilation succeeded.</returns> 18 }
bool Compile(IRenderPanel panel); 19 }
}
}
protected ShaderRoutineGL()
namespace OhioState.Graphics {
{ // The constructor should not make any OpenGL calls
public
bli interface
i f IHardwareResource<T>
d }
{
T GUID { get; } public bool Compile(IRenderPanel panel) {
} if (!created) {
Create();
public interface IOpenGLResource : IHardwareResource<uint> }
{ if (needsCompiled) {
} LoadSource();
} // Create the Handle (GUID) for the shader
Gl.glCompileShader(guid);
int compileStatus;
Gl.glGetShaderiv(guid, Gl.GL_COMPILE_STATUS,
out compileStatus);
isCompiled = (compileStatus == Gl.GL_TRUE);
SetCompilerLog();
needsCompiled = false;
}
return isCompiled;
}
namespaceOhioState.Graphics.OpenGL{
private void Create() publicclassShaderProgramGL:IShaderProgram,
{ IOpenGLResource,IDisposable
// Since OpenGL wants to return an unsigned int and unsigned int's {
// are not CLR compliant,
p , we need to cast this. ATI was g
giving
g me public ShaderProgramGL()
// some signed numbers, so we need to prevent a conversion here. {
unchecked // Do not make OpenGL calls here
{ }
// Create the Handle (
(GUID)
) for the shader public void MakeActive(IRenderPanel panel)
guid = (uint)Gl.glCreateShader(shaderType); {
} if (!created)
created = true; {
} Create();
}
private void LoadSource() if (needsLinked)
{ {
int length = currentContent[0].Length;
currentContent[0] Length; if (!Link())
string[] content = new string[1]; return;
int[] lengthArray = { length }; needsLinked = false; public void Deactivate()
// load the source code into the shader object } {
Gl glShaderSource(guid 1
Gl.glShaderSource(guid, 1, currentContent
currentContent, lengthArray); Gl.glUseProgram(guid); //di bl th
//disable the program object
bj t
} } Gl.glUseProgram(0);
}
private void Create() public void AttachShader(IShaderRoutine shader)
{ {
unchecked if (!created)
{ {
guid = (uint)Gl.glCreateProgram(); Create();
} }
created = true; if (!shaderList.Contains(shader))
} {
shaderList.Add(shader);
Gl.glAttachShader(guid, (shader as IOpenGLResource).GUID);
needsLinked = true;
}
}
y Imaginetheobjectsare
y Allowtheusertodefine
rotatedalongwitha
3Drotation usingmouse
imaginaryhemisphere
g y p
clickin2Dwindows
y Worksimilarlylikethe
hardwaretrackball
devices
y Superimposeahemi
sphereontotheviewport y Keeptrackthepreviousmouse
eep t ac t e p ev ous ouse
positionandthecurrentposition
y Thishemisphereis
y Calculatetheirprojectionpositions
projectedtoacircle p1andp2tothevirtualhemisphere
z
i
inscribedtotheviewport
ib dt th i t y Wethenrotatethespherefromp1
Wh h h f z
top2byfindingtheproperrotation
y Themousepositionis axisandangle
p j
projected y Thisrotation(ineyespace!)isthen
orthographicallytothis y
appliedtotheobject(callthe y
hemisphere rotationbeforeyoudefinethe
camerawithgluLookAt())
(
(x,y,0)
) y Youshouldalsorememberto
Y h ld l b
x
accumulatethecurrentrotationto x
thepreviousmodelviewmatrix
y Theaxisofrotationisgivenbythenormaltotheplane
determinedbytheorigin,p1,andp2
y Howtocalculatep1andp2?
y Assumingthemousepositionis(x,y),thenthespherepointP
y Theanglebetweenp1 alsohasxandycoordinatesequaltoxandy
andp
d 2isgivenby
i i nb y Assumetheradiusofthehemisphereis1.Sothezcoordinateof
Assumetheradiusofthehemi sphereis1 Sothezcoordinateof
= p1 p1 Pis
z 1 x y
2 2
y Note:normalizeviewportyextend
li i d
z
to1to1
y y Ifapointisoutsidethecircle,project
p ,p j
ittothenearestpointonthecircle
|n|
| sin | = (setzto0andrenormalize(x,y))
y
| p1 || p 2 | x
(
(x,y,0)
)
x
y ExamplefromEdAngelsOpenGLPrimer
y Inthisexample,thevirtualtrackballisusedtorotatea
Visualizationofthealgorithm colorcube
y Thecodeforthecolorcubefunctionisomitted
y Iwillnotcoverthefollowingcode,butIamsureyou
I ill h f ll i d b I
willfindituseful