I've mostly implemented cascading shadow maps (CSM), ... And samples the shadow map array with this function: ... opengl shadow-mapping.
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
CascadedShadowmapsnotquiteright
AskQuestion
Asked
7years,2monthsago
Modified
7years,2monthsago
Viewed
2ktimes
3
Ok.So,I'vebeenmessingaroundwithshadowsinmygameengineforthelastweek.I'vemostlyimplementedcascadingshadowmaps(CSM),butI'mhavingabitofaproblemwithshadowingthatIjustcan'tseemtosolve.
Theonlylightinthissceneisadirectionallight(sun),pointing{-0.1-0.25-0.65}.Icalculate4setsoffrustumboundsforthefoursplitsofmyCSMswiththiscode:
//eachprojectionmatrixcalculatedwithsamenearplane,differentfar
Frustummake_worldFrustum(constglm::mat4&_invProjView){
Frustumfr;glm::vec4temp;
temp=_invProjView*glm::vec4(-1,-1,-1,1);
fr.xyz=glm::vec3(temp)/temp.w;
temp=_invProjView*glm::vec4(-1,-1,1,1);
fr.xyZ=glm::vec3(temp)/temp.w;
...etc6moretimesforndccube
returnfr;
}
Forthelight,Igetaviewmatrixlikethis:
glm::mat4viewMat=glm::lookAt(cam.pos,cam.pos+lightDir,{0,0,1});
Ithencreateeachorthomatrixfromtheboundsofeachfrustum:
lightMatVec.clear();
for(auto&frus:cam.frusVec){
glm::vec3arr[8]{
glm::vec3(viewMat*glm::vec4(frus.xyz,1)),
glm::vec3(viewMat*glm::vec4(frus.xyZ,1)),
etc...
};
glm::vec3minO={INFINITY,INFINITY,INFINITY};
glm::vec3maxO={-INFINITY,-INFINITY,-INFINITY};
for(auto&vec:arr){
minO=glm::min(minO,vec);
maxO=glm::max(maxO,vec);
}
glm::mat4projMat=glm::ortho(minO.x,maxO.x,minO.y,maxO.y,minO.z,maxO.z);
lightMatVec.push_back(projMat*viewMat);
}
Ihavea4layerTEXTURE_2D_ARRAYboundto4framebuffersthatIdrawthesceneintowithaverysimplevertexshader(fragdisabledorpunchthroughalpha).
Ithendrawthefinalscene.Thevertexshaderoutputsfourshadowtexcoords:
outvec3slShadcrd[4];
//stuff
for(inti=0;i<4;i++){
vec4sc=WorldBlock.skylMatArr[i]*vec4(world_pos,1);
slShadcrd[i]=sc.xyz/sc.w*0.5f+0.5f;
}
Andafragmentshader,whichdeterminesthesplittousewith:
intcsmIndex=0;
for(uinti=0u;iCameraBlock.csmSplits[i])index++;
elsebreak;
}
Andsamplestheshadowmaparraywiththisfunction:
floatsample_shadow(vec3_sc,int_csmIndex,sampler2DArrayShadow_tex){
returntexture(_tex,vec4(_sc.xy,_csmIndex,_sc.z)).r;
}
And,thisisthesceneIget(witheachsplitslightlytintedandthe4depthlayersoverlayed):
Great!Looksgood.
But,ifIturnthecameraslightlytotheright:
Thenshadowsstartdisappearing(anddependingontheangle,appearingwheretheyshouldn'tbe).
IhaveGL_DEPTH_CLAMPenabled,sothatisn'ttheissue.I'mcullingfrontfaces,butturningthatoffdoesn'tmakeadifferencetothisissue.
WhatamImissing?Ifeellikeit'sanissuewithoneofmyprojections,buttheyalllookrighttome.Thanks!
EDIT:
Allfourofthethelight'sfrustumsdrawn.Theyareallthere,butonlyzischangingrelativetothecamera(seecommentbelow):
EDIT:
Probablymoreuseful,thisishowthefrustumslookwhenIonlyupdatethemonce,whenthecameraisat(0,0,0)andpointingforwards(0,1,0).AlsoIdrewthemwithdepthtestingthistime.
IMPORTANTEDIT:
Itseemsthatthisissueisdirectlyrelatedtothelight'sviewmatrix,currently:
glm::mat4viewMat=glm::lookAt(cam.pos,cam.pos+lightDir,{0,0,1});
Changingthevaluesforeyeandtargetseemstoaffectthebuggeredshadows.ButIdon'tknowwhatIshouldactuallybesettingthisto?Shouldbeeasyforsomeonewithabetterunderstandingthanme:D
openglshadow-mapping
Share
Improvethisquestion
Follow
editedMar5,2015at6:49
Jagoly
askedMar4,2015at6:15
JagolyJagoly
92911goldbadge77silverbadges2929bronzebadges
4
Idon'tseeanythingobviousinthecode.Maybedrawthefrustumofthecascadestoseeiftheylookcorrect(thecoloronthegrounddoesn'tgiveenoughinfo.)
– Jerem
Mar4,2015at9:02
(By"drawthefrustum",Imeanjustawireframebox.)
– Jerem
Mar4,2015at9:09
Whichfrustumdoyoumeantodraw?Ijustsetupcodetodrawthefrustumsofthefinalshadowmatrices,andtheytheyalllookidenticalfromthecamera'sPOV,butdoindeedhavedifferentvalues.IsthisbecausetheonlyvalueschangingrelativetothecameraaretheZvalues?Isthathowitshouldbe?
– Jagoly
Mar4,2015at10:44
Also,Ijustdrewthecamera'sviewfrustumsout,andtheyjustformanoutlinearoundtheviewport,whichseemscorrect.
– Jagoly
Mar4,2015at10:57
Addacomment
|
1Answer
1
Sortedby:
Resettodefault
Highestscore(default)
Datemodified(newestfirst)
Datecreated(oldestfirst)
4
Solvedit!Itwasindeedanissuewiththelight'sviewmatrix!AllIhadtodowasreplacecamPoswiththecentrepointofeachfrustum!Meaningthateachsplit'slightmatrixneededadifferentviewmatrix.SoIjustcreateeachviewmatrixlikethis...
glm::mat4viewMat=glm::lookAt(frusCentre,frusCentre+lightDir,{0,0,1});
AndgetfrusCentresimply...
glm::vec3calc_frusCentre(constFrustum&_frus){
glm::vec3min(INFINITY,INFINITY,INFINITY);
glm::vec3max(-INFINITY,-INFINITY,-INFINITY);
for(auto&vec:{_frus.xyz,_frus.xyZ,_frus.xYz,_frus.xYZ,
_frus.Xyz,_frus.XyZ,_frus.XYz,_frus.XYZ}){
min=glm::min(min,vec);
max=glm::max(max,vec);
}
return(min+max)/2.f;
}
Andbam!Everythingworksspectacularly!
EDIT(Lastone!):
WhatIhadwasnotquiteright.Theviewmatrixshouldactuallybe:
glm::lookAt(frusCentre-lightDir,frusCentre,{0,0,1});
Share
Improvethisanswer
Follow
editedMar5,2015at14:33
answeredMar5,2015at7:29
JagolyJagoly
92911goldbadge77silverbadges2929bronzebadges
2
1
Interesting...IhaveneverconsideredusingINFINITYtoinitializeminbefore.Iwasalwaysafraiditwouldnotbesupportedonallsystems,soinsteadIhaveusedFLT_MAX.However,INFINITYisanicersolutionbecausemathinvolvingitwillproduceNAN,makingitobviousthatsomething'suninitialized.IjustcheckedandINFINITYisdefinedasFLT_MAXonsystemsthatdonotsupporttheInfinityandQuietNaNfloating-pointbitpatterns,whichmakesitperfectlyusableonallsystems;+1formakingmelearnthat;)
– AndonM.Coleman
Mar5,2015at13:14
ConsideringhowmuchI'velearnedfromyou,thatmakesmefeelprettygreat:D
– Jagoly
Mar5,2015at14:31
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?Browseotherquestionstaggedopenglshadow-mappingoraskyourownquestion.
TheOverflowBlog
Makeyouropen-sourceprojectpublicbeforeyou’reready(Ep.444)
Thescienceofinterviewingdevelopers
FeaturedonMeta
AnnouncingthearrivalofValuedAssociate#1214:Dalmarus
Improvementstositestatusandincidentcommunication
RetiringOurCommunity-SpecificClosureReasonsforServerFaultandSuperUser
Temporarilypausingthesitesatisfactionsurvey
StagingGround:ReviewerMotivation,Scaling,andOpenQuestions
Related
0
OpenGLShadowMappingdualshader
0
JOGLshadowmapping
1
CascadedShadowMapsdon'tworkasexpected
0
Shadowmapworkswithorthoprojection,butnotperspectiveprojection
0
Passingavec3toglm::lookAtappearstomodifyit
HotNetworkQuestions
WhatisRNAVtransitionandwhatisthedifferencebetweenRNAVtransitionandRNAVSTAR
Isitaredflagforacompanytohave"unlimitedpaidtimeoff"?
Twoparallelrelaysfordoublecurrent
IntheU.S.,whyisn'tturnoutandactivismproportionaltoinfluence?
HowcanaverbalreasoningquestionbesolvedwithMathematica?
Haveastronomerstakenintoaccountthefactthatred-shiftedlightfromfar-awaystarsisalsoveryoldwhenstudyingtheexpansionoftheuniverse?
Mathematica13.0simplifiestrigonometricintegralwrong
WhyisMIDIgainbasedonafactorof40?
WhentochangeoilfornewgenerationMazda?
AquestionaboutCubeNuroadRaceFE'shubdynamo?
'Mapping'thevaluesofalisttovariable
AnelegantwaytowritelongequationsinLaTex?
HowManyDaysAfterSkimCoatCanIPaint?
StarWars:R2D2connectedtomainframe
Whyaren'tnegativefrequenciesfoldedinreconstructionofthealiasedsignal?
Googlespreadsheets
QGISreadsblankcellsas"nan"insteadof"NULL"
Tryingtouseacaralternatorforapowersource(notforcar)
Isitdangeroustoconsume30mgofZinc(asZincPicolinate)perday?
Myboss:"Ifeeljealous"
Didmyprofessoractunethicallybypublishingapaperwithafigurefrommythesiswithoutanyacknowledgement?
Pleasehelpmeclarifythissentenceabout'microtones'onGroveMusic
Whatdisadvantagesaretheretoencryptinganentireharddriveorahomedirectory?
Whatisthemostecologicallysustainablewaytohandleragscoveredinchaingrease?
morehotquestions
Questionfeed
SubscribetoRSS
Questionfeed
TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader.
Yourprivacy
Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy.
Acceptallcookies
Customizesettings