gl_FragCoord.z - OpenGL: Advanced Coding - Khronos Forums

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

gl_FragCoord is window-relative (screen) coordinates. .xy is pixel units of the center of the fragment. .z is the depth value that'll be written ... gl_FragCoord.z OpenGL OpenGL:AdvancedCoding Michele_Bosi February21,2008,4:08am #1 Hello, Iwouldliketoknowinwhatspaceisdefinedthevaluegl_FragCoord.z.AsfarasIknowgl_FragCoord.xandyareinscreencoordinates,butthe.zcomponentseemstogivesvaluesalwaysbetweenmoreorless0.9and1.0. HowcanIcomputetheworldoreye.zcoordinatefromgl_FragCoord.z? Thanks! Mic NiCo1 February21,2008,4:22am #2 FromtheGLSLspec: Thefixedfunctionalitycomputeddepthforafragmentmaybeobtainedbyreadinggl_FragCoord.z,... Soatthenearplanethisvalueis0andatthefarplaneit’s1. Youcancalculatetheworld/eyez-coordinatesthesamewaygluUnprojectdoes. N. knackered February21,2008,4:48am #3 andbecausezisnon-lineartofavourthenearertriangles,mostofasceneszwillbeinthatverysmallrange(0.9to1.0). Youcanlineariseitbyencoding(z-near)/(far-near)inthezcolumnofprojectionmatrix,andpre-multiplyzbywinthevertexshader:(z*w)/w=z Michele_Bosi February21,2008,6:53am #4 Thankyouguys,thesourcecodeofgluUnprojectseemsthedefinitivereference Xmas February21,2008,7:21am #5 knackered: andbecausezisnon-lineartofavourthenearertriangles,mostofasceneszwillbeinthatverysmallrange(0.9to1.0). Youcanlineariseitbyencoding(z-near)/(far-near)inthezcolumnofprojectionmatrix,andpre-multiplyzbywinthevertexshader:(z*w)/w=z IsupposewhatyouactuallymeantwasZclip=Wclip*(2*(Zview-near)/(far-near)-1),asOpenGLclipspacerangesfrom-Wclipto+Wclip,or-1to1afterperspectivedivision.It’sonlytheviewporttransformationthatscalesthisto[n,f]asgivenbyglDepthRange(n,f). Yourformulawouldverylikelymovethenearclipplanebehindthecamera(iffar>2*near)whichcanleadtoweirdartifacts. Butthereisanothercatch:Zinterpolationisalwayslinearinscreenspace,i.e.thedifferencebetweenZinneighboringfragmentsisconstant,unlikeperspectivecorrectvaryingswhichareusuallylinearinviewspacebutnon-linearinscreenspace. Becauseofthis,ifyouuseaperspectiveprojectiontheper-vertexZvaluesinscreenspacemustbenon-linear.OtherwisetheinterpolatedZvaluesarewrong,andyoucouldhaveasmallobjectappearinfrontofalargepolygoneventhoughit’sactuallybehind. system February21,2008,7:31am #6 Michele_Bosi: Hello, HowcanIcomputetheworldoreye.zcoordinatefromgl_FragCoord.z? Thanks! Mic JustdothisintheVS varyingfloatEyeVertexZ; EyeVertexZ=(ModelView*gl_Vertex).z; andintheFS youcanuseEyeVertexZ Michele_Bosi February21,2008,11:07am #7 ThankyouV-man,that’ssoeasythatIcannotexpalinhowIcouldn’tthinkaboutitbefore!Willtryitimmediately… oc2k1 February21,2008,4:20pm #8 ItispossibletoconvertaZbuffervaluetothedistancewith: floatZ=gl_ProjectionMatrix[3].z/(gl_FragCoord.z*-2.0+1.0-gl_ProjectionMatrix[2].z); Thisisusefulfordeferredrendering,butifthedistanceisalreadyknowninavertexshader,avaryingisfaster. cass February23,2008,3:39am #9 InOpenGL,thegl_FragCoord.wisthereciprocaloftheclipspacewofthefragment,whichisjusttheeyespacez(orthenegativeofit,anyway). InD3D,frag.wreallyisjusttheclipspacew,andthusdoesn’tneedtobereciprocatedforuseaseyespacez. sqrt_1 April28,2008,6:39pm #10 oc2k1: ItispossibletoconvertaZbuffervaluetothedistancewith: floatZ=gl_ProjectionMatrix[3].z/(gl_FragCoord.z*-2.0+1.0-gl_ProjectionMatrix[2].z); Thisisusefulfordeferredrendering,butifthedistanceisalreadyknowninavertexshader,avaryingisfaster. Sorryforthethreadrevive… Ihaveseenthiscodeinafewplaces-butIcannotseemtofigureoutthemathbehindit.Isthereanarticleortutorialsomewhereonthis? sqrt_1 April28,2008,8:52pm #11 Nevermind,Ifiguredoutthemath. Forreference: UsingtheprojectionmathfromheretogetCandD: http://www.opengl.org/sdk/docs/man/xhtml/glFrustum.xml wecanseethattogetthefinaldepth(F)fromtheviewdepth(V)(matrixexpansionanddividebywandassumingw=1) F=(V*C+D)/-V thereforetogetVfromF… F=-C+(D/-V) F+C=D/-V (F+C)/D=1/-V D/(F+C)=-V D/(-F-C)=V alsoasFneedsscalingfrom0…1to-1…1weneedtoF*2-1whichequals: D/(F*-2+1-C)=V Whichiswhatwasshownabove. DungeonLords November19,2009,4:17am #12 Hiall! Pleasesay,isgl_FragCoord.z/gl_FragCoord.wadistancefromthepointtocamera? Dark_Photon November19,2009,5:25am #13 DungeonLords: Pleasesay,isgl_FragCoord.z/gl_FragCoord.wadistancefromthepointtocamera? Nope.Checkthespec. gl_FragCoordiswindow-relative(screen)coordinates..xyispixelunitsofthecenterofthefragment..zisthedepthvaluethat’llbewrittentothedepthbuffer(0…1)..wis1/clip_space.w,where(forperspectiveprojectionsonly!!)clip_space.wis-eye_space.z,so:gl_FragCoord.w=-1/eye_space.z…forperspectiveprojectionsonly! Fororthographicprojections,gl_FragCoord.wshouldjustbe1(i.e.1/clip_space.w,i.e.1/eye_space.w,whereeye_space.w==1). Forconfirmation,seethelastrowoftheperspectiveandorthographicprojectiontransformsinAppendixFoftheRedBook. Soforaperspectiveprojection,youprobablywant-1/gl_FragCoord.w.Keepinmindthisgivesyoueye-spaceZ,wherevaluesinfrontofthescreenarenegative.Ifyouwantpositive,don’tnegate. Also,yousaidyouwantedadistancefromthepointtothecamera(eyepoint,presumably).Thisisnotwhateye_spaceZis!eye_spaceZisaminimumdistancefromtheXYplaneineye-spacetothepoint,notaradialdistancefromtheeyepoint(0,0,0)tothepoint.ThisisthesameconceptasbetweenEYE_PLANEfogcoordinatemodeandEYE_RADIALfogcoordinatemodes,fromthepre-shaderdays. DungeonLords November19,2009,1:11pm #14 Thankyou!!! Thenwhotisthis:floatOz=gl_FragCoord.z/gl_FragCoord.w; Dark_Photon November20,2009,4:57am #15 DungeonLords: Thenwhotisthis:floatOz=gl_FragCoord.z/gl_FragCoord.w; Foraperspectiveprojection… gl_FragCoord.z/gl_FragCoord.w==(0…1depthvalueoffragment)*(eye_spaceZvalueoffragment) Math-wise,thismakesnosensetome(maybeIneedmorecaffeinethismorning). Justoutofcuriousity,wheredidyougetthisexpression?Googling,Ifindthesetophits: oZone3D.Net:FoginGLSL OgreForums:HowtorendertheZ-buffertoaTexture Gamedev.net:DebuggingthedepthbufferofaFBO Yourwordingsuggeststhefirst(oZone3D).Thisstatestheexpressionis“Thedistancebetweenthecameraandthecurrentpixel(thezaxisvalue)”.Sorry,I’mnotbuyingit. Maybesomeoneelsecanmakesenseofthis. tomriddle October15,2011,6:07am #16 Thankstoall. AndIwanttoaskonequestion. Torenderoutthedepthwithshader,Ithinkthisisthequickestway. [b]smoothinvec4ex_Color; outvec4out_Color; voidmain(void){ floatdepth=gl_FragCoord.z; out_Color=vec4(depth,depth,depth,1.0); }[/b] however,youmentionedthatthisgl_FragCoord.zisnotlinearabove. thisisveryimportanttomesincethisdepthrenderisnotforgraphicratheranacademiccomputervisionmidwareforme. thenmyquestionishowtolinearlizeit? couldyoujustmodifymycodetogivemeananswer? thanks Dark_Photon October15,2011,5:31pm #17 tomriddle: …however,youmentionedthatthisgl_FragCoord.zisnotlinearabove…thenmyquestionishowtolinearlizeit? SeeRe:Urgent:AccessingDepthTextureFBOinGLSL tomriddle October16,2011,12:19am #18 thankyou! AsabeginnermodernGLlearner,Istillhavesomequestions. eventually,IwantthisrendereddepthmapofanobjecttostoreinaOpenCVMatdatatype(asapicture). IsthismeansImustrenderthisobjecttoframebufferthendosomememorycopytoanotherdatatype?Ievendon’tneedittodisplayonthescreen.HowtoachievethisfastandavoidtocostCPUtime?itseemsyourredirectlinkshowedsomethingaboutglBlitzFrameBuffer(),butIdon’tknowwhatfunctionshouldIuseinthiscase. http://www.geeks3d.com/20091216/geexlab-how-to-visualize-the-depth-buffer-in-glsl/ thisexampleseemsinvolvedinthetexturecalculations. I’mnotsurewhethertousetexturethere,canyoujustcalculatethelineardepthfromthegl_FragCoord.z? isthereanymatureexampleIcancodeasareference?thatgeek3dlabhasonlypieceofshaderprogram… I’ddisplay(store)thenearaswhite(1),farasblack(0). sonowImodified glDepthFunc(GL_GEQUAL);//becauseitreversed,thismustbeturned glDepthRange(1.0f,0.0f);//reverse andcleardepthatdisplayfunction glClearDepth(0.0f);//sincereversed thenmyoldfragshaderworksrightexceptthevalueisnotlinear. amIdoingthisright? howtomodifythegeek3dexampledothesame? thankyousomuch. Dark_Photon October17,2011,5:52am #19 tomriddle: eventually,IwantthisrendereddepthmapofanobjecttostoreinaOpenCVMatdatatype(asapicture).…thismeansImustrenderthisobjecttoframebufferthendosomememorycopytoanotherdatatype? Thatwouldbetheeasiestwaytogo.Renderthescene,thenuseglReadPixelstofetchthecolor(ordepth)bufferbacktotheCPU,thendowhatyouwantwithit. glBlitFramebufferisafunctionthatprovidesfortransferringdatafromoneframebuffertoanother.Youinsteadwanttogetyourdatabackfromtheframebuffer(and/oratexture)totheCPU. …thisexampleseemsinvolvedinthetexturecalculations.I’mnotsurewhethertousetexturethere,canyoujustcalculatethelineardepthfromthegl_FragCoord.z? Eveneasier:forperspectiveprojectionsspecifically(seepostsabove),-1/gl_FragCoord.wwillbeeye-spaceZ.Justscaleandshiftthatbynear/fartogetinyourdesired0…1value. Buttoyourpointabouttexture,ifyoudon’tcareaboutwhatthecolorbufferforthesceneis,andyoujustwantthecolorbuffertobealinearizedversionofthedepthbuffer,thenyes,youcanjustskiptheintermediatetexture(andmultipass),anddoallthisinasinglepasswritingdirectlytotheframebufferusingasimplefragmentthatbasicallyjustpipesyourlinearized0…1valuetothecoloroutput(usingthedepthbufferbehind-the-scenesforocclusionasnormal).Soforcomputingyourcolorvalueinthefragshader,somethinglike: gl_FragColor.rrr=(1/gl_FragCoord.w-n)/(f-n);//0=near;1=far gl_FragColor.a=1.0; I’ddisplay(store)thenearaswhite(1),farasblack(0).sonowImodified… Iguessyoucoulddothat.Butevensimplerwouldjustbetotakeyourcomputed0…1valueintheshader,negate,andadd1. tomriddle October19,2011,8:05am #20 [quote=“Dark_Photon”] tomriddle: Iguessyoucoulddothat.Butevensimplerwouldjustbetotakeyourcomputed0…1valueintheshader,negate,andadd1. yes!howdidn’tIcomeoutthis… butIknewglReadPixels()wasdeprecatedandveryslow…



請為這篇文章評分?