您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 企业文化 > cocos2dx文献翻译
[Cocos3.8Tutorial]RenderTexture+BlurThistutorialwillhelpyoutounderstandhowyoucanuseshadersandrendertexturesincocos2d-x3.0andwillgiveyousomeinsightsintheunderlyingmath.InoneofmyprojectsIfacedanecessitytomakeablurredversionofsomebackgroundlandscape,whichcompositiondependsonthescreensize,thatiscloudsarestickedtothetopofthescreenandgroundisstickedtothebottom,soit'snotanoptiontojustputablurredimageintheresourcefolder.Thelandscapemustbecomposed,drawninaRenderTexture,thendrawnagainwithblurringshader,savedtodiskandusedinconsequentlaunches.Theimagecanbeprettybigandtheblurradiuscanbeprettybigaswell,soweneedsomethingfast.Thistutorialcanbedividedintofollowingsteps:1.Divingintomathandcalculatinggaussianweights2.Creatingblurshader3.Renderingtextureandsavingittofile4.UsingTextureBlurinasampleprogramLet'sstart.Toblurapixelwejustneedtocalculateaweightedsumofthesurroundingpixels,whereweightsthemselvessumupto1.Anotherpropertythatwouldbenicetohaveisthatcentralweightsmustbeheavierthanthesideones.WhyGaussianfunctionisusuallypickedformakingblureffect?Becauseithasthreenicefeatures:1.It'sintegralequals12.It'smaximumvalueisinthesymmetrypoint3.Ithasthefollowingfeature:Tow-dimensionalGaussianfunctioncanbesplitintoaproductoftwoone-dimensionalfunctions.Whatitwillgiveus?Tocalculatethecoloroftheblurredpixelwithcoordinate(i,j)inastraightforwardmannerweneedtosumupallthepixelsinrange(i-R,i+R)x(j-R,j+R),whereRisablurradius.ThisresultsinanestedloopandnestedloopmeansO(n*n)complexityandwereallydonotwantsuchathinginashader.Keepinginmindthe3rdfeatureoftheGaussiandistributionwecansplitthenestedloopintwoconsequentloops.Atfirstwewilldoahorizontalblurandthen-vertical,thushavingO(n)complexity.Themagicisthatthefinalresultofsuchsimplificationwon'tdifferfromtheoneobtainedwithslownestedloop.Let'scalculateanintegralofGaussianfunctionwithsigma=1/3andmu=0fromx=-1to1.Thatwillgiveus0.9973,almost1.Let'snowuseacommontechniquefornumericalintegration:wearegoingtodraw2*R-1pointsfrom-1to1,calculateGaussianfunctioninthem,multipleobtainedvaluesby1/(R-1)andsumeverythingup.Thenicefactisthatthatsumwillequaltosomethingnear1andtheprecisionwillgrowtogetherwithR.Theonlyproblemlefttosolveisthatwewantcoefficientstosumupexactlyto1,otherwisetheblurredimagewillhavesomeproblemswithopacity(totallyopaqueimageswillbecomealittlebittransparent).Thiscanbeguaranteedbycalculatingthecentralcoefficientas1-sumofalltheothers.So,tothecodes.Theideaistopre-calculategaussiancoefficientsonstart,passthemtotheshaderanddonomathotherthanmultiplicationinside.Besidesthestandardv_fragmentColorandv_texCoordwehavefouradditionalparameters:1.pixelSize-inGLSLtherearenopixels,onlydecimals,forinstance0denotestheleftorthelowerborderofthetextureand1-therightortheupperborder.Thismeanswehavetoknowthedecimalsteptomaketothenextpixel.2.radius-ourblurradius3.weights-arrayofprecalculatedgaussianweights4.direction-2dvectordenotinghorizontalorverticalblurTheworduniforminfrontofthesevaluesmeanthattheyarenotgoingtochangeduringtherun.Therestoftheshaderbodyisprettystraightforward:takeapixel,accumulatesurroundingpixelswithsomecoefficientsandvoila.Ihadtohardcodemaximumarraysizetobe64asIfoundnowaytouseadynamicarrayasauniforminshader.Everythingisprettymuchself-explanatoryhere.WecreateanewGLProgramusingthestandardvertexshaderandourblurshader,passadditionalparametersusingGLProgramStateclassandeverythingisreadytogo.OnemayencounteranotherwayofassigningtheshaderbodytoGLchar*variable,somethinglikethis:IpreferusingString::createWithContentsOfFilebecauseitfreesyoufromnecessitytowrite\n\attheendofeverylinewhichisquiteannoying.Theonlythinglefttodoisactuallyblurringatexture.Ourstrategyherewillbeasfollows:1.Createaspritefromthetexturepassedasaparameter2.DrawittoaRenderTexturewithhorizontalblurshader3.Createaspritefromresultingtexture4.DrawthisspritetoaRendertexturewithverticalshader5.Saveimagetofile6.Waituntilsavingisdone,cleanupandnotifythecallerNow,tothemainmethod.Weneedthefollowingthingstobepassedasarguments:texturetoblur,blurradius,resultingpicturefilename,acallbacktoinvokewheneverythingisdoneandstepasanoptionalparameter,we'llgettoitinamatterofseconds.HereIusedalambdavariable-oneofthecoolestfeaturesofC++11.RecitationofthestepX,stepYetc.meansthatwewantthesevariablestobecapturedbytheirvalue.Thatmeansthatwhenweusethesevariablesinlambda,weactuallyusetheirlocalcopies.Anotheroptionistocapturevariablesbereference,butinourcasethesevariableswillbedestroyedatthemomentwhenthecallbackwillbeexecuted,thuscausingundefinedbehavior.InCocos2d-xsourcesyoucanfind[&]or[=]designations.Theymean,correspondingly,thatallvariablesshouldbecapturedbyreferenceorbyvalue.SomeoftheC++safetystandardsrecommendtobeasexplicitaspossiblewhendeclaringlambdacapturingmethod,whichmaybedifferentforeveryvariable.Finally,letsgetTextureBlurtowork!Somesampledrawinginpaint,alittlebitofadditionalcodetoHelloWorldsceneandherewego.That'showinitialpaysagelookslike:Andhereisit'sblurredversion:[Cocos3.8Tutorial]渲染纹理和虚化这个教程将帮助你理解如何使用cocos2d-x3.0的着色器和渲染纹理并且给你一些关于数学基础的独特见解。在我的其中一项项目中我需要制造一个根据屏幕大小
本文标题:cocos2dx文献翻译
链接地址:https://www.777doc.com/doc-3149136 .html