WebGLRenderingContext.vertexAttribPointer() - Web API 接口 ...
文章推薦指數: 80 %
vertexAttribPointer() method of the WebGL API binds the buffer currently bound to gl.ARRAY_BUFFER to a generic vertex attribute of the ...
SkiptomaincontentSkiptosearchSkiptoselectlanguageWeb开发技术WebAPI接口参考WebGLRenderingContextWebGLRenderingContext.vertexAttribPointer()ArticleActions中文(简体)此页面由社区从英文翻译而来。
了解更多并加入MDNWebDocs社区。
SyntaxDescriptionExamplesSpecificationsBrowsercompatibilitySeealsoRelatedTopicsWebGLAPIWebGLRenderingContext属性canvasdrawingBufferHeightdrawingBufferWidth方法activeTexture()attachShader()bindAttribLocation()bindBuffer()bindFramebuffer()bindRenderbuffer()bindTexture()blendColor()blendEquation()blendEquationSeparate()blendFunc()blendFuncSeparate()(en-US)bufferData()bufferSubData()(en-US)checkFramebufferStatus()(en-US)clear()clearColor()clearDepth()clearStencil()(en-US)colorMask()(en-US)
Experimental
commit()compileShader()compressedTexImage[23]D()compressedTexSubImage2D()(en-US)copyTexImage2D()(en-US)copyTexSubImage2D()(en-US)createBuffer()createFramebuffer()createProgram()createRenderbuffer()createShader()createTexture()cullFace()deleteBuffer()deleteFramebuffer()deleteProgram()deleteRenderbuffer()deleteShader()deleteTexture()depthFunc()depthMask()depthRange()(en-US)detachShader()disable()disableVertexAttribArray()(en-US)drawArrays()drawElements()enable()enableVertexAttribArray()finish()(en-US)flush()(en-US)framebufferRenderbuffer()(en-US)framebufferTexture2D()(en-US)frontFace()(en-US)generateMipmap()(en-US)getActiveAttrib()(en-US)getActiveUniform()(en-US)getAttachedShaders()(en-US)getAttribLocation()getBufferParameter()(en-US)getContextAttributes()getError()(en-US)getExtension()getFramebufferAttachmentParameter()(en-US)getParameter()getProgramInfoLog()getProgramParameter()getRenderbufferParameter()(en-US)getShaderInfoLog()(en-US)getShaderParameter()getShaderPrecisionFormat()(en-US)getShaderSource()getSupportedExtensions()getTexParameter()getUniform()getUniformLocation()(en-US)getVertexAttrib()(en-US)getVertexAttribOffset()(en-US)hint()(en-US)isBuffer()isContextLost()isEnabled()isFramebuffer()(en-US)isProgram()isRenderbuffer()(en-US)isShader()isTexture()(en-US)lineWidth()(en-US)linkProgram()makeXRCompatible()(en-US)pixelStorei()polygonOffset()readPixels()(en-US)renderbufferStorage()sampleCoverage()(en-US)scissor()shaderSource()stencilFunc()(en-US)stencilFuncSeparate()(en-US)stencilMask()(en-US)stencilMaskSeparate()(en-US)stencilOp()(en-US)stencilOpSeparate()(en-US)texImage2D()texParameter[fi]()texSubImage2D()(en-US)uniform[1234][fi][v]()uniformMatrix[234]fv()useProgram()validateProgram()vertexAttrib[1234]f[v]()vertexAttribPointer()viewport()RelatedpagesforWebGLANGLE_instanced_arraysEXT_blend_minmax(en-US)EXT_color_buffer_half_float(en-US)EXT_disjoint_timer_query(en-US)EXT_frag_depth(en-US)EXT_sRGB(en-US)EXT_shader_texture_lod(en-US)EXT_texture_filter_anisotropic(en-US)OES_element_index_uint(en-US)OES_standard_derivatives(en-US)OES_texture_float(en-US)OES_texture_float_linear(en-US)OES_texture_half_float(en-US)OES_texture_half_float_linear(en-US)OES_vertex_array_objectWEBGL_color_buffer_float(en-US)WEBGL_compressed_texture_etc1(en-US)WEBGL_compressed_texture_pvrtc(en-US)WEBGL_compressed_texture_s3tc(en-US)WEBGL_compressed_texture_s3tc_srgb(en-US)WEBGL_debug_renderer_info(en-US)WEBGL_debug_shaders(en-US)WEBGL_depth_texture(en-US)WEBGL_draw_buffers(en-US)WEBGL_lose_contextWebGL2RenderingContextWebGLActiveInfoWebGLBufferWebGLContextEventWebGLFramebufferWebGLObjectWebGLProgramWebGLQueryWebGLRenderbufferWebGLSamplerWebGLShaderWebGLShaderPrecisionFormatWebGLSyncWebGLTextureWebGLTransformFeedback(en-US)WebGLUniformLocationWebGLVertexArrayObjectSyntaxDescriptionExamplesSpecificationsBrowsercompatibilitySeealsoWebGLRenderingContext.vertexAttribPointer()
TheWebGLRenderingContext.vertexAttribPointer()methodoftheWebGLAPIbindsthebuffercurrentlyboundtogl.ARRAY_BUFFERtoagenericvertexattributeofthecurrentvertexbufferobjectandspecifiesitslayout.
告诉显卡从当前绑定的缓冲区(bindBuffer()指定的缓冲区)中读取顶点数据。
WebGLAPI的WebGLRenderingContext.vertexAttribPointer()方法绑定当前缓冲区范围到gl.ARRAY_BUFFER,成为当前顶点缓冲区对象的通用顶点属性并指定它的布局(缓冲区对象中的偏移量)。
Syntaxvoidgl.vertexAttribPointer(index,size,type,normalized,stride,offset);
Parameters
index
AGLuint(en-US)specifyingtheindexofthevertexattributethatistobemodified.
指定要修改的顶点属性的索引。
size
AGLint(en-US)specifyingthenumberofcomponentspervertexattribute.Mustbe1,2,3,or4.
指定每个顶点属性的组成数量,必须是1,2,3或4。
type
AGLenum(en-US)specifyingthedatatypeofeachcomponentinthearray.Possiblevalues:
指定数组中每个元素的数据类型可能是:
gl.BYTE:signed8-bitinteger,withvaluesin[-128,127]
有符号的8位整数,范围[-128,127]
gl.SHORT:signed16-bitinteger,withvaluesin[-32768,32767]
有符号的16位整数,范围[-32768,32767]
gl.UNSIGNED_BYTE:unsigned8-bitinteger,withvaluesin[0,255]
无符号的8位整数,范围[0,255]
gl.UNSIGNED_SHORT:unsigned16-bitinteger,withvaluesin[0,65535]
无符号的16位整数,范围[0,65535]
gl.FLOAT:32-bitIEEEfloatingpointnumber
32位IEEE标准的浮点数
WhenusingaWebGL2context,thefollowingvaluesareavailableadditionally:
使用WebGL2版本的还可以使用以下值:
gl.HALF_FLOAT:16-bitIEEEfloatingpointnumber
16位IEEE标准的浮点数
normalized
AGLboolean(en-US)specifyingwhetherintegerdatavaluesshouldbenormalizedintoacertainrangewhenbeingcastedtoafloat.
当转换为浮点数时是否应该将整数数值归一化到特定的范围。
Fortypesgl.BYTEandgl.SHORT,normalizesthevaluesto[-1,1]iftrue.
对于类型gl.BYTE和gl.SHORT,如果是true则将值归一化为[-1,1]
Fortypesgl.UNSIGNED_BYTEandgl.UNSIGNED_SHORT,normalizesthevaluesto[0,1]iftrue.
对于类型gl.UNSIGNED_BYTE和gl.UNSIGNED_SHORT,如果是true则将值归一化为[0,1]
Fortypesgl.FLOATandgl.HALF_FLOAT,thisparameterhasnoeffect.
对于类型gl.FLOAT和gl.HALF_FLOAT,此参数无效
stride
AGLsizei(en-US)specifyingtheoffsetinbytesbetweenthebeginningofconsecutivevertexattributes.Cannotbelargerthan255.Ifstrideis0,theattributeisassumedtobetightlypacked,thatis,theattributesarenotinterleavedbuteachattributeisinaseparateblock,andthenextvertex'attributefollowsimmediatelyafterthecurrentvertex.
一个GLsizei,以字节为单位指定连续顶点属性开始之间的偏移量(即数组中一行长度)。
不能大于255。
如果stride为0,则假定该属性是紧密打包的,即不交错属性,每个属性在一个单独的块中,下一个顶点的属性紧跟当前顶点之后。
offset
AGLintptr(en-US)specifyinganoffsetinbytesofthefirstcomponentinthevertexattributearray.Mustbeamultipleofthebytelengthof type.
GLintptr(en-US)指定顶点属性数组中第一部分的字节偏移量。
必须是类型的字节长度的倍数。
ReturnvalueNone.Exceptions
Agl.INVALID_VALUEerroristhrownifoffsetisnegative.
如果偏移量为负,则抛出gl.INVALID_VALUE错误。
Agl.INVALID_OPERATIONerroristhrownifstrideandoffsetarenotmultiplesofthesizeofthedatatype.
如果stride和offset不是数据类型大小的倍数,则抛出gl.INVALID_OPERATION错误。
Agl.INVALID_OPERATIONerroristhrownifnoWebGLBufferisboundtotheARRAY_BUFFERtarget.
如果没有将WebGLBuffer绑定到ARRAY_BUFFER目标,则抛出gl.INVALID_OPERATION错误。
WhenusingaWebGL2context,agl.INVALID_OPERATIONerroristhrownifthisvertexattributeisdefinedasaintegerinthevertexshader(e.g.uvec4orivec4,insteadofvec4).
DescriptionLet'sassumewewanttorendersome3Dgeometry,andforthatwewillneedtosupplyourverticestotheVertexShader.Eachvertexhasafewattributes,likeposition,normalvector,ortexturecoordinate,thataredefinedinanArrayBufferandwillbesuppliedtotheVertexBufferObject(VBO).First,weneedtobindtheWebGLBufferwewanttousetogl.ARRAY_BUFFER,then,withthismethod,gl.vertexAttribPointer(),wespecifyinwhatordertheattributesarestored,andwhatdatatypetheyarein.Inaddition,weneedtoincludethestride,whichisthetotalbytelengthofallattributesforonevertex.Also,wehavetocallgl.enableVertexAttribArray()totellWebGLthatthisattributeshouldbefilledwithdatafromourarraybuffer.
Usually,your3Dgeometryisalreadyinacertainbinaryformat,soyouneedtoreadthespecificationofthatspecificformattofigureoutthememorylayout.However,ifyouaredesigningtheformatyourself,oryourgeometryisintextfiles(likeWavefront.objfiles)andmustbeconvertedintoanArrayBufferatruntime,youhavefreechoiceonhowtostructurethememory.Forhighestperformance,interleavetheattributesandusethesmallestdatatypethatstillaccuratelyrepresentsyourgeometry.
Themaximumnumberofvertexattributesdependsonthegraphicscard,andyoucancallgl.getParameter(gl.MAX_VERTEX_ATTRIBS)togetthisvalue.Onhigh-endgraphicscards,themaximumis16,onlower-endgraphicscards,thevaluewillbelower.AttributeindexForeachattribute,youmustspecifyitsindex.Thisisindependentfromthelocationinsidethearraybuffer,soyourattributescanbesentinadifferentorderthanhowtheyarestoredinthearraybuffer.Youhavetwooptions:
Eitheryouspecifytheindexyourself.Inthiscase,youcallgl.bindAttribLocation()toconnectanamedattributefromthevertexshadertotheindexyouwanttouse.Thismustbedonebeforecallinggl.linkProgram().Youcanthenprovidethissameindextogl.vertexAttribPointer().
Alternatively,youusetheindexthatisassignedbythegraphicscardwhencompilingthevertexshader.Dependingonthegraphicscard,theindexwillvary,soyoumustcallgl.getAttribLocation()tofindouttheindex,andthenprovidethisindextogl.vertexAttribPointer().
IfyouareusingWebGL2,youcanspecifytheindexyourselfinthevertexshadercodeandoverridethedefaultusedbythegraphicscard,e.g.layout(location=3)invec4position;wouldsetthe"position"attributetoindex3.
IntegerattributesWhiletheArrayBuffercanbefilledwithbothintegersandfloats,theattributeswillalwaysbeconvertedtoafloatwhentheyaresenttothevertexshader.Ifyouneedtouseintegersinyourvertexshadercode,youcaneithercastthefloatbacktoanintegerinthevertexshader(e.g.(int)floatNumber),orusegl.vertexAttribIPointer()(en-US)fromWebGL2.DefaultattributevaluesThevertexshadercodemayincludeanumberofattributes,butwedon'tneedtospecifythevaluesforeachattribute.Instead,wecansupplyadefaultvaluethatwillbeidenticalforallvertices.Wecancallgl.disableVertexAttribArray()(en-US)totellWebGLtousethedefaultvalue,whilecallinggl.enableVertexAttribArray()willreadthevaluesfromthearraybufferasspecifiedwithgl.vertexAttribPointer().
Similarily,ifourvertexshaderexpectse.g.a4-componentattributewithvec4butinourgl.vertexAttribPointer()callwesetthesizeto2,thenWebGLwillsetthefirsttwocomponentsbasedonthearraybuffer,whilethethirdandfourthcomponentsaretakenfromthedefaultvalue.
Thedefaultvalueisvec4(0.0,0.0,0.0,1.0)bydefaultbutwecanspecifyadifferentdefaultvaluewithgl.vertexAttrib[1234]f[v]().
Forexample,yourvertexshadermaybeusingapositionandacolorattribute.Mostmesheshavethecolorspecifiedataper-vertexlevel,butsomemeshesareofauniformshade.Forthosemeshes,itisnotnecessarytoplacethesamecolorforeachvertexintothearraybuffer,soyouusegl.vertexAttrib4fv()tosetaconstantcolor.QueryingcurrentsettingsYoucancallgl.getVertexAttrib()(en-US)andgl.getVertexAttribOffset()(en-US)togetthecurrentparametersforanattribute,e.g.thedatatypeorwhethertheattributeshouldbenormalized.KeepinmindthattheseWebGLfunctionshaveaslowperformanceanditisbettertostorethestateinsideyourJavaScriptapplication.However,thesefunctionsaregreatfordebuggingaWebGLcontextwithouttouchingtheapplicationcode.ExamplesThisexampleshowshowtosendyourvertexattributestotheshaderprogram.Weuseanimaginarydatastructurewheretheattributesofeachvertexarestoredinterleavedwithalengthof20bytespervertex:
position:WeneedtostoretheX,YandZcoordinates.Forhighestprecision,weuse32-bitfloats;intotalthisuses12bytes.
normalvector:WeneedtostoretheX,YandZcomponentsofthenormalvector,butsinceprecisionisnotthatimportant,weuse8-bitsignedintegers.Forbetterperformance,wealignthedatato32bitsbyalsostoringafourthzero-valuedcomponent,bringingthetotalsizeto4bytes.Also,wetellWebGLtonormalizethevaluesbecauseournormalsarealwaysinrange[-1,1].
texturecoordinate:WeneedtostoretheUandVcoordinates;forthis16-bitunsignedintegersofferenoughprecision,thetotalsizeis4bytes.WealsotellWebGLtonormalizethevaluesto[0,1].
Forexample,thefollowingvertex:
{
"position":[1.0,2.0,1.5],
"normal":[1.0,0.0,0.0],
"texCoord":[0.5,0.25]
}
Willbestoredinthearraybufferasfollows:
0000803F
00000040
00000C3F
7F
00
00
00
7FFF
3FFF
CreatingthearraybufferFirst,wedynamicallycreatethearraybufferfromJSONdatausingaDataView(en-US).NotetheuseoftruebecauseWebGLexpectsourdatatobeinlittle-endian.
//loadgeometrywithfetch()andResponse.json()
constresponse=awaitfetch('assets/geometry.json');
constvertices=awaitresponse.json();
//Createarraybuffer
constbuffer=newArrayBuffer(20*vertices.length);
//Fillarraybuffer
constdv=newDataView(buffer);
for(leti=0;i
延伸文章資訊
- 1webgl vertexAttribPointer步进和偏移函数 - 简书
如果每个顶点数据都创建一个缓冲对象,那么会导致创建很多缓冲对象,而且在编码的过程中会产生相同的代码.所以webgl 推出使用vertexAttribPointer()的步 ...
- 2webGL: vertexAttribPointer 函式理解 - IT人
MDN官方定義告訴顯示卡從當前繫結的緩衝區(bindBuffer()指定的緩衝區)中讀取頂點資料。語法void gl.vertexAttribPointer(index, size, type,...
- 3[Day5] WebGL 修羅道(2) - 資料傳遞 - iT 邦幫忙
所以利用了 gl.vertexAttribPointer ,還要記得啟動 gl.enableVertexAttribArray 。 現在來看看我們的 draw function。原本的 coun...
- 4What is the purpose of vertexAttribPointer? - Stack Overflow
it tells WebgL how to interpret the data: gl.vertexAttribPointer(attrib, index, gl.FLOAT, false, ...
- 5glVertexAttribPointer - OpenGL 4 Reference Pages