5.3 - A Primer on Buffer Objects — LearnWebGL
文章推薦指數: 80 %
Buffer objects provide the data for attribute variables in vertex shader programs. Remember that WebGL is a restricted subset of OpenGL, and WebGL only ...
LearnWebGL
TableofContents
BookIndex
5.3-APrimeronBufferObjects¶
AbufferobjectisacontiguousblockofmemoryintheGPUthatcanbe
accessedveryquicklybyshaderprogramsexecutingontheGPU.Bufferobjects
storethedatathatshaderprogramsneedforrendering.Thecontentsofabuffer
objectisalwaysan1-dimensionalarray.Forourpurposeswewillconsiderabufferobject
toalwaysbehomogeneous-thatis,everyvaluewillhavethesamedatatype.
(YoucanmixdatatypeswithsometrickyJavaScriptcode,butlet’skeepthingssimple.)
Bufferobjectsprovidethedataforattributevariablesinvertex
shaderprograms.RememberthatWebGLisarestrictedsubsetofOpenGL,
andWebGLonlyallowsattributevariablestobeoftypefloat,
vec2,vec3,vec4,mat2,mat3,and
mat4.Theseareallfloatingpointvalues.Therefore,all
bufferobjectsthatyoucreatewillbearraysoffloatingpointvalues.
JavaScriptisnotastronglytypedlanguageanditdoesnotdistinguish
betweendifferenttypesofnumbers.Mostprogramminglanguageshaveshorts,ints,
floats,anddoubles.JavaScript’shasonlyonedatatypefornumericvalues:
number.JavaScriptwasmodifiedtodealwithbinarydatavaluesbyadding
“typedarray”objects.ForWebGL,allofyourbufferobjectswillcontain
Float32Arrayarrays.
//Floatingpointarrays.
varf32=newFloat32Array(size);//Fractionalvalueswith7digitsofaccuracy
Therearetwowaystoputdataintoa“typedarray”:
IncludeanormalJavaScriptarrayofnumbersasaparametertotheconstructor.
Createthearrayofacertainsizeandthensetindividualelementstospecificvalues.
Thesetwooptionsaredemonstratedinthefollowingcode:
//Createanarraycontaining6floats.Noticethebracketsaroundthearraydata.
varmy_array=newFloat32Array([1.0,2.0,3.0,-1.0,-2.0,-3.0]);
//Createanarraytohold4floatingpointnumbers.
varan_array=newFloat32Array(4);
an_array[0]=12.0;
an_array[1]=5.0;
an_array[2]=37.0;
an_array[3]=18.3;
CreatingandInitializingBufferObjects¶
NotethatbufferobjectsresideintheGPU,buttheyarecreated,managed,
anddeletedusingtheWebGLAPIfromJavaScriptcode.Hereisatypical
sequenceofcommandstocreateabufferobjectandfillitwithdata.
//-----------------------------------------------------------------------
functioncreateAndFillBufferObject(gl,data){
varbuffer_id;
//Createabufferobject
buffer_id=gl.createBuffer();
if(!buffer_id){
out.displayError('Failedtocreatethebufferobjectfor'+model_name);
returnnull;
}
//Makethebufferobjecttheactivebuffer.
gl.bindBuffer(gl.ARRAY_BUFFER,buffer_id);
//UploadthedataforthisbufferobjecttotheGPU.
gl.bufferData(gl.ARRAY_BUFFER,data,gl.STATIC_DRAW);
returnbuffer_id;
}
Pleasenotethefollowingaboutthiscode:
CreatinganobjectbufferdoesnothingmorethanreserveanewIDforanewbuffer.
Youwilltypicallyhavemanyobjectbuffersandonlyoneofthemisthe
“activebuffer”.Whenyouissuecommandsonbufferobjectsyouarealways
manipulatingthe“activebuffer”.ThebindBufferfunctionsimplychanges
the“activebuffer”tothespecificbufferusingthebuffer_id.
ThebufferDatafunctioncopiesdatafromyourJavaScriptprogram
intotheGPU’sbufferobject.Iftherewasalreadydatainthebufferobject
thenitscurrentcontentsisdeletedandthenewdataisadded.
ThemainerroryouwillreceivewhencopyingdatatotheGPUisOUT_OF_MEMORY.
Thecodeaboveshouldcheckforglerrorsbycallinggl.getError(),but
wewillworryaboutcatchingerrorslater.
Shaders,Buffers,andtheGraphicsPipeline¶
Shaderprogramsaresometimesdifficultto“wrapyourbrainaround”because
therelationshipbetweenthegraphicspipelineandashaderprogramisnot
obviousandsometimesneverexplained.Let’strytowritesomepseudocodethat
describeshowthegraphicspipelineperformsrendering.
EachtimeyourJavaScriptprogramcallsgl.drawArrays(mode,start,count),
‘count’numberofverticesaresentthroughthegraphicspipeline.
Yourvertexshaderprogramiscalledonceforeachvertexinanarrayof
verticesthatisstoredinabufferobject.
Insidethegraphicspipeline,hiddenfromyou,isaalgorithmthatisdoing
this:
for(j=start;j
延伸文章資訊
- 1使用Buffer
在〈使用attribute 變數〉中,每次只傳遞一個向量或浮點數,如果有多個頂點要繪製呢?這時可以透過Buffer,使用JavaScript 將資料放入Buffer,然後著色器從Buffer...
- 25.3 - A Primer on Buffer Objects — LearnWebGL
Buffer objects provide the data for attribute variables in vertex shader programs. Remember that ...
- 3Updating buffers from within shaders in webgl - Stack Overflow
What is the logic of binding buffers in webgl? - Stack Overflow
- 4WebGL2 Fundamentals
Buffers are arrays of binary data you upload to the GPU. ... This tells WebGL we want to get data...
- 5WebGL How It Works
Buffers are the way of getting vertex and other per vertex data onto the GPU. gl.createBuffer cre...