That normal map is in tangent-space, but you are treating it as object-space. You need a bitangent and/or tangent vector per-vertex in ...
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
ImplementingNormalMappingusingOpenGL/GLSL
AskQuestion
Asked
7years,2monthsago
Modified
4years,4monthsago
Viewed
14ktimes
2
1
I'mlearningGLSLandtryingtoimplementsomelightingandmappingtricks.I'mworkingwithShaderDesignertool.AftercodingnormalmappingIrecognizedthatmymodelilluminationlooksnotreal.Hereismycodeandsomepictures.Ifitpossibletellmewhatismyproblem.
VertexShader
#defineMAX_LIGHTS1
structLightProps
{
vec3direction[MAX_LIGHTS];
};
attributevec3tangent;
attributevec3bitangent;
varyingLightPropslights;
voidmain()
{
vec3N=normalize(gl_NormalMatrix*gl_Normal);
vec3T=normalize(gl_NormalMatrix*tangent);
vec3B=normalize(gl_NormalMatrix*bitangent);
mat3TBNMatrix=mat3(T,B,N);
vec4vertex=gl_ModelViewMatrix*gl_Vertex;
for(inti=0;i0?lightPos-vertex:lightPos);
lights.direction[i]*=TBNMatrix;
}
gl_TexCoord[0]=gl_MultiTexCoord0;
gl_Position=gl_ModelViewProjectionMatrix*gl_Vertex;
}
FragmentShader
#defineMAX_LIGHTS1
structLightProps
{
vec3direction[MAX_LIGHTS];
};
uniformsampler2DtextureUnit;
uniformsampler2DnormalTextureUnit;
uniformvec4TexColor;
varyingLightPropslights;
voidmain()
{
vec3N=normalize(texture2D(normalTextureUnit,gl_TexCoord[0].st).rgb*2.0-1.0);
vec4color=vec4(0,0,0,0);
for(inti=0;i0)
{
floatatt=1.0;
if(gl_LightSource[i].position.w>0)
{
att=1.0/(gl_LightSource[i].constantAttenuation+
gl_LightSource[i].linearAttenuation*dist+
gl_LightSource[i].quadraticAttenuation*dist*dist);
}
vec4ambient=gl_FrontLightProduct[i].ambient;
vec4diffuse=clamp(att*NdotL*gl_FrontLightProduct[i].diffuse,0,1);
color+=att*(ambient+diffuse);
}
}
vec4textureColor=texture2D(textureUnit,vec2(gl_TexCoord[0]));
gl_FragColor=TexColor*textureColor+gl_FrontLightModelProduct.sceneColor+color;
}
IsetTexColorto(0.3,0.3,0.3,1.0)andtakescreenshots:
Screenshot
ThereislittlebitlightingwhenIrotatecameraandlighttoleft,
butwhenIrotatetorighttheplanegotfullyilluminated.Ithinkthereissomethingwrongbecausewithoutnormalmappingplanelookssamefromtosides.Hereisnormaltexture.Thanksinadvance.
NormalMap:
openglglslfragment-shadervertex-shader
Share
Improvethisquestion
Follow
editedJun20,2020at9:12
CommunityBot
111silverbadge
askedMar13,2015at22:13
haksisthaksist
20922goldbadges55silverbadges1616bronzebadges
8
IthoughtthatthesenormalsforeveryfragmentandIjustneedtotransformthesenormalstoworldspacetomultiplywithlightdirectiontogetdiffuseintensity
– haksist
Mar14,2015at9:03
1
No,thatwouldworkofthenormalswerestoredinobject-space,buttheyarenot.Thosenormalsareintangent-space,andyoucantellthisbecausethepredominantcolorisblue.Youhavetwooptionshere:1.transformallofyourlightingdirectionvectorsintotangent-spaceor2.reversetransformyournormalmapfromtangent-spacebacktoview-space.BothrequiretheconstructionofaTBNmatrix.
– AndonM.Coleman
Mar14,2015at9:41
Okaythanks.Iwilltry
– haksist
Mar14,2015at9:44
Itriedyoursuggestedsolutionandhereistheresulti1300.photobucket.com/albums/ag94/haksist/….Isittrue?
– haksist
Mar14,2015at13:18
Thatlooksaboutright,it'shardtosaywithoutknowingexactlywherethelightislocated.Colorsarewashedout,butthatwasalreadythecaseinyouroriginalscreenshot.
– AndonM.Coleman
Mar14,2015at13:35
|
Show3morecomments
1Answer
1
Sortedby:
Resettodefault
Highestscore(default)
Datemodified(newestfirst)
Datecreated(oldestfirst)
5
Thatnormalmapisintangent-space,butyouaretreatingitasobject-space.
Youneedabitangentand/ortangentvectorper-vertexinadditiontoyournormalinordertoformthebasistoperformtransformationintoandoutoftangent-space.ThismatrixisoftenreferredtoassimplyTBN.
Youhavetwooptionshere:
Transformallofyourlightingdirectionvectorsintotangent-space
Usefulforforward-shading,canbedoneinavertexshader
Transformyournormalmapfromtangent-spacebacktoview-space
Requiredbydeferred-shading,mustbedoneinfragmentshader
BothoptionsrequiretheconstructionofaTBNmatrix,andifyourtangent-spacebasisisorthogonal(modelingsoftwarelikeAssimpcanbeconfiguredtodothisforyou)youcantransposetheTBNmatrixtodoeitherone.
Youareimplementingforward-shading,sosolution#1istheapproachyoushouldtake.
Belowisaroughoverviewofthenecessarystepsforsolution#1.Ordinarilyyouwoulddothecalculationofthelightingdirectionvectorinthevertexshaderforbetterperformance.
VertexShadertoTransformofLightingVectorsintoTangent-space:
attributevec3tangent;
attributevec3bitangent;
varyingvec3N;
varyingvec3V;
varyingvec3E;
varyingvec3T;
varyingvec3B;
voidmain()
{
N=normalize(gl_NormalMatrix*gl_Normal);
V=vec3(gl_ModelViewMatrix*gl_Vertex);
E=normalize(-V);
T=normalize(gl_NormalMatrix*tangent);
B=normalize(gl_NormalMatrix*bitangent);
gl_TexCoord[0]=gl_MultiTexCoord0;
gl_Position=gl_ModelViewProjectionMatrix*gl_Vertex;
}
FragmentShadertoTransformLightingVectorsintoTangent-space:
varyingvec3N;
varyingvec3V;
varyingvec3E;
varyingvec3B;
varyingvec3T;
uniformsampler2DtextureUnit;
uniformsampler2DnormalTextureUnit;
uniformvec4TexColor;
#defineMAX_LIGHTS1
voidmain()
{
//ConstructTangentSpaceBasis
mat3TBN=mat3(T,B,N);
vec3normal=normalize(texture2D(normalTextureUnit,gl_TexCoord[0].st).xyz*2.0-1.0);
vec4color=vec4(0,0,0,0);
for(inti=0;i0?lightPos.xyz-V:lightPos;
L*=TBN;//Transformintotangent-space
floatdist=length(L);
L=normalize(L);
floatNdotL=max(dot(L,N),0.0);
if(NdotL>0)
{
floatatt=1.0;
if(lightPos.w>0)
{
att=1.0/(gl_LightSource[i].constantAttenuation+
gl_LightSource[i].linearAttenuation*dist+
gl_LightSource[i].quadraticAttenuation*dist*dist);
}
vec4diffuse=clamp(att*NdotL*gl_FrontLightProduct[i].diffuse,0,1);
color+=att*gl_FrontLightProduct[i].ambient+diffuse;
}
}
vec4textureColor=texture2D(textureUnit,vec2(gl_TexCoord[0]));
gl_FragColor=TexColor*textureColor+gl_FrontLightModelProduct.sceneColor+color;
}
Thereisatutorialherethatshouldfillinthegapsandexplainhowtocomputetangentandbitangent.
Share
Improvethisanswer
Follow
editedMar14,2015at14:26
answeredMar14,2015at10:04
AndonM.ColemanAndonM.Coleman
41.1k22goldbadges7474silverbadges104104bronzebadges
1
WhatislightPos.wandhowcanIobtainit?
– Nolesh
May20,2019at13: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?Browseotherquestionstaggedopenglglslfragment-shadervertex-shaderoraskyourownquestion.
TheOverflowBlog
Makeyouropen-sourceprojectpublicbeforeyou’reready(Ep.444)
Thescienceofinterviewingdevelopers
FeaturedonMeta
AnnouncingthearrivalofValuedAssociate#1214:Dalmarus
Improvementstositestatusandincidentcommunication
RetiringOurCommunity-SpecificClosureReasonsforServerFaultandSuperUser
Temporarilypausingthesitesatisfactionsurvey
StagingGround:ReviewerMotivation,Scaling,andOpenQuestions
Related
38
VertexshaderattributemappinginGLSL
0
GLSLVertexShadercauseseitherflashingcolorsorallred
6
Normalmappingandphongshadingwithincorrectspecularcomponent
1
OpenGLdeferredrendering:pointlightimplementation
4
Normalmappinggonehorriblywrong
0
OpenGLError1281infragmentshader(onlybyusingblockinterface)
2
OpenGLNormalMapping
HotNetworkQuestions
HowcanItellwhich3rdpartyflashesarecompatiblewithCanon'sSL3missingpinhotshoemount?
Whyisacapacitortogroundalowfrequencypole,insteadofahighfrequencyzero?
Whyweremarijuanarestrictionsimplementedinthe1970smoresuccessfulinSouthKoreathanintheUnitedStates?
'Mapping'thevaluesofalisttovariable
MostcommoncommandtocompileaLaTeXdocument?
HowcanIcreateaLocalewithaspecificscriptcode?
ESTAform:Mentionthecitydistrictinthecontactinformationsection?
Non-committingauthenticatedencryptionschemesvscommittingauthenticatedencryptionschemes
Isitillegaltorideadrunkhorse?
GN:Howtopassaninstancer'slocalizedtexturecolortoitsinstances?
Arethereany/manyUSairports(withinstrumentapproaches)stillwithoutRNAVapproaches?
Whatdoestheidiomaticphrase"erronthesideof"mean?
Doesgravitationreallyexistattheparticlelevel?
DidSauroneverconsiderthattheValarand/orEruIlúvatarmaynotallowhimtoconquerMiddle-earth?
WhywouldIuseatrainerinsteadofridingoutside?
Iwant8bitsforeverycharacter!
Differencebetweenproductsandcoproducts.
Whatdoyoucalladesperateattemptunlikelytosucceed?
HowManyDaysAfterSkimCoatCanIPaint?
Myboss:"Ifeeljealous"
CanImakeGooglePlayshowmeALLreviewsforanapp?
Whyaren'tnegativefrequenciesfoldedinreconstructionofthealiasedsignal?
Movingplayerinsideofmovingspaceship?
CovidTestRequirementforDubaiTransitFromIrelandtoIndonesia
morehotquestions
Questionfeed
SubscribetoRSS
Questionfeed
TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader.
lang-c
Yourprivacy
Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy.
Acceptallcookies
Customizesettings