WebGL - Shaders - Tutorialspoint
文章推薦指數: 80 %
Shaders are the programs that run on GPU. Shaders are written in OpenGL ES Shader Language (known as ES SL). ES SL has variables of its own, data types, ... 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 Three.js&WebGL3DProgrammingCrashCourse(VR,OpenGL) 10Lectures 1hours FrahaanHussain MoreDetail WebGL2D/3DProgrammingandGraphicsRenderingForTheWeb 28Lectures 4hours FrahaanHussain MoreDetail 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
延伸文章資訊
- 1WebGL - Shaders - Tutorialspoint
Shaders are the programs that run on GPU. Shaders are written in OpenGL ES Shader Language (known...
- 2webgl Tutorial => Getting started with webgl
At a base level WebGL is an engine that runs 2 user supplied functions on the GPU. One function i...
- 3学习WebGL之深入了解Shader - 简书
无论是Vertex Shader还是Fragment Shader,都有基本的代码框架。下面是本文使用的Vertex Shader。 attribute vec4 position; varyi...
- 4使用shaders 在WebGL 上色- Web APIs | MDN
之前的例子,vertex shader 並沒有指定頂點任何顏色。 In WebGL, objects are built using sets of vertices, each of whic...
- 5認識著色器
在〈準備WebGL Canvas〉中談到,WebGL 的組成中需要著色器程式,初學WebGL 時,著色器程式中基本上會有頂點著色器(Vertex shader)及片段著色器(Fragment s...