WebGL - Shaders - Tutorialspoint
文章推薦指數: 80 %
Example − uniform vec4 lightPosition; ... Take a look at the following sample code of a vertex shader. It processes the vertices ... bool gl_FrontFacing;. Home CodingGround Jobs Whiteboard Tools Business Teachwithus WebGLTutorial WebGL-Home WebGL-Introduction WebGL-Html5CanvasOverview WebGL-Basics WebGL-GraphicsPipeline WebGLApplication WebGL-SampleApplication WebGL-Context WebGL-Geometry WebGL-Shaders AssociatingAttributes&BufferObjects WebGL-DrawingaModel WebGLExamples WebGL-DrawingPoints WebGL-DrawingaTriangle WebGL-ModesofDrawing WebGL-DrawingaQuad WebGL-Colors WebGL-Translation WebGL-Scaling WebGL-Rotation WebGL-CubeRotation WebGL-InteractiveCube WebGLUsefulResources WebGL-QuickGuide WebGL-UsefulResources WebGL-Discussion SelectedReading UPSCIASExamsNotes Developer'sBestPractices QuestionsandAnswers EffectiveResumeWriting HRInterviewQuestions ComputerGlossary WhoisWho WebGL-Shaders Advertisements PreviousPage NextPage ShadersaretheprogramsthatrunonGPU.ShadersarewritteninOpenGLESShaderLanguage(knownasESSL).ESSLhasvariablesofitsown,datatypes,qualifiers,built-ininputsandoutputs. DataTypes ThefollowingtableliststhebasicdatatypesprovidedbyOpenGLESSL. Sr.No. Type&Description 1 void Representsanemptyvalue. 2 bool Acceptstrueorfalse. 3 int Thisisasignedintegerdatatype. 4 float Thisisafloatingscalardatatype. 5 vec2,vec3,vec4 n-componentfloatingpointvector 6 bvec2,bvec3,bvec4 Booleanvector 7 ivec2,ivec3,ivec4 signedintegervector 8 mat2,mat3,mat4 2x2,3x3,4x4floatmatrix 9 sampler2D Accessa2Dtexture 10 samplerCube Accesscubemappedtexture Qualifiers TherearethreemainqualifiersinOpenGLESSL− Sr.No. Qualifier&Description 1 attribute ThisqualifieractsasalinkbetweenavertexshaderandOpenGLESforper-vertexdata.Thevalueofthisattributechangesforeveryexecutionofthevertexshader. 2 uniform ThisqualifierlinksshaderprogramsandtheWebGLapplication.Unlikeattributequalifier,thevaluesofuniformsdonotchange.Uniformsareread-only;youcanusethemwithanybasicdatatypes,todeclareavariable. Example−uniformvec4lightPosition; 3 varying Thisqualifierformsalinkbetweenavertexshaderandfragmentshaderforinterpolateddata.Itcanbeusedwiththefollowingdatatypes−float,vec2,vec3,vec4,mat2,mat3,mat4,orarrays. Example−varyingvec3normal; VertexShader Vertexshaderisaprogramcode,whichiscalledoneveryvertex.Ittransforms(move)thegeometry(ex:triangle)fromoneplacetoother.Ithandlesthedataofeachvertex(per-vertexdata)suchasvertexcoordinates,normals,colors,andtexturecoordinates. IntheESGLcodeofvertexshader,programmershavetodefineattributestohandledata.TheseattributespointtoaVertexBufferObjectwrittenInJavaScript.Thefollowingtaskscanbeperformedusingvertexshadersalongwithvertextransformation− Vertextransformation Normaltransformationandnormalization Texturecoordinategeneration Texturecoordinatetransformation Lighting Colormaterialapplication PredefinedVariables OpenGLESSLprovidesthefollowingpredefinedvariablesforvertexshader− Sr.No. Variables&Description 1 highpvec4gl_Position; Holdsthepositionofthevertex. 2 mediumpfloatgl_PointSize; Holdsthetransformedpointsize.Theunitsforthisvariablearepixels. SampleCode Takealookatthefollowingsamplecodeofavertexshader.Itprocessestheverticesofatriangle. attributevec2coordinates; voidmain(void){ gl_Position=vec4(coordinates,0.0,1.0); }; Ifyouobservetheabovecodecarefully,wehavedeclaredanattributevariablewiththenamecoordinates.(ThisvariablewillbeassociatedwiththeVertexBufferObjectusingthemethodgetAttribLocation().Theattributecoordinatesispassedasaparametertothismethodalongwiththeshaderprogramobject.) Inthesecondstepofthegivenvertexshaderprogram,thegl_positionvariableisdefined. gl_Position gl_Positionisthepredefinedvariablewhichisavailableonlyinthevertexshaderprogram.Itcontainsthevertexposition.Intheabovecode,thecoordinatesattributeispassedintheformofavector.Asvertexshaderisaper-vertexoperation,thegl_positionvalueiscalculatedforeachvertex. Later,thegl_positionvalueisusedbyprimitiveassembly,clipping,culling,andotherfixedfunctionalityoperationsthatoperateontheprimitivesafterthevertexprocessingisover. Wecanwritevertexshaderprogramsforallpossibleoperationsofvertexshader,whichwewilldiscussindividuallyinthistutorial. FragmentShader Ameshisformedbymultipletriangles,andthesurfaceoftheeachtriangleisknownasafragment.Afragmentshaderisthecodethatrunsoneverypixeloneachfragment.Thisiswrittentocalculateandfillthecoloronindividualpixels.Thefollowingtaskscanbeperformedusingfragmentshaders− Operationsoninterpolatedvalues Textureaccess Textureapplication Fog Colorsum PredefinedVariables OpenGLESSLprovidesthefollowingpredefinedvariablesforfragmentshader− Sr.No. Variables&Description 1 mediumpvec4gl_FragCoord; Holdsthefragmentpositionwithintheframebuffer. 2 boolgl_FrontFacing; Holdsthefragmentthatbelongstoafront-facingprimitive. 3 mediumpvec2gl_PointCoord; Holdsthefragmentpositionwithinapoint(pointrasterizationonly). 4 mediumpvec4gl_FragColor; Holdstheoutputfragmentcolorvalueoftheshader 5 mediumpvec4gl_FragData[n] Holdsthefragmentcolorforcolorattachmentn. SampleCode Thefollowingsamplecodeofafragmentshadershowshowtoapplycolortoeverypixelinatriangle. voidmain(void){ gl_FragColor=vec4(0,0.8,0,1); } Intheabovecode,thecolorvalueisstoredinthevariablegl.FragColor.Thefragmentshaderprogrampassestheoutputtothepipelineusingfixedfunctionvariables;FragColorisoneofthem.Thisvariableholdsthecolorvalueofthepixelsofthemodel. StoringandCompilingtheShaderPrograms Sinceshadersareindependentprograms,wecanwritethemasaseparatescriptanduseintheapplication.Or,youcanstorethemdirectlyinstringformat,asshownbelow. varvertCode= 'attributevec2coordinates;'+ 'voidmain(void){'+ 'gl_Position=vec4(coordinates,0.0,1.0);'+ '}'; CompilingtheShader Compilationinvolvesfollowingthreesteps− Creatingtheshaderobject Attachingthesourcecodetothecreatedshaderobject Compilingtheprogram CreatingtheVertexShader Tocreateanemptyshader,WebGLprovidesamethodcalledcreateShader().Itcreatesandreturnstheshaderobject.Itssyntaxisasfollows− ObjectcreateShader(enumtype) Asobservedinthesyntax,thismethodacceptsapredefinedenumvalueasparameter.Wehavetwooptionsforthis− gl.VERTEX_SHADERforcreatingvertexshader gl.FRAGMENT_SHADERforcreatingfragmentshader. AttachingtheSourcetotheShader YoucanattachthesourcecodetothecreatedshaderobjectusingthemethodshaderSource().Itssyntaxisasfollows− voidshaderSource(Objectshader,stringsource) Thismethodacceptstwoparameters− shader−Youhavetopassthecreatedshaderobjectasoneparameter. Source−Youhavetopasstheshaderprogramcodeinstringformat. CompilingtheProgram Tocompiletheprogram,youhavetousethemethodcompileShader().Itssyntaxisasfollow− compileShader(Objectshader) Thismethodacceptstheshaderprogramobjectasaparameter.Aftercreatingashaderprogramobject,attachthesourcecodetoitandpassthatobjecttothismethod. Thefollowingcodesnippetshowshowtocreateandcompileavertexshaderaswellasafragmentshadertocreateatriangle. //VertexShader varvertCode= 'attributevec3coordinates;'+ 'voidmain(void){'+ 'gl_Position=vec4(coordinates,1.0);'+ '}'; varvertShader=gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertShader,vertCode); gl.compileShader(vertShader); //FragmentShader varfragCode= 'voidmain(void){'+ 'gl_FragColor=vec4(0,0.8,0,1);'+ '}'; varfragShader=gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragShader,fragCode); gl.compileShader(fragShader); CombinedProgram Aftercreatingandcompilingboththeshaderprograms,youneedtocreateacombinedprogramcontainingboththeshaders(vertex&fragment).Thefollowingstepsneedtobefollowed− Createaprogramobject Attachboththeshaders Linkboththeshaders Usetheprogram CreateaProgramObject CreateaprogramobjectbyusingthemethodcreateProgram().Itwillreturnanemptyprogramobject.Hereisitssyntax− createProgram(); AttachtheShaders AttachtheshaderstothecreatedprogramobjectusingthemethodattachShader().Itssyntaxisasfollows− attachShader(Objectprogram,Objectshader); Thismethodacceptstwoparameters− Program−Passthecreatedemptyprogramobjectasoneparameter. Shader−Passoneofthecompiledshadersprograms(vertexshader,fragmentshader) Note−Youneedtoattachboththeshadersusingthismethod. LinktheShaders LinktheshadersusingthemethodlinkProgram(),bypassingtheprogramobjecttowhichyouhaveattachedtheshaders.Itssyntaxisasfollows− linkProgram(shaderProgram); UsetheProgram WebGLprovidesamethodcalleduseProgram().Youneedtopassthelinkedprogramtoit.Itssyntaxisasfollows− useProgram(shaderProgram); Thefollowingcodesnippetshowshowtocreate,link,anduseacombinedshaderprogram. varshaderProgram=gl.createProgram(); gl.attachShader(shaderProgram,vertShader); gl.attachShader(shaderProgram,fragShader); gl.linkProgram(shaderProgram); gl.useProgram(shaderProgram); PreviousPage PrintPage NextPage Advertisements
延伸文章資訊
- 1Intro to GLSL - Cornell CS
- 2gl_PointSize - OpenGL ES 3.1 Reference Pages - Khronos Group
- 3高级GLSL
片段着色器另一个有意思的输入变量是 gl_FrontFacing 变量。在面剔除教程中,我们提到过OpenGL可以根据顶点绘制顺序弄清楚一个面是正面还是背面。
- 4GLSL-to-HLSL 參考- UWP applications | Microsoft Docs
Sample [datatype.Function]. sampler2D [datatype], Texture2D [datatype] ... gl_FrontFacing. 此變數為bo...
- 5WebGL/gl-frontfacing.html at main - GitHub
WebGL/sdk/tests/conformance/glsl/variables/gl-frontfacing.html ... <canvas id="example" width="32...