GLSL gl_FragCoord.z Calculation and Setting gl_FragDepth
文章推薦指數: 80 %
I had tried using gl_DepthRange and in the example, but the values, preliminarily, didn't seem to be correct on my card. – imallett. Apr 22, ... 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 GLSLgl_FragCoord.zCalculationandSettinggl_FragDepth AskQuestion Asked 10years,1monthago Modified 7years,1monthago Viewed 16ktimes 25 17 So,I'vegotanimposter(therealgeometryisacube,possiblyclipped,andtheimpostergeometryisaMengersponge)andIneedtocalculateitsdepth. Icancalculatetheamounttooffsetinworldspacefairlyeasily.Unfortunately,I'vespenthoursfailingtoperturbthedepthwithit. TheonlycorrectresultsIcangetarewhenIgo: gl_FragDepth=gl_FragCoord.z Basically,Ineedtoknowhowgl_FragCoord.ziscalculatedsothatIcan: Taketheinversetransformationfromgl_FragCoord.ztoeyespace Addthedepthperturbation Transformthisperturbeddepthbackintothesamespaceastheoriginalgl_FragCoord.z. Iapologizeifthisseemslikeaduplicatequestion;there'sanumberofotherpostsherethataddresssimilarthings.However,afterimplementingallofthem,noneworkcorrectly.Ratherthantryingtopickonetogethelpwith,atthispoint,I'maskingforcompletecodethatdoesit.Itshouldjustbeafewlines. openglglslshader Share Improvethisquestion Follow editedApr23,2012at15:20 genpfault 49.3k1010goldbadges7979silverbadges128128bronzebadges askedApr22,2012at3:21 imallettimallett 13.9k99goldbadges5353silverbadges121121bronzebadges 6 Haveyouwrittenavertexshaderaswell?oronlyafragmentshader? – MichaelSlade Apr22,2012at4:08 2 Iwon'tgiveyoucodeongeneralprinciple,butIcangiveyouthislinktotheOpenGLWiki.Aswellasthislinktoatutorialofmineonimpostorsanddepththatshowshowtodothisaswell.Transformingthedepthbackistrivial. – NicolBolas Apr22,2012at5:08 Michael:yes,butit'sjustapassthroughshader.Asithappens,thecalculationsaredoneinworldspace,soIcancalculateeyespaceinthefragmentprogram.Nicol,Ihadalreadyseenthatpage.Iimplementitas:vec4clip_pos=gl_ProjectionMatrix*vec4(eye_pos,1.0);floatndc_depth=clip_pos.z/clip_pos.w;gl_FragDepth=(((clip_far-clip_near)*ndc_depth)+clip_near+clip_far)/2.0;Unfortunately,thedepthappearstofalloutsidethedepthrange,eventhoughthere'snooffsetting.Thanks, – imallett Apr22,2012at5:28 1 @IanMallett:Whatareclip_nearandclip_far?Becausethosesoundsuspiciouslylikethenearandfarclipdistancesusedtocomputetheperspectiveprojectionmatrix. – NicolBolas Apr22,2012at5:58 Theyare.Shouldn'ttheybe?Ihadtriedusinggl_DepthRangeandintheexample,butthevalues,preliminarily,didn'tseemtobecorrectonmycard. – imallett Apr22,2012at7:43 | Show1morecomment 2Answers 2 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 36 Forfuturereference,thekeycodeis: floatfar=gl_DepthRange.far;floatnear=gl_DepthRange.near; vec4eye_space_pos=gl_ModelViewMatrix*/*something*/ vec4clip_space_pos=gl_ProjectionMatrix*eye_space_pos; floatndc_depth=clip_space_pos.z/clip_space_pos.w; floatdepth=(((far-near)*ndc_depth)+near+far)/2.0; gl_FragDepth=depth; Share Improvethisanswer Follow answeredOct15,2012at21:11 imallettimallett 13.9k99goldbadges5353silverbadges121121bronzebadges 7 Shouldn't"gl_DepthRange.far"and"gl_DepthRange.near;"bereplacedwiththenearandfarrangesoftheprojectionmatrixinsteadoftheclipplanevalues? – Tara Sep21,2015at1:00 Notatall.gl_DepthRangeisnotthesamethingasthenearandfarplanevaluesusedtocalculatetheprojectionmatrix.Imightbemisunderstandingyourpointthough. – Tara Sep21,2015at1:38 @DudesonTheclipplanessimplydetermine,viatheprojectionmatrix,whichvalueswillmapoutsidetheNDC(andthereforebeclippedbythehardware).We'recompletelydonewiththemaftertheprojectionmatrixisspecified.Meanwhile,gl_DepthRange.(ne|f)aristherangeofthedepthbuffer,andisneededtoconvertfromNDCtothedepthbuffer.HTH – imallett Sep21,2015at2:36 Exactly.I'msorry,itseemsIdidn'trealizeyou'reconvertingfromNDCtothedepthbuffer(inwhichcaseusually(ndc.z+1.0)*0.5issufficient).Ithoughtyouwereconvertingfromlineardepthvaluestothedepthbuffer. – Tara Sep21,2015at3:01 @DudesonNotethatfortheusualvaluesofgl_DepthRange,thepenultimatelineinthesourceisexactlythis:) – imallett Sep21,2015at3:05 | Show2morecomments 7 Foranotherfuturereference,thisisthesameformulaasgivenbyimallett,whichwasworkingformeinanOpenGL4.0application: vec4v_clip_coord=modelview_projection*vec4(v_position,1.0); floatf_ndc_depth=v_clip_coord.z/v_clip_coord.w; gl_FragDepth=(1.0-0.0)*0.5*f_ndc_depth+(1.0+0.0)*0.5; Here,modelview_projectionis4x4modelview-projectionmatrixandv_positionisobject-spacepositionofthepixelbeingrendered(inmycasecalculatedbyaraymarcher). Theequationcomesfromthewindowcoordinatessectionofthismanual.Notethatinmycode,nearis0.0andfaris1.0,whicharethedefaultvaluesofgl_DepthRange.Notethatgl_DepthRangeisnotthesamethingasthenear/fardistanceintheformulaforperspectiveprojectionmatrix!Theonlytrickisusingthe0.0and1.0(orgl_DepthRangeincaseyouactuallyneedtochangeit),I'vebeenstrugglingforanhourwiththeotherdepthrange-butthatisalready"baked"inmy(perspective)projectionmatrix. Notethatthisway,theequationreallycontainsjustasinglemultiplybyaconstant((far-near)/2)andasingleadditionofanotherconstant((far+near)/2).Comparethattomultiply,addanddivide(possiblyconvertedtoamultiplybyanoptimizingcompiler)thatisrequiredinthecodeofimallett. Share Improvethisanswer Follow answeredApr1,2015at17:40 theswinetheswine 10.3k77goldbadges5555silverbadges100100bronzebadges 1 Thanksfortheusefulinfo.Notethatyourformula(1.0-0.0)*0.5*f_ndc_depth+(1.0+0.0)*0.5,whenyoufactortheterms,becomesthesameas(f_ndc_depth+1.0)*0.5thatotherpeopleweresharingintheothercommentsinhere. – R.Navega Feb25,2021at4:53 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?Browseotherquestionstaggedopenglglslshaderoraskyourownquestion. TheOverflowBlog Makeyouropen-sourceprojectpublicbeforeyou’reready(Ep.444) Thescienceofinterviewingdevelopers FeaturedonMeta AnnouncingthearrivalofValuedAssociate#1214:Dalmarus Improvementstositestatusandincidentcommunication RetiringOurCommunity-SpecificClosureReasonsforServerFaultandSuperUser Temporarilypausingthesitesatisfactionsurvey StagingGround:ReviewerMotivation,Scaling,andOpenQuestions Linked 14 HowtorenderdepthlinearlyinmodernOpenGLwithgl_FragCoord.zinfragmentshader? 5 DepthoffsetinOpenGL 2 Prioritizingselectedlineobjectsoverothersbymanipulatinggl_FragDepth 0 OpenGLESwritedepthdatatocolor Related 222 HowtodebugaGLSLshader? 214 Random/noisefunctionsforGLSL 1 SettingneighborfragmentcolorviaGLSL 79 CreatingaGLSLArraysofUniforms? 109 What'stheoriginofthisGLSLrand()one-liner? 8 Heathaze/distortioneffectinOpenGL(GLSL)andhowitshouldbeachieved 9 World-spacepositionfromlogarithmicdepthbuffer 0 blinn_phongilluminationonacube,DiffuseandSpecularlightarenotworkingproperly 1 Renderingusingnormalmapscausesrotation-dependentlighting HotNetworkQuestions WhyisMIDIgainbasedonafactorof40? StarWars:R2D2connectedtomainframe SignalprocessinginPythonvsC++(Bandpassfilter) Whatis"aerospacegrade"? canaPhDcandidatebeaguesteditorinapeerreviewedjournal? Pleasehelpmeclarifythissentenceabout'microtones'onGroveMusic Isthissinkfaucetremovable? Isitillegaltorideadrunkhorse? Isthereanypracticaluseforafunctionthatdoesnothing? ESTAform:Mentionthecitydistrictinthecontactinformationsection? USAssistantProfsalarynegotiationwithcounterofferbeforegoingupfortenure IsitOKtousemixedDNSservers? WhatisRNAVtransitionandwhatisthedifferencebetweenRNAVtransitionandRNAVSTAR Doesgravitationreallyexistattheparticlelevel? HowdoesHebrews11:27sayMoseswasnotafraid? CanWgatebewrittenonlyusingH,T? Astronautisdeludedintotakinghishelmetoff(anddies) UnabletomountaLinuxRAIDarray ArederivativesfrominterpolatingfunctionscreatedbyNDSolveusingderivativesofthesplineornumericsfromsolvingDE Isitdangeroustoconsume30mgofZinc(asZincPicolinate)perday? Can'tmultiplywidthin\newcommandforincludegraphics Iwant8bitsforeverycharacter! DifferencebetweenfirewallandACL Twoparallelrelaysfordoublecurrent morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-c Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings
延伸文章資訊
- 1Deceit in Depth
Example 13.4. Depth Correct Fragment Shader ... We write the final depth to a built-in output var...
- 2computing gl_FragDepth - Game Development Stack Exchange
- 3Fragment Shader/Defined Outputs - OpenGL Wiki
gl_FragDepth: This output is the fragment's depth. ... The sample mask output here will be logica...
- 4Playing with gl_FragDepth - OpenGL - Khronos Forums
I continued with my last example. I have a lots of quads that they are always looking to the came...
- 5高级GLSL
如果着色器中没有像 gl_FragDepth 变量写入,它就会自动采用 gl_FragCoord.z 的值。 我们自己设置深度值有一个显著缺点,因为只要我们在片段着色器中对 gl_FragDep...