Shadow Mapping OpenGL shadow not always drawing, and ...

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

Is there an easy way to get shadows in OpenGL? - Stack ... 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 ShadowMappingOpenGLshadownotalwaysdrawing,anddrawingwherethepositionofthelightis AskQuestion Asked 2years,2monthsago Modified 2years,2monthsago Viewed 140times 1 IhavebeentryingtodobasicShadowMappinginmycustomEngineusingLearnOpenGLasthesource.Thelinkfortheexacttutorialcanbefound:here. Ihavebeendebuggingthisbugforaroundtwoweeks,researchingtheinternet,andeventryingtowrapmyheadaroundthis,butallIcansayisthattheshadowalmostneverappears,andwhenitappearsitiswherethelightisPosistermsofxandz.Itriedtodoeverythingexactlylikeinthetutorialaround10times,IalsotriedtocheckthiswebsiteforsimilarquestionsbutforeverywayIfound,itwasnotmycase. findings InthisImage(1)youcanseethattheshadowisnotvisiblewhenthelightisontopofit,butitisthenvisibleonthisImage(2)whenthelightPos.xvariableisaround-4.5or4.5,thisissoforthelightPos.zvariabletoo.TheshadowwhenappearingisbeingdrawnwherethelightPosis,whereinthepicturesitiscircledbyaredline. Iusemultipleshaders,oneforthelightandshadowcalculations(ShadowMapping)oneforabasicdepthmapping(ShadowMapGen) HereismyShadowMappingshader: ShadowMappingVertex version460 invec3vertexIn; invec3normalIn; invec2textureIn; outvec3FragPos; outvec3normalOut; outvec2textureOut; outvec4FragPosLightSpace; uniformmat4model; uniformmat4view; uniformmat4projection; uniformmat4lightSpaceMatrix; voidmain() { textureOut=textureIn; FragPos=vec3(model*vec4(vertexIn,1.0)); normalOut=mat3(transpose(inverse(model)))*normalIn; FragPosLightSpace=lightSpaceMatrix*vec4(FragPos,1.0); gl_Position=projection*view*model*vec4(vertexIn,1.0); } ShadowMappingFrag outvec4FragColor; invec3FragPos; invec3normalOut; invec2textureOut; invec4FragPosLightSpace; uniformsampler2DdiffuseTexture; uniformsampler2DshadowMap; uniformvec3lightPos; uniformvec3viewPos; floatShadowCalculation(vec4fragPosLightSpace,vec3lightdir) { //performperspectivedivide vec3projCoords=fragPosLightSpace.xyz/fragPosLightSpace.w; //transformto[0,1]range projCoords=projCoords*0.5+0.5; //getclosestdepthvaluefromlight'sperspective(using[0,1]rangefragPosLightascoords) floatclosestDepth=texture(shadowMap,projCoords.xy).r; //getdepthofcurrentfragmentfromlight'sperspective floatcurrentDepth=projCoords.z; //checkwhethercurrentfragposisinshadow floatbias=max(0.05*(1.0-dot(normalOut,lightdir)),0.005); //checkwhethercurrentfragposisinshadow //floatshadow=currentDepth-bias>closestDepth?1.0:0.0; ////PCF floatshadow=0.0; vec2texelSize=1.0/textureSize(shadowMap,0); for(intx=-1;x<=1;++x) { for(inty=-1;y<=1;++y) { floatpcfDepth=texture(shadowMap,projCoords.xy+vec2(x,y)*texelSize).r; shadow+=currentDepth-bias>pcfDepth?1.0:0.0; } } shadow/=9.0; //keeptheshadowat0.0whenoutsidethefar_planeregionofthelight'sfrustum. if(projCoords.z>1.0) shadow=0.0; returnshadow; } voidmain() { vec3color=texture(diffuseTexture,textureOut).rgb; vec3normal=normalize(normalOut); vec3lightColor=vec3(1.0f); //ambient vec3ambient=0.30*color; //diffuse vec3lightDir=normalize(lightPos-FragPos); floatdiff=max(dot(lightDir,normal),0.0); vec3diffuse=diff*lightColor; //specular vec3viewDir=normalize(viewPos-FragPos); vec3reflectDir=reflect(-lightDir,normal); floatspec=0.0; vec3halfwayDir=normalize(lightDir+viewDir); spec=pow(max(dot(normal,halfwayDir),0.0),64.0); vec3specular=spec*lightColor; //calculateshadow floatshadow=ShadowCalculation(FragPosLightSpace,lightDir); vec3lighting=(ambient+(1.0-shadow)*(diffuse+specular))*color; FragColor=vec4(lighting,1.0); } ShadowMapGenVertex FragmentShaderisemptyforthisshader version460 invec3vertexIn; uniformmat4model; uniformmat4lightSpaceMatrix; voidmain() { gl_Position=model*lightSpaceMatrix*vec4(vertexIn,1.0); } Variableinitialisation lightPos=glm::vec3(-2.0f,4.0f,-1.0f); near_plane=1.0f; far_plane=7.5f; //SAMPLE2DUniformbinding TheShader::Instance()->SendUniformData("ShadowMapping_diffuseTexture",0); TheShader::Instance()->SendUniformData("ShadowMapping_shadowMap",1); DepthMapFramebufferGeneration ThisishowIgeneratemydepthmap/shadowmaptextureintheconstructorofmyscene: glGenFramebuffers(1,&depthMapFBO); //Createdepthtexture glGenTextures(1,&depthMap); glBindTexture(GL_TEXTURE_2D,depthMap); glTexImage2D(GL_TEXTURE_2D,0,GL_DEPTH_COMPONENT,SHADOW_WIDTH,SHADOW_HEIGHT,0,GL_DEPTH_COMPONENT,GL_FLOAT,NULL);//HeightandWidth=1024 glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_BORDER); floatborderColor[]={1.0,1.0,1.0,1.0}; glTexParameterfv(GL_TEXTURE_2D,GL_TEXTURE_BORDER_COLOR,borderColor); //AttachdepthtextureasFBO'sdepthbuffer glBindFramebuffer(GL_FRAMEBUFFER,depthMapFBO); glFramebufferTexture2D(GL_FRAMEBUFFER,GL_DEPTH_ATTACHMENT,GL_TEXTURE_2D,depthMap,0); glDrawBuffer(GL_NONE); glReadBuffer(GL_NONE); glBindFramebuffer(GL_FRAMEBUFFER,0); TheninanUpdate()functionthatrunsintheWhileloopoftheengineIfirstlydo: RenderObjectsfromlight'sperspective //LightProjectionandviewMatrix m_lightProjection=glm::ortho(-10.0f,10.0f,-10.0f,10.0f,near_plane,far_plane); m_lightView=glm::lookAt(lightPos,glm::vec3(0.0f),glm::vec3(0.0f,1.0f,0.0f)); //Calculatelightmatrixandsendit. m_lightSpaceMatrix=m_lightProjection*m_lightView; TheShader::Instance()->SendUniformData("ShadowMapGen_lightSpaceMatrix",1,GL_FALSE,m_lightSpaceMatrix); //RendertoFramebufferdepthMap glViewport(0,0,SHADOW_WIDTH,SHADOW_HEIGHT); glBindFramebuffer(GL_FRAMEBUFFER,depthMapFBO); glClear(GL_DEPTH_BUFFER_BIT); //SetcurrentShadertoShadowMapGen m_floor.SetShader("ShadowMapGen"); m_moon.SetShader("ShadowMapGen"); //SendmodelMatrixtocurrentShader m_floor.Draw(); m_moon.Draw(); //SetcurrentShaderbacktoShadowMapping m_moon.SetShader("ShadowMapping"); m_floor.SetShader("ShadowMapping"); glBindFramebuffer(GL_FRAMEBUFFER,0); RenderObjectsfromCamera'sperspective glViewport(0,0,SCREEN_WIDTH,SCREEN_HEIGHT); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); //UpdateCameraandSendtheviewandprojectionmatricestotheShadowMappingshader m_freeCamera->Update(); m_freeCamera->Draw(); //SendLightPos TheShader::Instance()->SendUniformData("ShadowMapping_lightPos",lightPos); //SendLightSpaceMatrix TheShader::Instance()->SendUniformData("ShadowMapping_lightSpaceMatrix",1,GL_FALSE,m_lightSpaceMatrix); //ActivateShadowMappingtexture glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D,depthMap); //SendmodelMatrixtoShadowMappingshaders m_moon.Draw(); m_floor.Draw(); Ihopesomeonewillseethis,thankyouforyourtime. c++openglframebuffershadow-mapping Share Improvethisquestion Follow askedMar15,2020at16:18 MrAbnoxMrAbnox 2366bronzebadges Addacomment  |  1Answer 1 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 2 Itriedtodoeverythingexactlylikeinthetutorialaround10times Well,youseemtohavemissedatleastoneobviousthing: m_lightSpaceMatrix=m_lightProjection*m_lightView; Sofar,sogood,butinyour"ShadowMapGen"vertexshader,youwrote: gl_Position=model*lightSpaceMatrix*vec4(vertexIn,1.0); Soyouendupwithmodel*projection*viewmultiplicationorder,whichdoesnotmakesensenomatterwhichconventionsyouadhereto.SincethetutorialusesdefaultGLconventions,youalwaysneedprojection*view*model*vertexmultiplicationorder,whichthetutorialalsocorrectlyuses. Share Improvethisanswer Follow answeredMar15,2020at17:02 derhassderhass 41.4k22goldbadges5050silverbadges7070bronzebadges 2 Justtested,anditworks.Yes,youareright,Ican'tbelieveIoverlookedthissmalldetail.Thanksforyourtime. – MrAbnox Mar15,2020at17:11 1 Didn'tcostmemuchtime,wastheveryfirstthingIlookedat...:) – derhass Mar15,2020at17:20 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?Browseotherquestionstaggedc++openglframebuffershadow-mappingoraskyourownquestion. TheOverflowBlog Makeyouropen-sourceprojectpublicbeforeyou’reready(Ep.444) Thescienceofinterviewingdevelopers FeaturedonMeta AnnouncingthearrivalofValuedAssociate#1214:Dalmarus Improvementstositestatusandincidentcommunication RetiringOurCommunity-SpecificClosureReasonsforServerFaultandSuperUser Temporarilypausingthesitesatisfactionsurvey StagingGround:ReviewerMotivation,Scaling,andOpenQuestions Related 1290 WhereandwhydoIhavetoputthe"template"and"typename"keywords? 18 PointersonmodernOpenGLshadowcubemapping? 1 CreatingatrianglewithOpenGL&GLSL 0 OpenGLShadowMappingdualshader 10 MultilightsshadowmappingdoesnotworkcorrectlyusingGLSL 1 OpenGLshadowmapping-shadowmaptexturedoesn'tgetsampledatall? 0 ShadowmapblankwithGL_LESSbutnotwithGL_GREATERorGL_ALWAYS? HotNetworkQuestions WhatwasthereasonforextendingNATOinthe90s? Differencebetweenproductsandcoproducts. Haveastronomerstakenintoaccountthefactthatred-shiftedlightfromfar-awaystarsisalsoveryoldwhenstudyingtheexpansionoftheuniverse? Myboss:"Ifeeljealous" CovidTestRequirementforDubaiTransitFromIrelandtoIndonesia Meaningofclappingattheendofmass Isitillegaltorideadrunkhorse? Whyisacapacitortogroundalowfrequencypole,insteadofahighfrequencyzero? CanWgatebewrittenonlyusingH,T? HowcanItellwhich3rdpartyflashesarecompatiblewithCanon'sSL3missingpinhotshoemount? sObjecttypesfromstring Tryingtouseacaralternatorforapowersource(notforcar) WhywouldIuseatrainerinsteadofridingoutside? Waystomakeanalienatmospherebreathable,butuncomfortable? Ihaveanarmadaofteleportingskyfortresses.DoIstillneedanavy? Whatdoestheidiomaticphrase"erronthesideof"mean? HowManyDaysAfterSkimCoatCanIPaint? Whatdoyoucalladesperateattemptunlikelytosucceed? ShouldIrevealmyslidesbit-by-bitwhengivingapresentation/lecture? GenerateAll8Knight'sMoves Whatisthemostecologicallysustainablewaytohandleragscoveredinchaingrease? HowdoesHebrews11:27sayMoseswasnotafraid? HowcanaverbalreasoningquestionbesolvedwithMathematica? Non-committingauthenticatedencryptionschemesvscommittingauthenticatedencryptionschemes morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-cpp Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?