OpenGL Shading Language ( GLSL ) I

文章推薦指數: 80 %
投票人數:10人

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 #include #include #include #include #include #defineGLEW_STATIC1 #include #include #include usingnamespacestd; /* Globalhandlesforthecurrentlyactiveprogramobject,withitstwoshaderobjects */ GLuintprogramObject=0; GLuintvertexShaderObject=0; GLuintfragmentShaderObject=0; staticGLintwin=0; intreadShaderSource(char*fileName,GLchar**shader) { //Allocatememorytoholdthesourceofourshaders. FILE*fp; intcount,pos,shaderSize; fp=fopen(fileName,"r"); if(!fp) return0; pos=(int)ftell(fp); fseek(fp,0,SEEK_END); //movetoend shaderSize=(int)ftell(fp)-pos; //calculatesfilesize fseek(fp,0,SEEK_SET); //rewindtobeginning if(shaderSize<=0){ printf("Shader%sempty\n",fileName); return0; } *shader=(GLchar*)malloc(shaderSize+1); //Readthesourcecode count=(int)fread(*shader,1,shaderSize,fp); (*shader)[count]='\0'; if(ferror(fp)) count=0; fclose(fp); return1; } //public intinstallShaders(constGLchar*vertex,constGLchar*fragment) { GLintvertCompiled,fragCompiled;//statusvalues GLintlinked; //Createavertexshaderobjectandafragmentshaderobject vertexShaderObject=glCreateShader(GL_VERTEX_SHADER); fragmentShaderObject=glCreateShader(GL_FRAGMENT_SHADER); //Loadsourcecodestringsintoshaders,compileandlink glShaderSource(vertexShaderObject,1,&vertex,NULL); glShaderSource(fragmentShaderObject,1,&fragment,NULL); glCompileShader(vertexShaderObject); glGetShaderiv(vertexShaderObject,GL_COMPILE_STATUS,&vertCompiled); glCompileShader(fragmentShaderObject); glGetShaderiv(fragmentShaderObject,GL_COMPILE_STATUS,&fragCompiled); if(!vertCompiled||!fragCompiled) return0; //Createaprogramobjectandattachthetwocompiledshaders programObject=glCreateProgram(); glAttachShader(programObject,vertexShaderObject); glAttachShader(programObject,fragmentShaderObject); //Linktheprogramobject glLinkProgram(programObject); glGetProgramiv(programObject,GL_LINK_STATUS,&linked); if(!linked) return0; //Installprogramobjectaspartofcurrentstate glUseProgram(programObject); return1; } intinit(void) { constchar*version; GLchar*VertexShaderSource,*FragmentShaderSource; intloadstatus=0; version=(constchar*)glGetString(GL_VERSION); if(version[0]!='2'||version[1]!='.'){ printf("ThisprogramrequiresOpenGL2.x,found%s\n",version); exit(1); } readShaderSource("tests.vert",&VertexShaderSource); readShaderSource("tests.frag",&FragmentShaderSource); loadstatus=installShaders(VertexShaderSource,FragmentShaderSource); returnloadstatus; } staticvoidReshape(intwidth,intheight) { glViewport(0,0,width,height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-1.0,1.0,-1.0,1.0,5.0,25.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.0f,0.0f,-15.0f); } voidCleanUp(void) { glDeleteShader(vertexShaderObject); glDeleteShader(fragmentShaderObject); glDeleteProgram(programObject); glutDestroyWindow(win); } staticvoidIdle(void) { glutPostRedisplay(); } staticvoidKey(unsignedcharkey,intx,inty) { switch(key){ case27: CleanUp(); exit(0); break; } glutPostRedisplay(); } voiddisplay(void) { GLfloatvec[4]; glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glClearColor(1.0,1.0,1.0,0.0); //getwhitebackgroundcolor glColor3f(1,0,0); //red,thiswillhavenoeffectifshaderisloaded glutWireSphere(2.0,10,5); glutSwapBuffers(); glFlush(); } intmain(intargc,char*argv[]) { intsuccess=0; glutInit(&argc,argv); glutInitWindowPosition(0,0); glutInitWindowSize(200,200); glutInitDisplayMode(GLUT_RGB|GLUT_DOUBLE|GLUT_DEPTH); win=glutCreateWindow(argv[0]); glutReshapeFunc(Reshape); glutKeyboardFunc(Key); glutDisplayFunc(display); glutIdleFunc(Idle); //Initializethe"OpenGLExtensionWrangler"library glewInit(); success=init(); if(success) glutMainLoop(); return0; } //tests.vert //aminimalvertexshader voidmain(void) { gl_Position=ftransform(); /* Sameas: gl_Position=gl_ProjectionMatrix*gl_ModelViewMatrix*gl_Vertex; or gl_Position=gl_ModelViewProjectionMatrix*gl_Vertex; */ } //tests.frag //aminimalfragmentshader voidmain(void) { gl_FragColor=vec4(1,1,0,1); //yellowcolor } GLSL1.5Specification



請為這篇文章評分?