Coordinates & Transforms in 2D
文章推薦指數: 80 %
gl_FragCoord.xy / resolution.xy produces a new vec2 by dividing ... above) contains X and Y coordinates that each have been normalized range from 0 to 1.
Coordinates&Transformsin2D
2Coordinates&Transformsin2D
2.1Aslightlyboring,laboriousexample
TheIntroductionmentionedthatallthecodethistutorialdealswith
isfragmentshaders(orpixelshaders)inGLSL.Foroursake,what
thatmeansisthatwearedealingwithshortprogramswhichcreate
images(andeventuallyanimations)byexplicitlygivingthecolorof
everypixelintheimage.
Thismaybeabitdifferentthanwhatyouareusedtoinmoregeneral
programminglanguages.Youarelikelyusedtoprogramsforwhich,at
anygivenpointintime,variableshaveaspecificvalueandthe
programisexecutingsomespecificpartofthecode.
Fragmentshadersdeviatefromthisabit,andrequireabitofa
differentmindset.Thewayweusethemhere,theycanbethoughtof
asprogramswhichrunsimultaneouslyovereverypixelintheimage,
andlikewise,havevariableswhichtakeondifferentvaluesforevery
pixel.(SeeStreamprocessingforalittlemorein-depthinformation
onthis.)
Thebelowcodegivesaverysimpleexampleofthis:
uniformvec2resolution;
voidmain()
{
vec2uv=gl_FragCoord.xy/resolution.xy;
gl_FragColor=vec4(uv.x,uv.y,0.0,1.0);
}
uniformvec2resolution;
voidmain()
{
vec2uv=gl_FragCoord.xy/resolution.xy;
gl_FragColor=vec4(uv.x,uv.y,0.0,1.0);
}
Usecode»
ClickUsecode,andthengototheRendertab.Youshouldseea
gradient-greenatthetopleftcorner,yellowatthetopright,red
atthebottomright,blackatthebottomleft,andcolorsblended
everywherebetweenthose.
ClickbacktotheFragmentShadertab(ignoretheParameterstab
fornow).Thecodemightlookfamiliarifyou'veusedsomethinglike
C,C++,orJava,butwithafewunfamiliarconstructs.vec2and
vec4arevectortypescontaining2elementsand4elements,
respectively(moreonthatlater).Fornow,justtreatavec2asa
structurewithfieldsxandy,andavec4asastructurewith
fieldsr,g,b,anda,allofthemfloating-pointvalues.
gl_FragCoordisoneofthosevariableswhichtakesonadifferent
valueforeverypixelintheimage;the.xyprovidesusavec2of
justtheXandYcoordinatesofeachpixel.resolution,onthe
otherhand,isauniformvariable-ithasthesamevalueoverall
pixels.Inthiscase,it'ssomethingtheenvironmentprovidestotell
usthetotalnumberofpixelsalongXandY.
gl_FragCoord.xy/resolution.xyproducesanewvec2bydividing
gl_FragCoord.xbyresolution.xandgl_FragCoord.yby
resolution.y.Trythecodebelowifyouwanttoverifyyourself
thatit'sthesameassplittingthemout:
uniformvec2resolution;
voidmain()
{
floatu=gl_FragCoord.x/resolution.x;
floatv=gl_FragCoord.y/resolution.y;
gl_FragColor=vec4(u,v,0.0,1.0);
}
uniformvec2resolution;
voidmain()
{
floatu=gl_FragCoord.x/resolution.x;
floatv=gl_FragCoord.y/resolution.y;
gl_FragColor=vec4(u,v,0.0,1.0);
}
Usecode»
Thus,theuvvector(oruandvseparatelyabove)containsXand
Ycoordinatesthateachhavebeennormalizedrangefrom0to1.
Sinceit'sdividingbythetotalresolution,itworksidenticallyat
anyresolution(resizetherenderwindowandsee,orclickthe
lower-righticontomakeitfull-screen).Thisgivesusanormal
(x,y)coordinateplane(orCartesianplane)wherethelower-left
pointis(0,0),movingtotherightincreasestheXcoordinate,and
movingupincreasestheYcoordinate-uptothetop-rightcorner
whichis(1,1).Thisisafairlystandardtransformationtosee
anytimepixellocationsareinvolved.
Finally,gl_FragColoriswhereweassignthepixel'srespective
colorintoavec4bygiving,inorder,itsred,green,blue,and
alphachannelvalues(andweignorealphahere,asitrefersto
transparencyanddoesn'tmakesensetousehere).Eachvalueisfrom
0to1,andvaluesoutsidethatrangeareclippedinsideofit;try
messingwiththevalues(e.g.replacinguwithu*4.0)toverify
this.
Theresult,then,isthatwe'veassignedtheredchannelofeachpixel
toitsXcoordinate,andthegreenchanneltotheYcoordinate.The
bluechannelwasjustleftat0.Thus,attheverylower-left,we'd
expecttoseeblack(redandgreenareboth0becauseXandYare
zero),andmovinguptothetop-right,we'dexpecttoseeyellow(red
andgreenarebothattheirmaximumof1).
2.2Whatcanthisactuallydo?
Youmaybecomplainingthatacoloredgradientisarather
uninterestingthingtodraw,anditis.However,withsomeadditional
math,thismethodofcreatinggraphicsisremarkablyflexible.
Firstoff,though,wemustbeabletocreatesomebasicshapesand
constructstodemonstratethings.We'vealreadyshownhowthe
computationofuvabovecancreatesimplecolorgradients-but
colorgradientsbytheirinherentfuzzinessmakeitdifficulttoshow
anysortofsharpdetailsorwell-definedshapes.
So,considerthebelowcode.Theuv.xlineisn'tespecially
important,butitwillappearagainandagain,anditisthereto
correcttheaspectratiooftheimage.Inourcase,allitmeansis
thatuv.xwillbescaledsothatagivenstepinuv.xisthesame
distanceasinuv.y,andourshapesaren'tsquashed.
uniformvec2resolution;
floatcount=10.0;
voidmain()
{
vec2uv=gl_FragCoord.xy/resolution.xy;
//Correctaspect:
uv.x=uv.x*resolution.x/resolution.y;
vec2uv_mod=mod(uv*count,1.0);
gl_FragColor=vec4(uv_mod.x,uv_mod.y,0,1.0);
}
uniformvec2resolution;
floatcount=10.0;
voidmain()
{
vec2uv=gl_FragCoord.xy/resolution.xy;
//Correctaspect:
uv.x=uv.x*resolution.x/resolution.y;
vec2uv_mod=mod(uv*count,1.0);
gl_FragColor=vec4(uv_mod.x,uv_mod.y,0,1.0);
}
Usecode»
Theimportantlineisthedefinitionofuv_mod:we'vescaledupuv
byacertainamountinbothXandY,andthenusedmodulototurnit
toarepeatingpatternagaininXandY-acrosssomedistance,it
risesfrom0to1,andthengoesbackto0.
Youshouldbeabletoseeasortofgridpatternemerging,andplaying
withthevalueofcount,orchangingthe1.0inmod(...,1.0)to
somethingelse,shouldproducesomeeffectsthatmakesense.However,
ifyoulook,you'llseeit'sstilljustabunchofsmallergradients.
Trylookingjustatuv_mod.xorjustuv_mod.y(i.e.change
gl_FragColorsothatthered,green,andbluechannelareall
uv_mod.x,andthensotheyallareuv_mod.y).
Nowconsider:Howcouldweturnthisintoagridwithsharplines,
insteadofgradients?Trytomakesenseofthebelow,andchange
valueslikethicknesstosomethingelse:
uniformvec2resolution;
floatcount=10.0;
floatthickness=0.05;
voidmain()
{
vec2uv=gl_FragCoord.xy/resolution.xy;
//Correctaspect:
uv.x=uv.x*resolution.x/resolution.y;
vec2uv_mod=mod(uv*count,1.0);
floatx1=uv_mod.x
延伸文章資訊
- 1Convert gl_FragCoord range to fragment range - Game ...
I'm playing with ranges and division based on resolution and fragment size/position, but couldn't...
- 2What is the range of gl_FragCoord - Stack Overflow
- 3Coordinates & Transforms in 2D
gl_FragCoord.xy / resolution.xy produces a new vec2 by dividing ... above) contains X and Y coord...
- 4gl_FragCoord is larger than the window size - Using Cinder
And you could remove all the resize code and passing any uniforms to the shader since everything ...
- 5Cardboard VR Projects for Android - 第 90 頁 - Google 圖書結果
float distance = length(u_LightPos - modelViewVertex); vec3 lightVector ... depth = gl_FragCoord....