How to do instancing the right way in OpenGL. - Stack Overflow

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

glDrawElementsInstanced use gl_InstanceID variable as if it were a static integer vertex attribute. When the first copy of the vertices is sent to OpenGL, ... 2022DeveloperSurveyisopen!Takesurvey. 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 HowtodoinstancingtherightwayinOpenGL. AskQuestion Asked 8years,3monthsago Modified 8years,3monthsago Viewed 17ktimes 4 1 IamtryingtouseVBOandInstancingmechanismthemostefficentway.IhaveaworldbasedonvoxelsandIwouldliketodrawthemusingleastpossiblenumberofdraw-calls.ThecodebelowpreparesVBOwithaquad: voidVoxelView::initVBOs(){ /*---------------------MainOpenGLProgram---------------------*/ /*Verticesofatriangle(counter-clockwisewinding)*/ floatdata[6][3]={ //Leftbottomtriangle {-0.5f,0.5f,0.0f}, {-0.5f,-0.5f,0.0f}, {0.5f,-0.5f,0.0f}, //Righttoptriangle {0.5f,-0.5f,0.0f}, {0.5f,0.5f,0.0f}, {-0.5f,0.5f,0.0f} }; /*----------------------InitialiseVBO-(Note:doonlyonce,atstartofprogram)---------------------*/ /*CreateanewVBOandusethevariable"triangleVBO"tostoretheVBOid*/ glGenBuffers(1,&triangleVBO); /*MakethenewVBOactive*/ glBindBuffer(GL_ARRAY_BUFFER,triangleVBO); /*Uploadvertexdatatothevideodevice*/ glBufferData(GL_ARRAY_BUFFER,6*3*sizeof(float),data,GL_STATIC_DRAW); /*Specifythatourcoordinatedataisgoingintoattributeindex0(shaderAttribute),andcontainsthreefloatspervertex*/ glVertexAttribPointer(shaderAttribute,3,GL_FLOAT,GL_FALSE,0,0); /*Enableattributeindex0(shaderAttribute)asbeingused*/ glEnableVertexAttribArray(shaderAttribute); /*MakethenewVBOactive.*/ glBindBuffer(GL_ARRAY_BUFFER,triangleVBO); /*-------------------------------------------------------------------------------------------------------*/ /*---------------------LoadVertexandFragmentshadersfromfilesandcompilethem--------------------*/ /*Readourshadersintotheappropriatebuffers*/ vertexSource=filetobuf("Shaders/exampleVertexShader1.vert"); fragmentSource=filetobuf("Shaders/exampleFragmentShader1.frag"); /*Assignourhandlesa"name"tonewshaderobjects*/ vertexShader=glCreateShader(GL_VERTEX_SHADER); fragmentShader=glCreateShader(GL_FRAGMENT_SHADER); /*Associatethesourcecodebufferswitheachhandle*/ glShaderSource(vertexShader,1,(constGLchar**)&vertexSource,0); glShaderSource(fragmentShader,1,(constGLchar**)&fragmentSource,0); /*Freethetemporaryallocatedmemory*/ free(vertexSource); free(fragmentSource); /*Compileourshaderobjects*/ glCompileShader(vertexShader); glCompileShader(fragmentShader); /*-------------------------------------------------------------------------------------------------------*/ /*--------------------Createshaderprogram,attachshaderstoitandthenlinkit---------------------*/ /*Assignourprogramhandlea"name"*/ shaderProgram=glCreateProgram(); /*Attachourshaderstoourprogram*/ glAttachShader(shaderProgram,vertexShader); glAttachShader(shaderProgram,fragmentShader); /*Bindattributeindex0(shaderAttribute)toin_Position*/ /*"in_Position"willrepresent"data"array'scontentsinthevertexshader*/ glBindAttribLocation(shaderProgram,shaderAttribute,"in_Position"); /*Linkshaderprogram*/ glLinkProgram(shaderProgram); Iamrenderingthequadthefollowingway: voidVoxelView::renderVBO() { /*Setshaderprogramasbeingactivelyused*/ glUseProgram(shaderProgram); /*SetbackgroundcolourtoBLACK*/ glClearColor(0.0,0.0,0.0,1.0); /*ClearbackgroundwithBLACKcolour*/ glClear(GL_COLOR_BUFFER_BIT); /*Actuallydrawthetriangle,givingthenumberofverticesprovidedbyinvokeglDrawArrays whiletellingthatourdataisatriangleandwewanttodraw0-3vertexes */ glDrawArrays(GL_TRIANGLES,0,6); } Iwouldliketodrawthisquad(whichusesVBO)multipletimesusingtheinstancingmechanizm.IwouldlikeittofefairlysimpleasIwanttoimplementitformoresophisticatedcode.IknowthatIshoulduseglDrawElementsInstancedmethodtouseinstancingbutIdon'tknowhowtodoit.Doesanybodyknowhowtodoit? c++openglvbogpu Share Improvethisquestion Follow askedFeb3,2014at22:32 PawełJastrzębskiPawełJastrzębski 72711goldbadge66silverbadges2424bronzebadges 1 AlwaysincludeyourOpenGLversioninfuture...itmakesanenormousdifferenceasyouprobablyknow. – Engineer Dec20,2014at19:09 Addacomment  |  1Answer 1 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 7 WhenusingglDrawElementsInstancedyouneedtomakeyourshadersusegl_InstanceiD #version410 layout(location=0)invec3Position; layout(location=1)invec2TexCoord; layout(location=2)invec3Normal; layout(location=3)inmat4WVP; layout(location=7)inmat4World; outvec2TexCoord0; outvec3Normal0; outvec3WorldPos0; flatoutintInstanceID; voidmain() { gl_Position=WVP*vec4(Position,1.0); TexCoord0=TexCoord; Normal0=World*vec4(Normal,0.0)).xyz; WorldPos0=World*vec4(Position,1.0)).xyz; InstanceID=gl_InstanceID; }; glDrawElementsInstancedusegl_InstanceIDvariableasifitwereastaticintegervertexattribute.WhenthefirstcopyoftheverticesissenttoOpenGL, gl_InstanceIDwillbezero.ItwillthenbeincrementedonceforeachcopyofthegeometryandwilleventuallyreachinstanceCount-1. Itbehaveslikethis for(intn=0;nand#include"filename"? 2960 Howdoyouset,clear,andtoggleasinglebit? 3696 WhatarethedifferencesbetweenapointervariableandareferencevariableinC++? 3408 Whatdoestheexplicitkeywordmean? 3251 HowdoIiterateoverthewordsofastring? 4234 TheDefinitiveC++BookGuideandList 9741 Whatisthe"-->"operatorinC/C++? 2393 WhatisTheRuleofThree? 1945 EasiestwaytoconvertinttostringinC++ 1 Opengltrianglenotdrawn HotNetworkQuestions Whatmakesaluminumaerospacegrade? Didmyprofessoractunethicallybypublishingapaperwithafigurefrommythesiswithoutanyacknowledgement? IsitallowedtocopycodeundertheUnityReference-OnlyLicense? Using\textsc{}manuallyinsection Partitioningalistbasedonacriterionforsublists WhyisMIDIgainbasedonafactorof40? DidSauroneverconsiderthattheValarand/orEruIlúvatarmaynotallowhimtoconquerMiddle-earth? Waystomakeanalienatmospherebreathable,butuncomfortable? QGISreadsblankcellsas"nan"insteadof"NULL" HowManyDaysAfterSkimCoatCanIPaint? WhatisRNAVtransitionandwhatisthedifferencebetweenRNAVtransitionandRNAVSTAR StarWars:R2D2connectedtomainframe Ihaveanarmadaofteleportingskyfortresses.DoIstillneedanavy? ESTAform:Mentionthecitydistrictinthecontactinformationsection? GenerateAll8Knight'sMoves Mathematica13.0simplifiestrigonometricintegralwrong Twoparallelrelaysfordoublecurrent Non-committingauthenticatedencryptionschemesvscommittingauthenticatedencryptionschemes WhatpreventsmefrommakingonebigestimatedFederaltaxpaymentonJan15? Inbetweenfractions Iwant8bitsforeverycharacter! FindthenthFibonaccinumber,wherenisthemthFibonaccinumber Howcanaprivatekeybeimportedtoadescriptorwallet? Iworkfromhomeasasoftwareengineerandmyjobishappywithmyperformance.ButI'mputtinginlittleeffort.AmIabadpersonoremployee? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-cpp Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?