Stencil buffer - Wikipedia
文章推薦指數: 80 %
A stencil buffer is an extra data buffer, in addition to the color buffer and Z-buffer, found on modern graphics hardware. The buffer is per pixel and works ... Stencilbuffer FromWikipedia,thefreeencyclopedia Jumptonavigation Jumptosearch Thisarticlehasmultipleissues.Pleasehelpimproveitordiscusstheseissuesonthetalkpage.(Learnhowandwhentoremovethesetemplatemessages) ThisarticlemaybeexpandedwithtexttranslatedfromthecorrespondingarticleinSerbian.(April2014)Click[show]forimportanttranslationinstructions. Viewamachine-translatedversionoftheSerbianarticle. MachinetranslationlikeDeepLorGoogleTranslateisausefulstartingpointfortranslations,buttranslatorsmustreviseerrorsasnecessaryandconfirmthatthetranslationisaccurate,ratherthansimplycopy-pastingmachine-translatedtextintotheEnglishWikipedia. Consideraddingatopictothistemplate:therearealready381articlesinthemaincategory,andspecifying|topic=willaidincategorization. Donottranslatetextthatappearsunreliableorlow-quality.Ifpossible,verifythetextwithreferencesprovidedintheforeign-languagearticle. Youmustprovidecopyrightattributionintheeditsummaryaccompanyingyourtranslationbyprovidinganinterlanguagelinktothesourceofyourtranslation.AmodelattributioneditsummaryisContentinthiseditistranslatedfromtheexistingSerbianWikipediaarticleat[[:sr:¿¿¿¿¿¿¿_¿¿¿¿¿]];seeitshistoryforattribution. Youshouldalsoaddthetemplate{{Translated|sr|¿¿¿¿¿¿¿_¿¿¿¿¿}}tothetalkpage. Formoreguidance,seeWikipedia:Translation. Thisarticleneedsadditionalcitationsforverification.Pleasehelpimprovethisarticlebyaddingcitationstoreliablesources.Unsourcedmaterialmaybechallengedandremoved.Findsources: "Stencilbuffer" – news ·newspapers ·books ·scholar ·JSTOR(January2021)(Learnhowandwhentoremovethistemplatemessage) ThisarticlemayrequirecleanuptomeetWikipedia'squalitystandards.Thespecificproblemis:Thearticledoesnotclearlyexplaintheconceptofastencilbuffer.Pleasehelpimprovethisarticleifyoucan.(September2013)(Learnhowandwhentoremovethistemplatemessage) Thisarticle'sfactualaccuracymaybecompromisedduetoout-of-dateinformation.Pleasehelpupdatethisarticletoreflectrecenteventsornewlyavailableinformation.(January2016) (Learnhowandwhentoremovethistemplatemessage) Inthisimage,therearewhiteregionsandblackregions,representing1sand0sinthestencilbufferrespectively.Shapesarethendrawnontopofthestripesbyinvertingthevalueofthestencilbuffer.Ifthebufferatthatpixelhasavalueof0(black),colorthepixelwhite(1)andviceversa. Astencilbufferisanextradatabuffer,inadditiontothecolorbufferandZ-buffer,foundonmoderngraphicshardware.Thebufferisperpixelandworksonintegervalues,usuallywithadepthofonebyteperpixel.TheZ-bufferandstencilbufferoftensharethesameareaintheRAMofthegraphicshardware. Inthesimplestcase,thestencilbufferisusedtolimittheareaofrendering(stenciling).MoreadvancedusageofthestencilbuffermakesuseofthestrongconnectionbetweentheZ-bufferandthestencilbufferintherenderingpipeline.Forexample,stencilvaluescanbeautomaticallyincreased/decreasedforeverypixelthatfailsorpassesthedepthtest. Thesimplecombinationofdepthtestandstencilmodifiersmakeavastnumberofeffectspossible(suchasstencilshadowvolumes,Two-SidedStencil,[1]compositing,decaling,dissolves,fades,swipes,silhouettes,outlinedrawing,orhighlightingofintersectionsbetweencomplexprimitives)thoughtheyoftenrequireseveralrenderingpassesand,therefore,canputaheavyloadonthegraphicshardware. Themosttypicalapplicationisstilltoaddshadowsto3Dapplications.Itisalsousedforplanarreflections. Otherrenderingtechniques,suchasportalrendering,usethestencilbufferinotherways;forexample,itcanbeusedtofindtheareaofthescreenobscuredbyaportalandre-renderthosepixelscorrectly. ThestencilbufferanditsmodifierscanbeaccessedincomputergraphicsbyusingAPIslikeOpenGL,Direct3DorVulkan. Contents 1Architecture 2Stenciltest 3Administration 4Z-fighting 5Shadowvolume 6Reflections 7PlanarShadows 8Spatialshadows 9Otherapplications 10OpenGL 11Seealso 12References Architecture[edit] ThestencilbuffertypicallysharesthesamememoryspaceastheZ-buffer,andtypicallytheratiois24bitsforZ-buffer+8bitsforstencilbufferor,inthepast,15bitsforZ-buffer+1bitforstencilbuffer.Anothervariantis4+24,where28ofthe32bitsareusedand4ignored.StencilandZ-buffersarepartoftheframebuffer,coupledtothecolorbuffer.Thefirstchipavailabletoawidermarketwas3Dlabs'PermediaII,whichsupportedaone-bitstencilbuffer. Thebitsallocatedtothestencilbuffercanbeusedtorepresentnumericalvaluesintherange[0,2n-1],andalsoasaBooleanmatrix(nisthenumberofallocatedbits),eachofwhichmaybeusedtocontroltheparticularpartofthescene.Anycombinationofthesetwowaysofusingtheavailablememoryisalsopossible. Stenciltest[edit] Stenciltestorstencilingisamongtheoperationsonthepixels/fragments(Per-pixeloperations),locatedafterthealphatest,andbeforethedepthtest.Thestenciltestensuresundesiredpixelsdonotreachthedepthtest.Thissavesprocessingtimeforthescene.Similarly,thealphatestcanpreventcorrespondingpixelstoreachthestenciltest. Thetestitselfiscarriedoutoverthestencilbuffertosomevalueinit,oralteredorusedit,andcarriedoutthroughtheso-calledstencilfunctionandstenciloperations.Thestencilfunctionisafunctionbywhichthestencilvalueofacertainpixeliscomparedtoagivenreferencevalue.Ifthiscomparisonislogicallytrue,thestenciltestpasses.Otherwisenot. Indoingso,thepossiblereactioncausedbytheresultofcomparingthreedifferentstate-depthandstencilbuffer: Stenciltestisnotpassed Stenciltestispassedbutnotthedepthtest Bothtestsarepassed(orstenciltestispassed,andthedepthisnotenabled) Foreachofthesecasescanbesetdifferentoperationsovertheexaminedpixel. IntheOpenGLstencilfunctions,thereferencevalueandmask,respectively,definethefunctionglStencilFunc.InDirect3DeachofthesecomponentsisadjustedindividuallyusingmethodsSetRenderStatedevicescurrentlyincontrol.Thismethodexpectstwoparameters,thefirstofwhichisaconditionthatissetandtheotheritsvalue.Intheorderthatwasusedabove,theseconditionsarecalledD3DRS_STENCILFUNC,D3DRS_STENCILREF,andD3DRS_STENCILMASK. StenciloperationsinOpenGLadjustglStencilOpfunctionthatexpectsthreevalues.InDirect3D,again,eachstatesetsaspecificmethodSetRenderState.ThethreestatesthatcanbeassignedtosurgeryarecalledD3DRS_STENCILFAIL,D3DRENDERSTATE_STENCILZFAIL,andD3DRENDERSTATE_STENCILPASS. Administration[edit] Althoughtherangeofstencilbufferapplicationsisratherwide,wecanmentionseveralwell-knownapplications. Onthepictureabovethegroundwiththepictureisjustabovethewhitesurface,whichisnotenoughtopreventtheeffectofdeepstruggle.Incontrast,instensilinga(lowerfigure)thiseffectiscompletelyremoved,evenwhentheyarecoplanarsurfaces. Z-fighting[edit] Mainarticle:Z-fighting DuetothelackofprecisionintheZ-buffer,coplanarpolygonsthatareshort-range,oroverlapping,canbeportrayedasasingleplanewithamultitudeofirregularcross-sections.Thesesectionscanvarydependingonthecamerapositionandotherparametersandarerapidlychanging.ThisiscalledZ-fighting.Thereexistmultiplesolutionstothisissue: -Bringthefarplaneclosertorestrictthescene'sdepth,thusincreasingtheaccuracyoftheZ-buffer,orreducingthedistanceatwhichobjectsarevisibleinthescene. -IncreasethenumberofbitsallocatedtotheZ-buffer,whichispossibleattheexpenseofmemoryforthestencilbuffer. -Movepolygonsfartherapartfromoneanother,whichrestrictsthepossibilitiesfortheartisttocreateanelaboratescene. AlloftheseapproachestotheproblemcanonlyreducethelikelihoodthatthepolygonswillexperienceZ-fighting,anddonotguaranteeadefinitivesolutioninthegeneralcase. Asolutionthatincludesthestencilbufferisbasedontheknowledgeofwhichpolygonshouldbeinfrontoftheothers.Thesilhouetteofthefrontpolygonisdrawnintothestencilbuffer.Afterthat,therestofthescenecanberenderedonlywherethesilhouetteisnegative,andsowillnotclashwiththefrontpolygon. Shadowvolume[edit] Shadowvolumeisatechniqueusedin3Dcomputergraphicstoaddshadowstoarenderedscene.TheywerefirstproposedbyFrankCrowin1977[2]asthegeometrydescribingthe3Dshapeoftheregionoccludedfromalightsource.Ashadowvolumedividesthevirtualworldintwo:areasthatareinshadowandareasthatarenot. Thestencilbufferimplementationofshadowvolumesisgenerallyconsideredamongthemostpracticalgeneral-purposereal-timeshadowingtechniquesforuseonmodern3Dgraphicshardware.IthasbeenpopularisedbythevideogameDoom3,andaparticularvariationofthetechniqueusedinthisgamehasbecomeknownasCarmack'sReverse. Reflections[edit] Reflectionofasceneisdrawnasthesceneitselftransformedandreflectedrelativetothe"mirror"plane,whichrequiresmultiplerenderpassesandusingofstencilbuffertorestrictareaswherethecurrentrenderpassworks: Drawthesceneexcludingmirrorareas–foreachmirrorlocktheZ-bufferandcolorbuffer Rendervisiblepartofthemirror Depthtestissetupsothateachpixelispassedtoenterthemaximumvalueandalwayspasses foreachmirror: Depthtestissetsothatitpassesonlyifthedistanceofapixelislessthanthecurrent(defaultbehavior) Thematrixtransformationischangedtoreflectthescenerelativetothemirrorplane UnlocktheZ-bufferandcolorbuffer Drawthescene,butonlythepartofitthatliesbetweenthemirrorplaneandthecamera.Inotherwords,amirrorplaneisalsoaclippingplane Againlockscolorbuffer,depthtestissetsothatitalwayspasses,resetstencilforthenextmirror. PlanarShadows[edit] Whiledrawingaplaneofshadows,therearetwodominantproblems: Thefirstconcernstheproblemofdeepstruggleincasetheflatgeometryisnotawardedonthepartcoveredwiththeshadowofshadowsandoutside.Seethesectionthatrelatestothis. Anotherproblemrelatestotheextentoftheshadowsoutsidetheareawheretheplanethere. Anotherproblem,whichmayormaynotappear,dependingonthetechnique,thedesignofmorepolygonsinonepartoftheshadow,resultingindarkerandlighterpartsofthesameshade.Allthreeproblemscanbesolvedgeometrically,butbecauseofthepossibilitythathardwareaccelerationisdirectlyused,itisafarmoreelegantimplementationusingthestencilbuffer: 1.Enablelightsandthelights 2.Drawascenewithoutanypolygonthatshouldbeprojectedshadows 3.Drawallpolygonswhichshouldbeprojectedshadows,butwithoutlights.Indoingso,thestencilbuffer,thepixelofeachpolygontobeassignedtoaspecificvalueforthegroundtowhichtheybelong.Thedistancebetweenthesevaluesshouldbeatleasttwo,becauseforeachplanetobeusedtwovaluesfortwostates:intheshadowsandbright. 4.Disableanyglobalillumination(toensurethatthenextstepswillaffectonlyindividualselectedlight)Foreachplane:Foreachlight:1.Editastencilbufferandonlythepixelsthatcarryaspecificvaluefortheselectedlevel.Increasethevalueofallthepixelsthatareprojectedobjectsbetweenthedateofagivenlevelandbright. 2.Allowonlyselectedlightforhimtodrawlevelatwhichpartofherspecificvaluewasnotchanged. Spatialshadows[edit] Stencilbufferimplementationofspatialdrawingshadowsisanyshadowofageometricbodythatitsvolumeincludespartofthescenethatisinit.Ifanypartofthescenebelongstothisvolume,lightisnotilluminatedgiven,otherwiseitis.Thisproblemiscompoundedbytheincreaseinthenumberoflightsbutdoesnotaddressthenumberofareasonwhichtheshadowsfall.Thereareseveralsolutionstotheproblem,butwefollowedthefollowingalgorithm: 1.Drawascenewithoutlight 2.LocktheZ-bufferandcolorbuffer,sothatthetwocannotmakechangesForeachlight1.Usingin-depthinformationaboutthescene(Z-buffer)tofillthestencilbufferonlyonpartsofthescenewherevolumeshadowdoesnotexistorarenotvisiblefromtheexistingbuildings. 2.Unlockbufferforcolor,andadjustthefunctionoftheZ-buffertoallowamendmentsonlywherethedepthvalueequaltoanexisting 3.Drawthesceneilluminatedonlybythislight,butonlyforpartofthescenepassingthestenciltest Eachofthesepassagesimpliesthatacleanstencilbuffercanbeused. Asfortheshadows,thistechniquecanbeusedtoilluminatepartsofspacethatareunderstronglight.Forexample,thebrightnessofthespotlightinadarkroomwithalargepresenceofdustintheaircouldbeseenilluminatingtheappropriatevolumeofspace. Otherapplications[edit] Afurtherexampleistheso-calledsoftshadow,inwhichthetransitionbetweentheilluminatedandshadowedpartofthesceneisoutoffocus.Specifically,onewaytoachievethiseffectstencilbufferistomultiplythevolumeoftheshadow,andthatasthecopies,respectivelyarescaledaccordingtoageometricserieswithalowmagnification,e.g.,.1.04.TheCenterofscalingcanbethecenterofgravityofthepolygonthatrepresentsthetopvolume.Thisinitselfwillgiveaseriesofcompositeshadowsthatgivethedesiredeffect. AnotherimplementationincludesthefieldofvisualizationduringthemodelingtechniquesolidsConstructiveSolidGeometry(CSG),whereinstencilbuffer,togetherwiththeZ-buffer,cansuccessfullysolvetheproblemsoftheBooleanoperationsoftheSOLiD. OpenGL[edit] glEnable(GL_STENCIL_TEST);//bydefaultnotenabled glStencilMask(stencilMask);//allowwritingtostencilbuffer,bydefault(0xFF)nomask. glClearStencil(clearStencilValue);//clearstencilvalue,bydefault=0 glStencilFunc(func,ref,mask);//bydefaultGL_ALWAYS,0,0xFF,alwayspassstenciltest glStencilOp(fail,zfail,zpass);//bydefaultGL_KEEP,GL_KEEP,GL_KEEP,donotchangestencilbuffer glClear(GL_STENCIL_BUFFER_BIT);//clearstencilbuffer,fillwith(clearStencilValue&stencilMask) Test:(ref&mask)func(stencilValue&mask) Dependingonthethreepossibleconditionsofthestencilfunction/depthfunction. 1.StencilTestFunctionfails: IfsayfuncisGL_NEVER,thestenciltestwillalwaysfail. NeitherColor/Z-buffersaremodified.ThestencilbufferismodifiedasperglStencilOpfail. IfsayglStencilOp(GL_REPLACE,GL_KEEP,GL_KEEP)thenGL_REPLACEtakesplaceand stencilValue=(ref&stencilMask)//willbecomeref 2.StencilTestFunctionpasses/DepthTestFunctionfails: IfsayfuncisGL_ALWAYS,thestenciltestwillalwayspass,butdepthtestmayfail. NeitherColor/Z-bufferaremodified.ThestencilbufferismodifiedasperglStencilOpzfail. IfsayglStencilOp(GL_KEEP,GL_INCR,GL_KEEP)thenGL_INCRtakesplaceand stencilValue=(stencilValue+1)//willbecome1 3.StencilFunctionpasses/DepthFunctionpasses: IfsayfuncisGL_ALWAYS,thestenciltestwillalwayspass.Ifthedepthtestalsopasses. BothColor/Z-bufferaremodified.ThestencilbufferismodifiedasperglStencilOpzpass. Ifsay,glStencilOp(GL_KEEP,GL_KEEP,GL_KEEP)thenStencilvaluesarenotchanged,onlyColorandZ-buffersaremodified. TypicallyStencilbufferisinitializedbysettingZ-bufferandcolorbuffermaskstofalse.andthensettingappropriaterefvaluetostencilbufferbyfailingthestenciltesteverytime. //disablecolorandZ-buffers glColorMask(GL_FALSE,GL_FALSE,GL_FALSE,GL_FALSE); glDepthMask(GL_FALSE); glStencilFunc(GL_NEVER,1,0xFF);//neverpassstenciltest glStencilOp(GL_REPLACE,GL_KEEP,GL_KEEP);//replacestencilbuffervaluestoref=1 glStencilMask(0xFF);//stencilbufferfreetowrite glClear(GL_STENCIL_BUFFER_BIT);//firstclearstencilbufferbywritingdefaultstencilvalue(0)toallofstencilbuffer. draw_stencil_shape();//atstencilshapepixellocationsinstencilbufferreplacestencilbuffervaluestoref=1 Nowusetheinitializedstencilbufferandstenciltesttowriteonlyinthelocationswherethestencilvalueis1: //enablecolorandZ-buffers. glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE); glDepthMask(GL_TRUE); //nomoremodifyingofstencilbufferonstencilanddepthpass. glStencilMask(0x00); //canalsobeachievedbyglStencilOp(GL_KEEP,GL_KEEP,GL_KEEP); //stenciltest:onlypassstenciltestatstencilValue==1(Assumingdepthtestwouldpass.) //andwriteactualcontenttodepthandcolorbufferonlyatstencilshapelocations. glStencilFunc(GL_EQUAL,1,0xFF); draw_actual_content(); Seealso[edit] Z-buffering(depthbuffer) Shadowvolume(astencilbuffertechniquecreatingshadows) References[edit] ^"StencilBufferTechniques(Direct3D9)-Win32apps". ^Crow,FranklinC:"ShadowAlgorithmsforComputerGraphics",ComputerGraphics(SIGGRAPH'77Proceedings),vol.11,no.2,242-248. Retrievedfrom"https://en.wikipedia.org/w/index.php?title=Stencil_buffer&oldid=1087338835" Categories:Computergraphics3DrenderingHiddencategories:ArticlestobeexpandedfromApril2014AllarticlestobeexpandedArticlesneedingtranslationfromSerbianWikipediaArticlesneedingadditionalreferencesfromJanuary2021AllarticlesneedingadditionalreferencesArticlesneedingcleanupfromSeptember2013AllpagesneedingcleanupCleanuptaggedarticleswithareasonfieldfromSeptember2013WikipediapagesneedingcleanupfromSeptember2013ArticleswithobsoleteinformationfromJanuary2016AllWikipediaarticlesinneedofupdatingArticleswithmultiplemaintenanceissues Navigationmenu Personaltools NotloggedinTalkContributionsCreateaccountLogin Namespaces ArticleTalk English Views ReadEditViewhistory More Search Navigation MainpageContentsCurrenteventsRandomarticleAboutWikipediaContactusDonate Contribute HelpLearntoeditCommunityportalRecentchangesUploadfile Tools WhatlinkshereRelatedchangesUploadfileSpecialpagesPermanentlinkPageinformationCitethispageWikidataitem Print/export DownloadasPDFPrintableversion Languages DeutschMagyarPolskiСрпски/srpski中文 Editlinks
延伸文章資訊
- 1Stencil testing - LearnOpenGL
A stencil buffer (usually) contains 8 bits per stencil value that amounts to a total of 256 diffe...
- 2模板测试
当片段着色器处理完一个片段之后, 模板测试 (Stencil Test)会开始执行,和深度 ... 模板测试是根据又一个缓冲来进行的,它叫做 模板缓冲 (Stencil Buffer),我们可以...
- 3Stencil Test - OpenGL Wiki
The Stencil Test is a per-sample operation performed after the Fragment Shader. The fragment's st...
- 4Unit Testing - Stencil.js
Stencil makes it easy to unit test components and app utility functions using Jest. Unit tests va...
- 5走进Stencil Buffer 系列0 : 模板缓冲和模板测试是什么?
模板测试(Stencil Test)是现代渲染流水线的一环,其中涉及到的就是模板缓冲(Stencil Buffer),模板缓冲可以用来制作物体的遮罩、轮廓描边、阴影、 ...