When should I enable/disable vertex position attributes in ...

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

I'm working on some WebGL code that has multiple shader programs that run sequentially. Previously, I was using gl.enableVertexAttribArray(...) ... Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore WhenshouldIenable/disablevertexpositionattributesinWebGL/OpenGL? AskQuestion Asked 6years,3monthsago Modified 1year,2monthsago Viewed 6ktimes 6 2 I'mworkingonsomeWebGLcodethathasmultipleshaderprogramsthatrunsequentially. Previously,Iwasusinggl.enableVertexAttribArray(...)asrequiredduringinitializationformyglcontextandshaders.Iassumed,perhapsincorrectly,thatcallingthisfunctionwassettingstatespecifictotheprogramselectedbygl.useProgram(...) Now,myfirstshaderprogramhastwoenabledattributearrays,andmysecondonehasoneenabled.Whenthesecondprogramruns,Igetanerror: Error:WebGL:drawArrays:noVBOboundtoenabledvertexattribindex1! SothatleadsmetothinkthatmaybeIneedtobedisablingvertexattribute1afterusingitinthefirstprogram,butIwantedtoverifythatthisishowI'msupposedtobedoingit,andhopefullygetanexplanationofwhythisisorisn'tcorrect. IsthebestpracticetoenableVertexAttribArray(...)anddisableVertexAttribArrayforeveryarraylocationbeforeandaftereachuse? javascriptwebgl Share Follow editedMar29,2016at15:33 NicolBolas 416k6262goldbadges720720silverbadges912912bronzebadges askedMar29,2016at15:17 JoshuaBreedenJoshuaBreeden 1,69311goldbadge1515silverbadges2727bronzebadges 2 soundslikeitexpectsitafteryousetthevertexAttribPointer – ratchetfreak Mar29,2016at15:24 Whoops...Idescribeditincorrectlybefore.Editednow,butit'smyfirstprogramwithtwoattributes,andmysecondwithone.Anditdoesn'tlikegoingtooneafterstartingwithtwo. – JoshuaBreeden Mar29,2016at15:26 Addacomment  |  3Answers 3 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 7 I'venevercalleddisableVertexAttribArrayinmylifeandI'vewritten100sofWebGLprograms.Theremayormaynotbeanyperfbenefitstocallingitbutthere'snocompatibilityissuestonotcallingit. Thespecsaysyou'llonlygetanerroriftheattributeisconsumedbythecurrentprogramandaccesswouldbeoutofrangeorifthere'snobufferboundtoanenabledattribute. Wecantestthatandseethatitworksjustfine. varvsThatUses2Attributes=` attributevec4position; attributevec2texcoord; varyingvec2v_texcoord; voidmain(){ v_texcoord=texcoord; gl_Position=position; } `; varvsThatUses1Attribute=` attributevec4position; varyingvec2v_texcoord; voidmain(){ v_texcoord=position.xy*0.5+0.5; gl_Position=position+vec4(1,0,0,0); } `; varfs=` precisionmediumpfloat; varyingvec2v_texcoord; voidmain(){ gl_FragColor=vec4(v_texcoord,v_texcoord.x*v_texcoord.y,1); } `; vargl=document.querySelector("canvas").getContext("webgl"); document.body.appendChild(gl.canvas); varprogramThatUses2Attributes=twgl.createProgramFromSources(gl,[vsThatUses2Attributes,fs]); varprogramThatUses1Attribute=twgl.createProgramFromSources(gl,[vsThatUses1Attribute,fs]); varpositionLocation2AttribProg=gl.getAttribLocation(programThatUses2Attributes,"position"); vartexcoordLocation2AttribProg=gl.getAttribLocation(programThatUses2Attributes,"texcoord"); varpositionLocation1AttribProg=gl.getAttribLocation(programThatUses1Attribute,"position"); varpositionBufferFor2AttribPrg=gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER,positionBufferFor2AttribPrg); gl.bufferData(gl.ARRAY_BUFFER,newFloat32Array([ -1,-1, -.5,1, 0,-1, ]),gl.STATIC_DRAW); vartexcoordBufferFor2AttribPrg=gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER,texcoordBufferFor2AttribPrg); gl.bufferData(gl.ARRAY_BUFFER,newFloat32Array([ 0,0, 0.5,1, 1,0, ]),gl.STATIC_DRAW); varpositionBufferFor1AttribPrg=gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER,positionBufferFor1AttribPrg); gl.bufferData(gl.ARRAY_BUFFER,newFloat32Array([ -1,-1, 0,-1, -1,1, -1,1, 0,-1, 0,1, ]),gl.STATIC_DRAW); //turnon2attributes gl.enableVertexAttribArray(positionLocation2AttribProg); gl.enableVertexAttribArray(texcoordLocation2AttribProg); gl.bindBuffer(gl.ARRAY_BUFFER,positionBufferFor2AttribPrg); gl.vertexAttribPointer(positionLocation2AttribProg,2,gl.FLOAT,false,0,0); gl.bindBuffer(gl.ARRAY_BUFFER,texcoordBufferFor2AttribPrg); gl.vertexAttribPointer(texcoordLocation2AttribProg,2,gl.FLOAT,false,0,0); //drawwith2attributesenabled gl.useProgram(programThatUses2Attributes); gl.drawArrays(gl.TRIANGLES,0,3); //setupforsecondprogramthatusesonly1attribute gl.bindBuffer(gl.ARRAY_BUFFER,positionBufferFor1AttribPrg); gl.vertexAttribPointer(positionLocation1AttribProg,2,gl.FLOAT,false,0,0); //NOTICEWEHAVE!NOTturnedoffotherattribute gl.useProgram(programThatUses1Attribute); gl.drawArrays(gl.TRIANGLES,0,6); log("glError:",gl.getError()); functionlog(){ varpre=document.createElement("pre"); pre.appendChild(document.createTextNode(Array.prototype.join.call(arguments,""))); document.body.appendChild(pre); } canvas{border:1pxsolidblack;}

Thisexampledrawsatrianglewith3verticesusing2attributes.

Itthendrawsaquadusing6verticesand1attribute
WITHOUTTURNINGOFFTHENOW2ndUNUSEDATTRIBUTE.

Thatmeansnotonlyisthatattributeleftonbutitonlyhas3verticeseven
thoughthedrawwilluse6vertices.Becausethatattributeisnot'comsumed'by
thecurrentprogramit'sokaccordingtothespec.
So,yourerrorislikelysomethingelse. Notethatdeletingabufferwillunbinditfromtheattribute,atwhichpointitwillbeanenabledattributewithnobufferandcauseanerrorunlessyoudisableit. Attributestateisseparatefromprogramstatewhichyoufoundout. Yourerrormeansexactlywhatitsays.Youtriedtodraw,thatprogramrequireddataonattribute#1.Youenableditatsomepointwithgl.enableVertexAttribArraybutyoudidn'tgiveitanydatawithgl.vertexAttribPointer.Soyougotanerror. Notethatgl.vertexAttribPointerbindsthebuffercurrentlyboundtogl.ARRAY_BUFFERtothespecifiedattribute. Youmightfindthisansweruseful https://stackoverflow.com/a/27164577/128511 Share Follow editedMay23,2017at11:44 CommunityBot 111silverbadge answeredMar30,2016at6:46 gmangman 93k2929goldbadges235235silverbadges349349bronzebadges 0 Addacomment  |  5 ThisQ/Ahelpedmeanswermyquestion: Conflictwhenusingtwoormoreshaderswithdifferentnumberofattributes Inordertomakeitworkcorrectly,Ineededtodisableunusedattributesbeforedrawingwithashaderprogramthatdoesn'tusethem.Ican'texplainwhysomepeoplesaythisshouldn'tbenecessary,butdoingsosolvesmyproblem. Share Follow editedMay23,2017at12:32 CommunityBot 111silverbadge answeredApr7,2016at21:16 JoshuaBreedenJoshuaBreeden 1,69311goldbadge1515silverbadges2727bronzebadges Addacomment  |  0 You'llneverneedstocalldisableVertexAttribArray()inWebGL.I'llnotewhythismethodactuallyexistsatfirst. Asyouknow,WebGLwasjustaportedlibraryfromOpenGLES2,andOpenGLES2isasubsetofOpenGL. InthelistoftheAPIofOpenGL,thereissomeoftheotherwaytopassvertexbufferstoGPUwithoutspecifyingvertexbufferaspointer. Forinstance,inOpenGLenvironmentyoucansendvertexbufferdatabycallinggl.begin(),gl.Vertex(),gl.end()andsoon. Inthisway,youdon'tneedtocallgl.enableVertexAttribArray(). ButthereisnowaytospecifybufferswithoutcallingenableVertexAttribArray()inWebGL.Therefore,youneverneedtocallthemethod,itisjustahistoricalreason. Andyoudon'tneedtocallenableVertexAttribArray()ineachframe.Itisveryheavyoperationsinceyoushouldnotcallthateachframe. YoujustneedstocallenableVertexAttribArray()justafterinitializingbuffer. Share Follow editedMay4,2021at16:11 AlexisWilke 17.4k1010goldbadges7373silverbadges132132bronzebadges answeredApr1,2016at14:37 kyasbalkyasbal 1,02211goldbadge1010silverbadges2323bronzebadges 3 So,theissueI'mrunningintoisassuch:IfIenableVertex...atinitialization,Igettheerror.However,ifIenableVertex...beforeeachredraw,itworksfine.Notethatthisisforthefirstlayer(withtwovertexattribs),notthesecondone.Thecodeofthesecondoneremainsunchanged,butit'stheplacethrowingtheerrorwhenIchangethefirstshader. – JoshuaBreeden Apr4,2016at20:52 Andyoudon'tneedtocallenableVertexAttribArrayineachframe.Itisveryheavyoperationsinceyoushouldnotcallthateachframe.YoujustneedstocallenableVertexAttribArrayjustafterinitializingbuffer.Thisisbadadvice.YouneedtoenablethevertexattributesthatyourVBOisexposingANDyourshaderisconsuming.IfyourshaderexpectsanattributeyourVBOdoesn'tprovide,youmustdisablesaidattribute,oryouwillgetanaccessviolationduringrendering.AnotheroptionistoskiprenderingiftheshaderandVBOdon'tmatch100%. – Tara Nov18,2019at20:42 1 "glEnableVertexAttribArray()"and"glDisableVertexAttribArray()"affectglobalstate.Thereforewheneveryourenderanobjectwithadifferentshaderorvertexlayout,youmustenable/disablevertexattributesaccordingly. – Tara Nov18,2019at20:43 Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedjavascriptwebgloraskyourownquestion. TheOverflowBlog HowStackOverflowislevelingupitsunittestinggame Developersvsthedifficultybomb(Ep.459) FeaturedonMeta Testingnewtrafficmanagementtool Duplicatedvotesarebeingcleanedup Trending:Anewanswersortingoption Updatedbuttonstylingforvotearrows:currentlyinA/Btesting Visitchat Linked 12 Whatisthelogicofbindingbuffersinwebgl? 3 Conflictwhenusingtwoormoreshaderswithdifferentnumberofattributes 1 gl_PositionwillnotmovevertexwhenIpassinpositiontoshaderwithattribute? Related 2197 WhenshouldIusedoubleorsinglequotesinJavaScript? 2473 Disable/enableaninputwithjQuery? 1638 WhatisthepurposeofthevarkeywordandwhenshouldIuseit(oromitit)? 933 jQuerydisable/enablesubmitbutton 1444 Howdoesthe"this"keywordwork,andwhenshoulditbeused? 60 IsitimportanttocallglDisableVertexAttribArray()? 1036 WhenshouldIusecurlybracesforES6import? 0 webGL-vertexAttribPointer:Bad`type`:NONE 1 WebGL:noVBOboundtoenabledvertex.DoIneed"vertexAttribPointer"forvertexindices? 1 WebGL:Oneprogram'svertexattributeinfluencesotherprogram HotNetworkQuestions WhatmightImakeaplayerrolliftheyaskaphysical,self-awarenessquestion? SecrecyinMathematics Stagnatedrenaissanceeratechnologyinafantasysetting? Managermakingmeworkextrapost-notice(UK—Scotland) Whyisthe所有misplacedin今年所有发生的事情? HowdoInotatealternatingquicklybetweentwonotesanoctaveawayfromeachother? WhyisDante'sMagnumOpusCalleda'DivineComedy'? AsBlack,howdoyoudealwiththedoublepawnsintheRuyLopezexchangevariation? Whatpumpsbloodthroughalistener'sbody? DoIhavelegalobligationtochangethepaymentmethodatarestaurant,iftheyrefuseto(buthavetheabilityto)acceptmycreditcard? ProofinconstructivemathematicsthattheprincipalsquarerootfunctionexistsinanyCauchycompleteArchimedeanorderedfield HowdoIknowwhichweaponstokeepinBorderlands2? DevelopmentofOldNorse2ndand3rdpersonsg.(presentindicative)formsof"tobe" WhataretheparameterswhichIcanusetocomparetheresearchtworesearchersinPureMathematics? Howtoinsertpilcrow¶atthestartofeachparagraphautomatically CanIusemultipletransistorsinparallelifasingletransistorcan'tcarryenoughcurrent? WhyandhowwouldItransmitemailsviaseveralMailTransferAgents? GolfGitHub'sPagerLogic Controllinganopponent'sCosima,GodoftheVoyage Partswithnopartnumberhowisitidentified?(needhelp,butforfuturetoo) Creatingatitlepage Problemmodellingasimpleshapeandthenapplyingsubdivisionsurfacemodifier Doesawatercloset(toiletstall)requireanelectricaloutlet? Short-termcapitalgainstaxoncryptocurrency morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-js Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?