OpenGL Shading Language ( GLSL ) I
文章推薦指數: 80 %
Return: A non-zero value for future reference. void glShaderSource ( GLuint shader, GLsizei count, const GLchar **string, const GLint *length ).
Syllabus
Blank
Homework
Quizzes
Notes
Labs
Scores
Blank
LectureNotesDr.TongLaiYu,20101.Introduction2.OpenGLShadingLanguage(GLSL)I3.GLSLII4.CurveandSurfaceDesign
5.ModelingShapeswithPolygonalMeshes6.TextureMapping7.CastingShadows8.ToolsforRasterDisplay9.ParsingExternalObjects
OpenGLShadingLanguage(GLSL)
Someofthematerialsinthesetwochaptersareadoptedfrom
"InteractiveComputerGraphics",byEdwardAngel
Also,pleasereadthearticle"varray-glsl.pdf",whichisdownloaded
fromtheInternet,inthedirectory:
/pool/u/class/cs520/shaders-doc
ExtendingOpenGL
GLSLincludedinOpenGL2.0,releasedin2004.
Othershadinglanguages:Cg(CforGraphics)--crossplatform,
HLSL(HighLevelShadingLanguage)--byMicrosoft,usedinDirectX
GLSLispartofOpenGL,soitsnaturallyeasilyintegratedinOpenGLprograms.
GLSLisaC-likelanguagewithsomeC++features,
mainlyforprocessingnumerics,notforstringsorcharacters.
ProgrammablePipelines
OpenGL1.5fixedfunctionpipeline:
OpenGL2.0allowsprogrammableprocessors:
Programmableprocessors:dataflowfromtheapplicationtothevertexprocessor,onto
thefragmentprocessorandultimatelytotheframebuffer.
Allowsvendorstoproducefastergraphicshardwarewithmoreparallelfeatures.
ShadeTrees
Lightingmodelsandshaderscanberepresentedbytrees.
Phongshadingmodel:
I=kdLdl.n+ksLs(r.v)α
+kaLaIa
r=2(n.l)n-l
Wecanformcollectionoftrees,eachofwhichdefinesadifferentmethodforshadingasurface.
Weusestandardtreetraversalalgorithmsfortheevaluationofexpressionsthat
defineshaders.
ExpressionTreeforPhongShading.
ExpressionTreeforReflectionVector.
OpenGLShadersExecutionModel
Driver--apieceofsoftwaremanagingtheaccesstoahardware.
OpenGLlibrariescanbeconsideredasdriversastheymanagesharedaccess
totheunderlyinggraphicshardware.
ThefollowingfigureillustrateshowOpenGLshadersarehandledinthe
executionenvironmentofOpenGL:
ApplicationscommunicatewithOpenGLbycallingfunctionsthatarepartoftheOpenGLAPI.
glCreateShaderallowsapplicationstoallocatewithintheOpenGLdriver
thedatastructuresneededtostoreanOpenGLshader.
ApplicationprovidesshadersourcecodebycallingglShaderSource.
OverviewofGLSL
Versions
Manyversions,notnecessaryusingthelatest,whichmaynotbe
supportedbyhardware
OpenGLversionGLSLversion
2.0110
2.1120
3.0130
....
3.3330
....
4.5450
DataTypes
floatint
vec2ivec2
vec3ivec3
vec4ivec4
mat2,mat3,mat4
sampler2D, bool
C-likeFunctions:
floatmyFunction(floatx,floaty)
{
floata=x*x;
floatb=y*y;
returna+b;
}
Recursionnotallowed
Nopointers:
voidmyFunction(floatx,floaty,floatresult)
{
floata=x*x;
floatb=y*y;
result=a+b;
}
C++-likeconstructors:
voidmyFunction(floatx)
{
vec3color3=vec3(0.5,0.2,0.8);
vec3color3a=vec3(0.5);//3valuesare0.5
vec4color4=vec4(color3,1.0);//alphais1.0
//Arrays
vec2[3]arr=vec2[3](vec2(1.0,2.0),vec2(3.0,4.0),
vec2(5.0,6.0));
}
Swizzling:
voidmyFunction(vec3postion)
{
floatx=position.x;
floaty=position[1];
}
Array-styleaceesing:[0][1][2][3]
Coordinatedimension:.x.y.z.w
Colorchannel:.r.g.b.a
Texturedimension:.s.t.p.q
vec2p1=postion.xy;
vec2p2=position.yz;
vec4colorAlpha;
vec3color=colorAlpha.rgb;
vec3colorbgr=colorAlpha.bgr;
vec4colorgray=colorAlpha.bbba;
Operations
C-likeoperators
vector*matrix
matrix*vector
matrix*matrix
Note:
vec2(x1,y1)*vec2(x2,y2)==vec2(x1*x2,y1*y2)
functiondot()givesdotproduct
functioncross()givescrossproduct
Built-infunctions
Alotofbuilt-infunctions
abs,mod,exp,log,sin,cos,tan,acos,asin,atan
pow,min,max,floor,ceil,fract,sqrt
Canbeappliedtovectors
sin(vec2(x,y))
Graphicsspecificfunctions
clamp(x,min,max)
step(threshold,x)
smoothstep(start,end,x)
mix(a,b,ratio)
length(vec2(x,y))
distance(vec2(A),vec2(B))==length(B-A)
dFdx(value)//segmentshaderonly
dFdy(value)
texture(sampler2DanImage,vec2texCoord)
VertexShaders
Avertexprocessorisaprogrammableunitthatoperatesonincomingvertexvalues,usually
performingtraditionalgraphicsoperations
suchasthefollowing:
Vertextransformation
Normaltransformationandnormalization
Texturecoordinategeneration
Texturecoordinatetransformation
Lighting
Colormaterialapplication
Avertexshader(program)isashaderrunningonthisprocessor;itreplacesthefixed-functionoperations
withoperationsdefinedby
theshader.
Thefollowingfigureshowsvertexprocessorinputsandoutputs:
AnExample:
//Asimplepass-throughvertexshader
voidmain()
{
gl_Position=gl_ProjectionMatrix*gl_ModelViewMatrix*gl_Vertex;
}
//Asimplevertexshader
constvec4green=vec4(0.0,1.0,0.0,1.0);
voidmain()
{
gl_Position=gl_ModelViewMatrix*gl_Vertex;
gl_FrontColor=green;
}
ExecutionModel
FragmentShaders
FragmentProcessorisaprogrammableunitoperatingonfragmentvalues,usually
performingtraditionalgraphicsoperationssuchas:
Operationsoninterpolatedvalues
Textureaccess
Textureapplication
Fog
Colorsum
Fragmentshaders(programs)areexecutedaftertherasterizer
andthusoperateoneachfragmentratherthanoneachvertex.
Canperformtraditionaloperationsonrectangularimages:
Pixelzoom
Scaleandbias
Colortablelookup
Convolution
Colormatrix
Thefollowingfigureshowsfragmentprocessorinputsandoutputs:
Anexample:
//Asimplefragmentshader
voidmain()
{
gl_FragColor=gl_FrontColor;
}
ExecutionModel
SmoothShading
EnvironmentMapping
BumpMapping
OpenGLShadingLanguageAPI
Overview
NeedOpenGL2.0orlater.
ApprovedbyOpenGLArchitecturalReviewBoard(ARB)
Necessarystepstogetashaderprogramreadyandgoing:
Shader
glCreateShader
↓
glShaderSource
↓
glCompileShader
Program
glCreateProgram
↓
glAttachShader
↓
glAttachShader
↓
glLinkProgram
↓
glUseProgram
ProgramObjectisaContainerforshaders
Cancontainmultipleshaders
OtherGLSLfunctions
GLuintprogObj;
progObj=glCreateProgram();
/*
defineshaderobjectshere
*/
glUseProgrm(progObj);
glLinkProgram(progObj);
glCreateShader()Createsoneormoreshaderobjects.
glShaderSource()Providessourcecodesfortheseshaders.
glCompileShader()Compileseachoftheshaders.
glCreateProgram()Createsaprogramobject.
glAttachShader()Attachallshaderobjectstotheprogram.
glLinkProgram()Linktheprogramobject.
glUseProgram()Installtheexecutableprogramaspart
ofOpenGL'scurrentstate.
CreatingShaderObjects
Shadersareaddedtotheprogramobjectandcompiled.
Usualmethodofpassingashaderisasanull-terminatedstringusingthefunction
glShaderSource().
Theshadercanbesavedinafileandreadintoastring:
{
structstatstatBuf;
FILE*fp=fopen(shaderFile,"r");
char*buf;
stat(shaderFile,&statBuf);
buf=(char*)malloc(statBuf.st_size+1*sizeof(char));
fread(buf,1,statBuf.st_size,fp);
buf[statBuf.st_size]='\0';
fclose(fp);
returnbuf;
}
GluintglCreateShader(GLenumshaderType)
Createsanemptyshader.
shaderType:Specifiesthetypeofshadertobecreated;
eitherGL_VERTEX_SHADERorGL_FRAGMENT_SHADER.
Return:Anon-zerovalueforfuturereference.
voidglShaderSource(GLuintshader,GLsizeicount,
constGLchar**string,constGLint*length)
Definesashader'ssourcecode.
shader:TheshaderobjectcreatedbyglCreateShader().
string:Thearrayofstringsspecifyingthesourcecodeoftheshader.
count:Thenumberofstringsinthearray.
length:Pointstoanarrayspecifingthelengthsofthestrings.If
NULL,thestringsareNULL-terminated.
CompilingShaderObjects
voidglCompileShader(GLuintshader)
Compilesthesourcecodestringsstoredintheshaderobjectshader.
glShaderInfoLog()givethecompilationlog.
LinkingandUsingShaders
Eachshaderobjectiscompiledindependently.Tocreateaprogram,
weneedtolinkalltheshaderobjects.
GLuintglCreateProgram(void)
Createsanemptyprogramobjectandreturnsanon-zerovalueforfuture
reference.
voidglAttachShader(GLuintprogram,GLuintshader)
Attachestheshaderobjectspecifiedbyshadertotheprogram
objectspecifiedbyprogram.
voidglLinkProgram(GLuintprogram)
Linkstheprogramobjectsspecifiedbyprogram.
voidglUseProgram(GLuintprogram)
Installstheprogramobjectspecifiedbyprogramaspartofcurrent
renderingstate.
Ifprogramis0,theprogrammableprocessorsaredisabled,and
fixedfunctionalityisusedforbothvertexandfragmentprocessing.
CleaningUp
voidglDeleteShader(GLuintshader),
voidglDeleteProgram(GLuintprogram),
voidglDetachShader(GLuintprogram,GLuintshader).
Herearethetypicalstepsindevelopingashaderprogram:
Startbydeclaringaprogramobjectandgettinganidentifierforit:
GLunitprogObj;
progObj=glCreateProgram();
Theprogramobjectisacontainerthatcanholdmultipleshadersandother
GLSLfunctions.
Creatingshaderobjects:
GLcharvertexProg[]="shader-source-code";
GLuintvertexObj;
vertexObj=glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexObj,1,vertexProg,NULL);
glCompileShader(vertexObj);
glAttachObject(progObj,vertexObj);
Linkeverything:
glLinkProgram(progObj);
DataTypesInGLSL
Fourmaintypes:float,int,boolandsampler.Forthefirstthreetypes,vector
typesareavailable:
vec2,vec3,vec4 2D,3Dand4Dfloatingpointvector
ivec2,ivec3,ivec4 2D,3Dand4Dintegervector
bvec2,bvec3,bvec4 2D,3Dand4Dbooleanvectors
Forfloatstherearealsomatrixtypes:
mat2,mat3,mat4 2x2,3x3,4x4floatingpointmatrix
Samplersaretypesrepresentingtextures:
sampler1D,sampler2D,sampler3D 1D,2Dand3Dtexture
samplerCube CubeMaptexture
sampler1Dshadow,sampler2Dshadow 1Dand2Ddepth-componenttexture
Attributes,UniformsAndVaryings
Therearethreetypesofinputsandoutputsinashader:uniforms,attributesandvaryings.
Uniforms
valuesdonotchangeduringarendering,
i.e.variableswhosevaluesareassignedoutsidethescope
ofglBegin()andglEnd().
read-only
Uniformvariablesprovideamechanismforsharingdata
amonganapplicationprogram,vertexshaders,andfragmentshaders.
Attributes
Onlyavailableinvertexshader.Theyareusedforvariablesthatchangeatmostoncepervertexinthevertexshader.
Attributesareread-only.
Twotypes:
User-defined:e.g.
attributefloatx;
attributevec3velocity;
Built-invariables:includesOpenGLstatevariableslikecolor,position,normal,
e.g.
gl_Vertex
gl_Color
Varyings
Usedforpassingdatafromavertexshadertoafragmentshader.
Definedonaper-vertexbasisbutareinterpolatedovertheprimitive
bytherasterizer.Canbeuser-definedorbuilt-in.
Mustbedeclaredasglobal.
Built-InTypes
GLSLhassomebuilt-inattributesinavertexshader:
gl_Vertex
4Dvectorrepresentingthevertexposition
gl_Normal
3Dvectorrepresentingthevertexnormal
gl_Color
4Dvectorrepresentingthevertexcolor
gl_MultiTexCoordX
4DvectorrepresentingthetexturecoordinateoftextureunitX
Therearesomeotherbuilt-inattributes.
GLSLalsohassomebuilt-inuniforms:
gl_ModelViewMatrix 4x4Matrixrepresentingthemodel-viewmatrix.
gl_ModelViewProjectionMatrix 4x4Matrixrepresentingthemodel-view-projectionmatrix.
gl_NormalMatrix 3x3Matrixrepresentingtheinversetransposemodel-viewmatrix.
Thismatrixisusedfornormaltransformation.
Therearesomeotherbuilt-inuniforms,likelightingstates.Seereference[2],page42fora
fulllist.
GLSLBuilt-InVaryings:
gl_FrontColor 4Dvectorrepresentingtheprimitivesfrontcolor
gl_BackColor 4Dvectorrepresentingtheprimitivesbackcolor
gl_TexCoord[X] 4DvectorrepresentingtheXthtexturecoordinate
Therearesomeotherbuilt-invaryings.Seereference[2],page44forafulllist.
Andlastbutnotleasttherearesomebuilt-intypeswhichareusedforshaderoutput:
gl_Position 4Dvectorrepresentingthefinalprocessedvertexposition.Only
availableinvertexshader.
gl_FragColor 4Dvectorrepresentingthefinalcolorwhichiswrittenintheframe
buffer.Onlyavailableinfragmentshader.
gl_FragDepth floatrepresentingthedepthwhichiswritteninthedepthbuffer.
Onlyavailableinfragmentshader.
Theimportanceofbuilt-intypesisthattheyaremappedtotheOpenGLstates.Forexampleif
youcallglLightfv(GL_LIGHT0,GL_POSITION,my_light_position)thisvalueisavailableasa
uniformusinggl_LightSource[0].positioninavertexand/orfragmentshader.
GenericTypes
Youarealsoabletospecifyyourownattributes,uniformsandvaryings.Forexampleif
youwanttopassa3Dtangentvectorforeachvertexfromyourapplicationtothevertex
shaderyoucanspecifya"Tangent"attribute:
attributevec3Tangent;
OperatorsandFunctions
Bitoperationsarenotallowed.
Someusualoperatorsareoverloaded.e.g.
mat4a;
vec4b,c,d;
c=b*a; //treatbasarowmatrix
d=a*b; //treatbasacolumnmatrix
HasaswizzlingoperatorthatisavariantoftheCselectionoperation(.).
vec4a=vec4(1.0,2.0,3.01.0);
a.x=2.5;
a.yz=vec2(-1.0,3.0);
Wemayusetheoperatortoswapelements.e.g.
a.xy=a.yz;
GLSLhasmanybuilt-infunctionsincluding:
trigonometricfunctions:sin,cos,tan
inversetrigonometricfunctions:asin,acos,atan
mathematicalfunctions:pow,log2,sqrt,abs,max,min
geometricalfunctions:length,distance,normalize,reflect
GLSLusesamechanismcalledcallbyvalue-returntopass
parameters.Functionparametersareclassifiedasin(default),
out,orinout.Returnedvariablesarecopiedback
tothecallingfunction.Inputparametersarecopiedfromthecalling
program.
ACompleteExample:Aminimalshaderprogram
/*
tests.cpp
SampleprogramshowinghowtowriteGLshaderprograms.
Shadersourcesareinfiles"tests.vert"and"tests.frag".
@Author:T.L.Yu,2008
*/
#include
延伸文章資訊
- 1An Overview of the OpenGL Shading Language - InformIT
However, unlike ANSI C, main() does not return an integer value; ... GLSL switch statements also ...
- 2Advanced GLSL - LearnOpenGL
The gl_Position and gl_PointSize are output variables since their value is read as output from th...
- 3swap.glsl - gists · GitHub
Instantly share code, notes, and snippets. @gre · gre/swap.glsl. Forked from gre ...
- 4atomicCompSwap - OpenGL 4 Reference Pages
- 5OpenGL Shading Language ( GLSL ) I
Return: A non-zero value for future reference. void glShaderSource ( GLuint shader, GLsizei count...