How to get coordinate of fragment shaders? gl_FragCoord not ...

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

gl_FragCoord is a built-in input variables, it isn't necessary to declared the input variable gl_FragCoord . The x and y coordinate are ... 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 Howtogetcoordinateoffragmentshaders?gl_FragCoordnotworking AskQuestion Asked 3years,2monthsago Modified 3years,2monthsago Viewed 5ktimes 2 I'mtryingtomakeaMandelbrotsetexplorer,whichwillshadethepixelsonthescreenbasedonitscoordinateinthewindow.I'vedonethisbeforewithoutusingshadersbutitsextremelyslow.Ican'tfigureouthowtogetthepositionofthefragmentsothatIcanusethealgorithmI'vealreadydevelopedtorendertheMandelbrotset. I'musingljgwl3.I'vebeenresearchingalldayonhowtodothis,andIcan'tfindanycomprehensivefindingsonhowtogetthecoordinates.Itseemslikegl_FragCoordshouldworkandthenIcouldusegl_FragCoord.xandgl_FragCoord.ytogetthexandyvalues,whichisallIneedforthealgorithm,butmyscreenalwaysendsupbeingallred.I'mnotpassinganyinfofromthevertexshaderintomyfragmentshaderbecauseIneedtorenderthecolorofeachcoordinateintheMandelbrotbasedonitsxandyvalues,sothevertexpositionsaren'thelpful(Ialsodon'tunderstandhowtogetthose). Hereismyfragmentshader: invec4gl_FragCoord; uniformvec2viewportDimensions; uniformfloatminX; uniformfloatmaxX; uniformfloatminY; uniformfloatmaxY; vec3hsv2rgb(vec3c){ vec4K=vec4(1.0,2.0/3.0,1.0/3.0,3.0); vec3p=abs(fract(c.xxx+K.xyz)*6.0-K.www); returnc.z*mix(K.xxx,clamp(p-K.xxx,0.0,1.0),c.y); } voidmain(){ floatx=gl_FragCoord.x; floaty=gl_FragCoord.y; vec2c=vec2((x*(maxX-minX)/viewportDimensions.x+minX),(y*(maxY-minY)/viewportDimensions.y+minY)); vec2z=c; floatlimit=1000; floatiterations=0; for(inti=0;i4){ break; } iterations+=1.0; } floatitRGB=iterations/limit; vec3hsv=vec3(itRGB,1.0,1.0); vec3rgb=hsv2rgb(hsv); gl_FragColor=vec4(rgb,1); } IthoughtthatIcouldusegl_FragCoordwithoutdeclaringitasinfirstbutitdoesn'tworkeitherway.vec2cisattemptingtomapthecurrentcoordinatetoacoordinateinthecomplexnumbergridbasedoncurrentresolutionofthewindow. Thisisallthat'sinmyvertexshader: voidmain(){ gl_Position=ftransform(); } Andtherelevantbitofmyclientcode: glBegin(GL_POLYGON); glVertex2f(-1f,-1f); glVertex2f(1f,-1f); glVertex2f(1f,1f); glVertex2f(-1f,1f); glEnd(); Thisisrunninginmywindowloop,andjustcreatesthesquarewherethemandelbrotissupposedtorender. ThisistheoutputofmyworkingjavaMandelbrotprogramwhichdoesn'tuseshaders: Thisistheoutputofmyshaderprogram: Fullscreen: Ialsohavenoclueastohowtobeabletoresizethewindowproperlywithouttheblackbars.Iamattemptingtodothiswithvec2cinmycodeaboveasIhavesettheuniformstobethewindowsheightandwidthandamusingthatwhenmappingthecoordinatetothecomplexnumberplane,butasgl_FragCoorddoesn'tseemtoworkthenneithershouldthis.AlinktoacurrentguideonlgjwlscreenresizingbasedonglfwCreateWindowwouldbevastlyappreciated. javaopenglglslshaderlwjgl Share Improvethisquestion Follow editedMar24,2019at9:43 Rabbid76 176k2525goldbadges101101silverbadges145145bronzebadges askedMar24,2019at1:26 uhinuhin 2311silverbadge33bronzebadges 2 1 Whatexactlydoyouexpectctobe?Areyouexpectingittobeavalueontherange[-1,1]?Whataremin/maxX/Y,andhowdotheyrelatetoviewportDimensions? – NicolBolas Mar24,2019at1:35 @NicolBolasCisintendedtobeacoordinateinthecomplexnumbergridthatthemandelbrotliesin.RightnowIhavethisbeingfrom[-2,2]yaxisand[-2,2]xaxis.minX,maxX,minY,maxY,definethedomainandrangeofthecomplexnumberplaneIwanttoview,andtheviewportDimensionsisintendedtobeusedtomapthosenumberstopixelvaluesofthewindow. – uhin Mar24,2019at14:48 Addacomment  |  1Answer 1 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 2 gl_FragCoordisabuilt-ininputvariables,itisn'tnecessarytodeclaredtheinputvariablegl_FragCoord.Thexandycoordinatearewindow(pixel)coordinate. Thelowerleftofgl_FragCoordis(0.5,0.5)andtheupperrightis(W-0.5,H-0.5),whereWandHarethewidthandtheheightoftheviewport. You'vetomapgl_FragCoord.xtotherange[minX,maxX]andgl_FragCoord.ytotherange[minY,maxy]. IrecommendtoustheGLSLfunctionmixforthis. viewportDimensionsisassumedtocontainthewithandtheheightoftheviewportrectangleinwindow(pixel)coordinates. vec2c=mix(vec2(minX,minY),vec2(maxX,maxY),gl_FragCoord.xy/viewportDimensions.xy); Seethe(WebGL)example,whereIappliedthesuggestionstothethefragmentshaderofthequestion. Theboundsareinitializedasfollows minX=-2.5 minY=-2.0 maxX=1.5 maxY=2.0 (functionloadscene(){ varcanvas,gl,vp_size,prog,bufObj={}; functioninitScene(){ canvas=document.getElementById("ogl-canvas"); gl=canvas.getContext("experimental-webgl"); if(!gl) return; progDraw=gl.createProgram(); for(leti=0;i<2;++i){ letsource=document.getElementById(i==0?"draw-shader-vs":"draw-shader-fs").text; letshaderObj=gl.createShader(i==0?gl.VERTEX_SHADER:gl.FRAGMENT_SHADER); gl.shaderSource(shaderObj,source); gl.compileShader(shaderObj); letstatus=gl.getShaderParameter(shaderObj,gl.COMPILE_STATUS); if(!status)alert(gl.getShaderInfoLog(shaderObj)); gl.attachShader(progDraw,shaderObj); gl.linkProgram(progDraw); } status=gl.getProgramParameter(progDraw,gl.LINK_STATUS); if(!status)alert(gl.getProgramInfoLog(progDraw)); progDraw.inPos=gl.getAttribLocation(progDraw,"inPos"); progDraw.minX=gl.getUniformLocation(progDraw,"minX"); progDraw.maxX=gl.getUniformLocation(progDraw,"maxX"); progDraw.minY=gl.getUniformLocation(progDraw,"minY"); progDraw.maxY=gl.getUniformLocation(progDraw,"maxY"); progDraw.viewportDimensions=gl.getUniformLocation(progDraw,"viewportDimensions"); gl.useProgram(progDraw); varpos=[-1,-1,1,-1,1,1,-1,1]; varinx=[0,1,2,0,2,3]; bufObj.pos=gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER,bufObj.pos); gl.bufferData(gl.ARRAY_BUFFER,newFloat32Array(pos),gl.STATIC_DRAW); bufObj.inx=gl.createBuffer(); bufObj.inx.len=inx.length; gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,bufObj.inx); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,newUint16Array(inx),gl.STATIC_DRAW); gl.enableVertexAttribArray(progDraw.inPos); gl.vertexAttribPointer(progDraw.inPos,2,gl.FLOAT,false,0,0); gl.enable(gl.DEPTH_TEST); gl.clearColor(0.0,0.0,0.0,1.0); window.onresize=resize; resize(); requestAnimationFrame(render); } functionresize(){ //vp_size=[gl.drawingBufferWidth,gl.drawingBufferHeight]; vp_size=[window.innerWidth,window.innerHeight]; //vp_size=[256,256] canvas.width=vp_size[0]; canvas.height=vp_size[1]; } functionrender(deltaMS){ gl.viewport(0,0,canvas.width,canvas.height); gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT); gl.uniform1f(progDraw.minX,-2.5); gl.uniform1f(progDraw.minY,-2.0); gl.uniform1f(progDraw.maxX,1.5); gl.uniform1f(progDraw.maxY,2.0); gl.uniform2f(progDraw.viewportDimensions,canvas.width,canvas.height); gl.drawElements(gl.TRIANGLES,bufObj.inx.len,gl.UNSIGNED_SHORT,0); requestAnimationFrame(render); } initScene(); })(); html,body{margin:0;overflow:hidden;} precisionmediumpfloat; attributevec2inPos; voidmain() { gl_Position=vec4(inPos.xy,0.0,1.0); } precisionmediumpfloat; uniformvec2viewportDimensions; uniformfloatminX; uniformfloatmaxX; uniformfloatminY; uniformfloatmaxY; vec3hsv2rgb(vec3c){ vec4K=vec4(1.0,2.0/3.0,1.0/3.0,3.0); vec3p=abs(fract(c.xxx+K.xyz)*6.0-K.www); returnc.z*mix(K.xxx,clamp(p-K.xxx,0.0,1.0),c.y); } voidmain() { floatx=gl_FragCoord.x; floaty=gl_FragCoord.y; vec2c=mix(vec2(minX,minY),vec2(maxX,maxY),gl_FragCoord.xy/viewportDimensions.xy); vec2z=c; floatlimit=64.0; floatiterations=0.0; for(inti=0;i<64;i++){ floatt=2.0*z.x*z.y+c.y; z.x=z.x*z.x-z.y*z.y+c.x; z.y=t; if(z.x*z.x+z.y*z.y>4.0){ break; } iterations+=1.0; } floatitRGB=iterations/limit; vec3hsv=vec3(itRGB,1.0,1.0); vec3rgb=hsv2rgb(hsv); gl_FragColor=vec4(rgb,1); } Share Improvethisanswer Follow editedMar24,2019at15:09 answeredMar24,2019at9:27 Rabbid76Rabbid76 176k2525goldbadges101101silverbadges145145bronzebadges 10 2 mixisavector-wisefunction,soyoushouldusemix(vec2(minX,minY),vec2(maxX,maxY),gl_FragCoord.xy/viewportDimensions). – NicolBolas Mar24,2019at14:51 I'mnotsureifusingmixisreallythebestoption.Thetransformationinquestioncanbereducedtoasimplemultiply-add,andpre-calcultaingthe2coefficientsandsendingthosetotheshaderappearsmoreefficienttome – derhass Mar24,2019at14:54 1 @uhin:"IfIputgl_FragColor=vec4(gl_FragCoord.x,gl_FragCoord.y,1,1);itjustdisplaysawhitescreen,meaningthattherewouldbea1forboththexandy,foreveryfragment?Why?Thatiswhatisconfusingme."Butthatpointisexplicitelyaddressedintheanswer.Itdoesntmeanitis1,itmeansitis>=1,andthatishowitisupposedto. – derhass Mar24,2019at15:05 1 @derhassOH!Ithoughtthatthevaluesofgl_FragCoordwerefrom[0,1].Thanks! – uhin Mar24,2019at15:09 1 @Rabbid76myproblemwasthatIwassettingmyuniformsafterendingtheshaderprogram.Ifixeditnow.Thanks! – uhin Mar24,2019at15:16  |  Show5morecomments 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?Browseotherquestionstaggedjavaopenglglslshaderlwjgloraskyourownquestion. TheOverflowBlog Makeyouropen-sourceprojectpublicbeforeyou’reready(Ep.444) Thescienceofinterviewingdevelopers FeaturedonMeta AnnouncingthearrivalofValuedAssociate#1214:Dalmarus Improvementstositestatusandincidentcommunication RetiringOurCommunity-SpecificClosureReasonsforServerFaultandSuperUser Temporarilypausingthesitesatisfactionsurvey StagingGround:ReviewerMotivation,Scaling,andOpenQuestions Related 2256 HowtogetanenumvaluefromastringvalueinJava 1265 HowtogetthecurrentworkingdirectoryinJava? 2 Paletteswapusingfragmentshaders 2 Texturecoordinatespassedtofragmentshaderareall0 1 CreatingatrianglewithOpenGL&GLSL 7 GLSLfloat/vec3/vec4arraymaxsize=GL_MAX_VERTEX_UNIFORM_VECTORS? 6 OpenGLandGLSLmemoryalignmentforuniformsandvaryings 1 Can'tgetglVertexAttribPointertorendercolourfromshaders HotNetworkQuestions Audiosplitterwithoutbufferpossible? Waystomakeanalienatmospherebreathable,butuncomfortable? ESTAform:Mentionthecitydistrictinthecontactinformationsection? Howcanaprivatekeybeimportedtoadescriptorwallet? Isthisaninsectnest? Whyisacapacitortogroundalowfrequencypole,insteadofahighfrequencyzero? Mathematica13.0simplifiestrigonometricintegralwrong Howdoyougagafish-personwithouttape? Iworkfromhomeasasoftwareengineerandmyjobishappywithmyperformance.ButI'mputtinginlittleeffort.AmIabadpersonoremployee? GAMmodelwarningmessage:stepfailureinthetaestimation ProbleminNewton'sPrincipiamentionedbyV.I.Arnol'd Googlespreadsheets Canarunascendinglistbemade? Tryingtouseacaralternatorforapowersource(notforcar) AquestionaboutCubeNuroadRaceFE'shubdynamo? Colourina5by5grid,withevolutionrules,sothatthestartinggridisthesameastheoutputgrid WhatdoesGandalftheWhitemeanbyhisstrangespeechaboutBoromir? Howdoyouemptyanonlinevirtualdebitcard? DifferentwaystocitereferencesinMathematics Isitdangeroustoconsume30mgofZinc(asZincPicolinate)perday? WhatisRNAVtransitionandwhatisthedifferencebetweenRNAVtransitionandRNAVSTAR Differencebetweenproductsandcoproducts. WhatdoesChaosTaxmean? Whataresomealternativestotannininplantbark? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. default Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?