first-pass-linearize-crt-gamma-bob-fields.vs 239 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704
  1. #version 150
  2. in vec4 position;
  3. in vec2 texCoord;
  4. out Vertex {
  5. vec2 vTexCoord;
  6. vec2 uv_step;
  7. float interlaced;
  8. };
  9. uniform vec4 targetSize;
  10. uniform vec4 sourceSize[];
  11. // USER SETTINGS BLOCK //
  12. #define crt_gamma 2.500000
  13. #define lcd_gamma 2.200000
  14. #define levels_contrast 1.0
  15. #define halation_weight 0.0
  16. #define diffusion_weight 0.075
  17. #define bloom_underestimate_levels 0.8
  18. #define bloom_excess 0.000000
  19. #define beam_min_sigma 0.020000
  20. #define beam_max_sigma 0.300000
  21. #define beam_spot_power 0.330000
  22. #define beam_min_shape 2.000000
  23. #define beam_max_shape 4.000000
  24. #define beam_shape_power 0.250000
  25. #define beam_horiz_filter 0.000000
  26. #define beam_horiz_sigma 0.35
  27. #define beam_horiz_linear_rgb_weight 1.000000
  28. #define convergence_offset_x_r -0.000000
  29. #define convergence_offset_x_g 0.000000
  30. #define convergence_offset_x_b 0.000000
  31. #define convergence_offset_y_r 0.000000
  32. #define convergence_offset_y_g -0.000000
  33. #define convergence_offset_y_b 0.000000
  34. #define mask_type 1.000000
  35. #define mask_sample_mode_desired 0.000000
  36. #define mask_specify_num_triads 0.000000
  37. #define mask_triad_size_desired 3.000000
  38. #define mask_num_triads_desired 480.000000
  39. #define aa_subpixel_r_offset_x_runtime -0.0
  40. #define aa_subpixel_r_offset_y_runtime 0.000000
  41. #define aa_cubic_c 0.500000
  42. #define aa_gauss_sigma 0.500000
  43. #define geom_mode_runtime 0.000000
  44. #define geom_radius 2.000000
  45. #define geom_view_dist 2.000000
  46. #define geom_tilt_angle_x 0.000000
  47. #define geom_tilt_angle_y 0.000000
  48. #define geom_aspect_ratio_x 432.000000
  49. #define geom_aspect_ratio_y 329.000000
  50. #define geom_overscan_x 1.000000
  51. #define geom_overscan_y 1.000000
  52. #define border_size 0.015
  53. #define border_darkness 2.0
  54. #define border_compress 2.500000
  55. #define interlace_bff 0.000000
  56. #define interlace_1080i 0.000000
  57. // END USER SETTINGS BLOCK //
  58. // compatibility macros for transparently converting HLSLisms into GLSLisms
  59. #define mul(a,b) (b*a)
  60. #define lerp(a,b,c) mix(a,b,c)
  61. #define saturate(c) clamp(c, 0.0, 1.0)
  62. #define frac(x) (fract(x))
  63. #define float2 vec2
  64. #define float3 vec3
  65. #define float4 vec4
  66. #define bool2 bvec2
  67. #define bool3 bvec3
  68. #define bool4 bvec4
  69. #define float2x2 mat2x2
  70. #define float3x3 mat3x3
  71. #define float4x4 mat4x4
  72. #define float4x3 mat4x3
  73. #define float2x4 mat2x4
  74. #define IN params
  75. #define texture_size sourceSize[0].xy
  76. #define video_size sourceSize[0].xy
  77. #define output_size targetSize.xy
  78. #define frame_count phase
  79. #define static
  80. #define inline
  81. #define const
  82. #define fmod(x,y) mod(x,y)
  83. #define ddx(c) dFdx(c)
  84. #define ddy(c) dFdy(c)
  85. #define atan2(x,y) atan(y,x)
  86. #define rsqrt(c) inversesqrt(c)
  87. #define input_texture source[0]
  88. #ifdef GL_ES
  89. #ifdef GL_FRAGMENT_PRECISION_HIGH
  90. precision highp float;
  91. #else
  92. precision mediump float;
  93. #endif
  94. #define COMPAT_PRECISION mediump
  95. #else
  96. #define COMPAT_PRECISION
  97. #endif
  98. #if __VERSION__ >= 130
  99. #define COMPAT_VARYING in
  100. #define COMPAT_TEXTURE texture
  101. #else
  102. #define COMPAT_VARYING varying
  103. #define FragColor gl_FragColor
  104. #define COMPAT_TEXTURE texture2D
  105. #endif
  106. ///////////////////////////// SETTINGS MANAGEMENT ////////////////////////////
  107. // PASS SETTINGS:
  108. // gamma-management.h needs to know what kind of pipeline we're using and
  109. // what pass this is in that pipeline. This will become obsolete if/when we
  110. // can #define things like this in the .cgp preset file.
  111. #define FIRST_PASS
  112. #define SIMULATE_CRT_ON_LCD
  113. ////////////////////////////////// INCLUDES //////////////////////////////////
  114. //#include "bind-shader-h"
  115. ///////////////////////////// BEGIN BIND-SHADER-PARAMS ////////////////////////////
  116. #ifndef BIND_SHADER_PARAMS_H
  117. #define BIND_SHADER_PARAMS_H
  118. ///////////////////////////// GPL LICENSE NOTICE /////////////////////////////
  119. // crt-royale: A full-featured CRT shader, with cheese.
  120. // Copyright (C) 2014 TroggleMonkey <trogglemonkey@gmx.com>
  121. //
  122. // This program is free software; you can redistribute it and/or modify it
  123. // under the terms of the GNU General Public License as published by the Free
  124. // Software Foundation; either version 2 of the License, or any later version.
  125. //
  126. // This program is distributed in the hope that it will be useful, but WITHOUT
  127. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  128. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  129. // more details.
  130. //
  131. // You should have received a copy of the GNU General Public License along with
  132. // this program; if not, write to the Free Software Foundation, Inc., 59 Temple
  133. // Place, Suite 330, Boston, MA 02111-1307 USA
  134. ///////////////////////////// SETTINGS MANAGEMENT ////////////////////////////
  135. /////////////////////////////// BEGIN INCLUDES ///////////////////////////////
  136. //#include "../user-settings.h"
  137. ///////////////////////////// BEGIN USER-SETTINGS ////////////////////////////
  138. #ifndef USER_SETTINGS_H
  139. #define USER_SETTINGS_H
  140. ///////////////////////////// DRIVER CAPABILITIES ////////////////////////////
  141. // The Cg compiler uses different "profiles" with different capabilities.
  142. // This shader requires a Cg compilation profile >= arbfp1, but a few options
  143. // require higher profiles like fp30 or fp40. The shader can't detect profile
  144. // or driver capabilities, so instead you must comment or uncomment the lines
  145. // below with "//" before "#define." Disable an option if you get compilation
  146. // errors resembling those listed. Generally speaking, all of these options
  147. // will run on nVidia cards, but only DRIVERS_ALLOW_TEX2DBIAS (if that) is
  148. // likely to run on ATI/AMD, due to the Cg compiler's profile limitations.
  149. // Derivatives: Unsupported on fp20, ps_1_1, ps_1_2, ps_1_3, and arbfp1.
  150. // Among other things, derivatives help us fix anisotropic filtering artifacts
  151. // with curved manually tiled phosphor mask coords. Related errors:
  152. // error C3004: function "float2 ddx(float2);" not supported in this profile
  153. // error C3004: function "float2 ddy(float2);" not supported in this profile
  154. //#define DRIVERS_ALLOW_DERIVATIVES
  155. // Fine derivatives: Unsupported on older ATI cards.
  156. // Fine derivatives enable 2x2 fragment block communication, letting us perform
  157. // fast single-pass blur operations. If your card uses coarse derivatives and
  158. // these are enabled, blurs could look broken. Derivatives are a prerequisite.
  159. #ifdef DRIVERS_ALLOW_DERIVATIVES
  160. #define DRIVERS_ALLOW_FINE_DERIVATIVES
  161. #endif
  162. // Dynamic looping: Requires an fp30 or newer profile.
  163. // This makes phosphor mask resampling faster in some cases. Related errors:
  164. // error C5013: profile does not support "for" statements and "for" could not
  165. // be unrolled
  166. //#define DRIVERS_ALLOW_DYNAMIC_BRANCHES
  167. // Without DRIVERS_ALLOW_DYNAMIC_BRANCHES, we need to use unrollable loops.
  168. // Using one static loop avoids overhead if the user is right, but if the user
  169. // is wrong (loops are allowed), breaking a loop into if-blocked pieces with a
  170. // binary search can potentially save some iterations. However, it may fail:
  171. // error C6001: Temporary register limit of 32 exceeded; 35 registers
  172. // needed to compile program
  173. //#define ACCOMODATE_POSSIBLE_DYNAMIC_LOOPS
  174. // tex2Dlod: Requires an fp40 or newer profile. This can be used to disable
  175. // anisotropic filtering, thereby fixing related artifacts. Related errors:
  176. // error C3004: function "float4 tex2Dlod(sampler2D, float4);" not supported in
  177. // this profile
  178. //#define DRIVERS_ALLOW_TEX2DLOD
  179. // tex2Dbias: Requires an fp30 or newer profile. This can be used to alleviate
  180. // artifacts from anisotropic filtering and mipmapping. Related errors:
  181. // error C3004: function "float4 tex2Dbias(sampler2D, float4);" not supported
  182. // in this profile
  183. //#define DRIVERS_ALLOW_TEX2DBIAS
  184. // Integrated graphics compatibility: Integrated graphics like Intel HD 4000
  185. // impose stricter limitations on register counts and instructions. Enable
  186. // INTEGRATED_GRAPHICS_COMPATIBILITY_MODE if you still see error C6001 or:
  187. // error C6002: Instruction limit of 1024 exceeded: 1523 instructions needed
  188. // to compile program.
  189. // Enabling integrated graphics compatibility mode will automatically disable:
  190. // 1.) PHOSPHOR_MASK_MANUALLY_RESIZE: The phosphor mask will be softer.
  191. // (This may be reenabled in a later release.)
  192. // 2.) RUNTIME_GEOMETRY_MODE
  193. // 3.) The high-quality 4x4 Gaussian resize for the bloom approximation
  194. //#define INTEGRATED_GRAPHICS_COMPATIBILITY_MODE
  195. //////////////////////////// USER CODEPATH OPTIONS ///////////////////////////
  196. // To disable a #define option, turn its line into a comment with "//."
  197. // RUNTIME VS. COMPILE-TIME OPTIONS (Major Performance Implications):
  198. // Enable runtime shader parameters in the Retroarch (etc.) GUI? They override
  199. // many of the options in this file and allow real-time tuning, but many of
  200. // them are slower. Disabling them and using this text file will boost FPS.
  201. #define RUNTIME_SHADER_PARAMS_ENABLE
  202. // Specify the phosphor bloom sigma at runtime? This option is 10% slower, but
  203. // it's the only way to do a wide-enough full bloom with a runtime dot pitch.
  204. #define RUNTIME_PHOSPHOR_BLOOM_SIGMA
  205. // Specify antialiasing weight parameters at runtime? (Costs ~20% with cubics)
  206. #define RUNTIME_ANTIALIAS_WEIGHTS
  207. // Specify subpixel offsets at runtime? (WARNING: EXTREMELY EXPENSIVE!)
  208. //#define RUNTIME_ANTIALIAS_SUBPIXEL_OFFSETS
  209. // Make beam_horiz_filter and beam_horiz_linear_rgb_weight into runtime shader
  210. // parameters? This will require more math or dynamic branching.
  211. #define RUNTIME_SCANLINES_HORIZ_FILTER_COLORSPACE
  212. // Specify the tilt at runtime? This makes things about 3% slower.
  213. #define RUNTIME_GEOMETRY_TILT
  214. // Specify the geometry mode at runtime?
  215. #define RUNTIME_GEOMETRY_MODE
  216. // Specify the phosphor mask type (aperture grille, slot mask, shadow mask) and
  217. // mode (Lanczos-resize, hardware resize, or tile 1:1) at runtime, even without
  218. // dynamic branches? This is cheap if mask_resize_viewport_scale is small.
  219. #define FORCE_RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  220. // PHOSPHOR MASK:
  221. // Manually resize the phosphor mask for best results (slower)? Disabling this
  222. // removes the option to do so, but it may be faster without dynamic branches.
  223. #define PHOSPHOR_MASK_MANUALLY_RESIZE
  224. // If we sinc-resize the mask, should we Lanczos-window it (slower but better)?
  225. #define PHOSPHOR_MASK_RESIZE_LANCZOS_WINDOW
  226. // Larger blurs are expensive, but we need them to blur larger triads. We can
  227. // detect the right blur if the triad size is static or our profile allows
  228. // dynamic branches, but otherwise we use the largest blur the user indicates
  229. // they might need:
  230. #define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_3_PIXELS
  231. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_6_PIXELS
  232. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_9_PIXELS
  233. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_12_PIXELS
  234. // Here's a helpful chart:
  235. // MaxTriadSize BlurSize MinTriadCountsByResolution
  236. // 3.0 9.0 480/640/960/1920 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  237. // 6.0 17.0 240/320/480/960 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  238. // 9.0 25.0 160/213/320/640 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  239. // 12.0 31.0 120/160/240/480 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  240. // 18.0 43.0 80/107/160/320 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  241. /////////////////////////////// USER PARAMETERS //////////////////////////////
  242. // Note: Many of these static parameters are overridden by runtime shader
  243. // parameters when those are enabled. However, many others are static codepath
  244. // options that were cleaner or more convert to code as static constants.
  245. // GAMMA:
  246. static const float crt_gamma_static = 2.5; // range [1, 5]
  247. static const float lcd_gamma_static = 2.2; // range [1, 5]
  248. // LEVELS MANAGEMENT:
  249. // Control the final multiplicative image contrast:
  250. static const float levels_contrast_static = 1.0; // range [0, 4)
  251. // We auto-dim to avoid clipping between passes and restore brightness
  252. // later. Control the dim factor here: Lower values clip less but crush
  253. // blacks more (static only for now).
  254. static const float levels_autodim_temp = 0.5; // range (0, 1] default is 0.5 but that was unnecessarily dark for me, so I set it to 1.0
  255. // HALATION/DIFFUSION/BLOOM:
  256. // Halation weight: How much energy should be lost to electrons bounding
  257. // around under the CRT glass and exciting random phosphors?
  258. static const float halation_weight_static = 0.0; // range [0, 1]
  259. // Refractive diffusion weight: How much light should spread/diffuse from
  260. // refracting through the CRT glass?
  261. static const float diffusion_weight_static = 0.075; // range [0, 1]
  262. // Underestimate brightness: Bright areas bloom more, but we can base the
  263. // bloom brightpass on a lower brightness to sharpen phosphors, or a higher
  264. // brightness to soften them. Low values clip, but >= 0.8 looks okay.
  265. static const float bloom_underestimate_levels_static = 0.8; // range [0, 5]
  266. // Blur all colors more than necessary for a softer phosphor bloom?
  267. static const float bloom_excess_static = 0.0; // range [0, 1]
  268. // The BLOOM_APPROX pass approximates a phosphor blur early on with a small
  269. // blurred resize of the input (convergence offsets are applied as well).
  270. // There are three filter options (static option only for now):
  271. // 0.) Bilinear resize: A fast, close approximation to a 4x4 resize
  272. // if min_allowed_viewport_triads and the BLOOM_APPROX resolution are sane
  273. // and beam_max_sigma is low.
  274. // 1.) 3x3 resize blur: Medium speed, soft/smeared from bilinear blurring,
  275. // always uses a static sigma regardless of beam_max_sigma or
  276. // mask_num_triads_desired.
  277. // 2.) True 4x4 Gaussian resize: Slowest, technically correct.
  278. // These options are more pronounced for the fast, unbloomed shader version.
  279. #ifndef RADEON_FIX
  280. static const float bloom_approx_filter_static = 2.0;
  281. #else
  282. static const float bloom_approx_filter_static = 1.0;
  283. #endif
  284. // ELECTRON BEAM SCANLINE DISTRIBUTION:
  285. // How many scanlines should contribute light to each pixel? Using more
  286. // scanlines is slower (especially for a generalized Gaussian) but less
  287. // distorted with larger beam sigmas (especially for a pure Gaussian). The
  288. // max_beam_sigma at which the closest unused weight is guaranteed <
  289. // 1.0/255.0 (for a 3x antialiased pure Gaussian) is:
  290. // 2 scanlines: max_beam_sigma = 0.2089; distortions begin ~0.34; 141.7 FPS pure, 131.9 FPS generalized
  291. // 3 scanlines, max_beam_sigma = 0.3879; distortions begin ~0.52; 137.5 FPS pure; 123.8 FPS generalized
  292. // 4 scanlines, max_beam_sigma = 0.5723; distortions begin ~0.70; 134.7 FPS pure; 117.2 FPS generalized
  293. // 5 scanlines, max_beam_sigma = 0.7591; distortions begin ~0.89; 131.6 FPS pure; 112.1 FPS generalized
  294. // 6 scanlines, max_beam_sigma = 0.9483; distortions begin ~1.08; 127.9 FPS pure; 105.6 FPS generalized
  295. static const float beam_num_scanlines = 3.0; // range [2, 6]
  296. // A generalized Gaussian beam varies shape with color too, now just width.
  297. // It's slower but more flexible (static option only for now).
  298. static const bool beam_generalized_gaussian = true;
  299. // What kind of scanline antialiasing do you want?
  300. // 0: Sample weights at 1x; 1: Sample weights at 3x; 2: Compute an integral
  301. // Integrals are slow (especially for generalized Gaussians) and rarely any
  302. // better than 3x antialiasing (static option only for now).
  303. static const float beam_antialias_level = 1.0; // range [0, 2]
  304. // Min/max standard deviations for scanline beams: Higher values widen and
  305. // soften scanlines. Depending on other options, low min sigmas can alias.
  306. static const float beam_min_sigma_static = 0.02; // range (0, 1]
  307. static const float beam_max_sigma_static = 0.3; // range (0, 1]
  308. // Beam width varies as a function of color: A power function (0) is more
  309. // configurable, but a spherical function (1) gives the widest beam
  310. // variability without aliasing (static option only for now).
  311. static const float beam_spot_shape_function = 0.0;
  312. // Spot shape power: Powers <= 1 give smoother spot shapes but lower
  313. // sharpness. Powers >= 1.0 are awful unless mix/max sigmas are close.
  314. static const float beam_spot_power_static = 1.0/3.0; // range (0, 16]
  315. // Generalized Gaussian max shape parameters: Higher values give flatter
  316. // scanline plateaus and steeper dropoffs, simultaneously widening and
  317. // sharpening scanlines at the cost of aliasing. 2.0 is pure Gaussian, and
  318. // values > ~40.0 cause artifacts with integrals.
  319. static const float beam_min_shape_static = 2.0; // range [2, 32]
  320. static const float beam_max_shape_static = 4.0; // range [2, 32]
  321. // Generalized Gaussian shape power: Affects how quickly the distribution
  322. // changes shape from Gaussian to steep/plateaued as color increases from 0
  323. // to 1.0. Higher powers appear softer for most colors, and lower powers
  324. // appear sharper for most colors.
  325. static const float beam_shape_power_static = 1.0/4.0; // range (0, 16]
  326. // What filter should be used to sample scanlines horizontally?
  327. // 0: Quilez (fast), 1: Gaussian (configurable), 2: Lanczos2 (sharp)
  328. static const float beam_horiz_filter_static = 0.0;
  329. // Standard deviation for horizontal Gaussian resampling:
  330. static const float beam_horiz_sigma_static = 0.35; // range (0, 2/3]
  331. // Do horizontal scanline sampling in linear RGB (correct light mixing),
  332. // gamma-encoded RGB (darker, hard spot shape, may better match bandwidth-
  333. // limiting circuitry in some CRT's), or a weighted avg.?
  334. static const float beam_horiz_linear_rgb_weight_static = 1.0; // range [0, 1]
  335. // Simulate scanline misconvergence? This needs 3x horizontal texture
  336. // samples and 3x texture samples of BLOOM_APPROX and HALATION_BLUR in
  337. // later passes (static option only for now).
  338. static const bool beam_misconvergence = true;
  339. // Convergence offsets in x/y directions for R/G/B scanline beams in units
  340. // of scanlines. Positive offsets go right/down; ranges [-2, 2]
  341. static const float2 convergence_offsets_r_static = float2(0.1, 0.2);
  342. static const float2 convergence_offsets_g_static = float2(0.3, 0.4);
  343. static const float2 convergence_offsets_b_static = float2(0.5, 0.6);
  344. // Detect interlacing (static option only for now)?
  345. static const bool interlace_detect = true;
  346. // Assume 1080-line sources are interlaced?
  347. static const bool interlace_1080i_static = false;
  348. // For interlaced sources, assume TFF (top-field first) or BFF order?
  349. // (Whether this matters depends on the nature of the interlaced input.)
  350. static const bool interlace_bff_static = false;
  351. // ANTIALIASING:
  352. // What AA level do you want for curvature/overscan/subpixels? Options:
  353. // 0x (none), 1x (sample subpixels), 4x, 5x, 6x, 7x, 8x, 12x, 16x, 20x, 24x
  354. // (Static option only for now)
  355. static const float aa_level = 12.0; // range [0, 24]
  356. // What antialiasing filter do you want (static option only)? Options:
  357. // 0: Box (separable), 1: Box (cylindrical),
  358. // 2: Tent (separable), 3: Tent (cylindrical),
  359. // 4: Gaussian (separable), 5: Gaussian (cylindrical),
  360. // 6: Cubic* (separable), 7: Cubic* (cylindrical, poor)
  361. // 8: Lanczos Sinc (separable), 9: Lanczos Jinc (cylindrical, poor)
  362. // * = Especially slow with RUNTIME_ANTIALIAS_WEIGHTS
  363. static const float aa_filter = 6.0; // range [0, 9]
  364. // Flip the sample grid on odd/even frames (static option only for now)?
  365. static const bool aa_temporal = false;
  366. // Use RGB subpixel offsets for antialiasing? The pixel is at green, and
  367. // the blue offset is the negative r offset; range [0, 0.5]
  368. static const float2 aa_subpixel_r_offset_static = float2(-1.0/3.0, 0.0);//float2(0.0);
  369. // Cubics: See http://www.imagemagick.org/Usage/filter/#mitchell
  370. // 1.) "Keys cubics" with B = 1 - 2C are considered the highest quality.
  371. // 2.) C = 0.5 (default) is Catmull-Rom; higher C's apply sharpening.
  372. // 3.) C = 1.0/3.0 is the Mitchell-Netravali filter.
  373. // 4.) C = 0.0 is a soft spline filter.
  374. static const float aa_cubic_c_static = 0.5; // range [0, 4]
  375. // Standard deviation for Gaussian antialiasing: Try 0.5/aa_pixel_diameter.
  376. static const float aa_gauss_sigma_static = 0.5; // range [0.0625, 1.0]
  377. // PHOSPHOR MASK:
  378. // Mask type: 0 = aperture grille, 1 = slot mask, 2 = EDP shadow mask
  379. static const float mask_type_static = 1.0; // range [0, 2]
  380. // We can sample the mask three ways. Pick 2/3 from: Pretty/Fast/Flexible.
  381. // 0.) Sinc-resize to the desired dot pitch manually (pretty/slow/flexible).
  382. // This requires PHOSPHOR_MASK_MANUALLY_RESIZE to be #defined.
  383. // 1.) Hardware-resize to the desired dot pitch (ugly/fast/flexible). This
  384. // is halfway decent with LUT mipmapping but atrocious without it.
  385. // 2.) Tile it without resizing at a 1:1 texel:pixel ratio for flat coords
  386. // (pretty/fast/inflexible). Each input LUT has a fixed dot pitch.
  387. // This mode reuses the same masks, so triads will be enormous unless
  388. // you change the mask LUT filenames in your .cgp file.
  389. static const float mask_sample_mode_static = 0.0; // range [0, 2]
  390. // Prefer setting the triad size (0.0) or number on the screen (1.0)?
  391. // If RUNTIME_PHOSPHOR_BLOOM_SIGMA isn't #defined, the specified triad size
  392. // will always be used to calculate the full bloom sigma statically.
  393. static const float mask_specify_num_triads_static = 0.0; // range [0, 1]
  394. // Specify the phosphor triad size, in pixels. Each tile (usually with 8
  395. // triads) will be rounded to the nearest integer tile size and clamped to
  396. // obey minimum size constraints (imposed to reduce downsize taps) and
  397. // maximum size constraints (imposed to have a sane MASK_RESIZE FBO size).
  398. // To increase the size limit, double the viewport-relative scales for the
  399. // two MASK_RESIZE passes in crt-royale.cgp and user-cgp-contants.h.
  400. // range [1, mask_texture_small_size/mask_triads_per_tile]
  401. static const float mask_triad_size_desired_static = 24.0 / 8.0;
  402. // If mask_specify_num_triads is 1.0/true, we'll go by this instead (the
  403. // final size will be rounded and constrained as above); default 480.0
  404. static const float mask_num_triads_desired_static = 480.0;
  405. // How many lobes should the sinc/Lanczos resizer use? More lobes require
  406. // more samples and avoid moire a bit better, but some is unavoidable
  407. // depending on the destination size (static option for now).
  408. static const float mask_sinc_lobes = 3.0; // range [2, 4]
  409. // The mask is resized using a variable number of taps in each dimension,
  410. // but some Cg profiles always fetch a constant number of taps no matter
  411. // what (no dynamic branching). We can limit the maximum number of taps if
  412. // we statically limit the minimum phosphor triad size. Larger values are
  413. // faster, but the limit IS enforced (static option only, forever);
  414. // range [1, mask_texture_small_size/mask_triads_per_tile]
  415. // TODO: Make this 1.0 and compensate with smarter sampling!
  416. static const float mask_min_allowed_triad_size = 2.0;
  417. // GEOMETRY:
  418. // Geometry mode:
  419. // 0: Off (default), 1: Spherical mapping (like cgwg's),
  420. // 2: Alt. spherical mapping (more bulbous), 3: Cylindrical/Trinitron
  421. static const float geom_mode_static = 0.0; // range [0, 3]
  422. // Radius of curvature: Measured in units of your viewport's diagonal size.
  423. static const float geom_radius_static = 2.0; // range [1/(2*pi), 1024]
  424. // View dist is the distance from the player to their physical screen, in
  425. // units of the viewport's diagonal size. It controls the field of view.
  426. static const float geom_view_dist_static = 2.0; // range [0.5, 1024]
  427. // Tilt angle in radians (clockwise around up and right vectors):
  428. static const float2 geom_tilt_angle_static = float2(0.0, 0.0); // range [-pi, pi]
  429. // Aspect ratio: When the true viewport size is unknown, this value is used
  430. // to help convert between the phosphor triad size and count, along with
  431. // the mask_resize_viewport_scale constant from user-cgp-constants.h. Set
  432. // this equal to Retroarch's display aspect ratio (DAR) for best results;
  433. // range [1, geom_max_aspect_ratio from user-cgp-constants.h];
  434. // default (256/224)*(54/47) = 1.313069909 (see below)
  435. static const float geom_aspect_ratio_static = 1.313069909;
  436. // Before getting into overscan, here's some general aspect ratio info:
  437. // - DAR = display aspect ratio = SAR * PAR; as in your Retroarch setting
  438. // - SAR = storage aspect ratio = DAR / PAR; square pixel emulator frame AR
  439. // - PAR = pixel aspect ratio = DAR / SAR; holds regardless of cropping
  440. // Geometry processing has to "undo" the screen-space 2D DAR to calculate
  441. // 3D view vectors, then reapplies the aspect ratio to the simulated CRT in
  442. // uv-space. To ensure the source SAR is intended for a ~4:3 DAR, either:
  443. // a.) Enable Retroarch's "Crop Overscan"
  444. // b.) Readd horizontal padding: Set overscan to e.g. N*(1.0, 240.0/224.0)
  445. // Real consoles use horizontal black padding in the signal, but emulators
  446. // often crop this without cropping the vertical padding; a 256x224 [S]NES
  447. // frame (8:7 SAR) is intended for a ~4:3 DAR, but a 256x240 frame is not.
  448. // The correct [S]NES PAR is 54:47, found by blargg and NewRisingSun:
  449. // http://board.zsnes.com/phpBB3/viewtopic.php?f=22&t=11928&start=50
  450. // http://forums.nesdev.com/viewtopic.php?p=24815#p24815
  451. // For flat output, it's okay to set DAR = [existing] SAR * [correct] PAR
  452. // without doing a. or b., but horizontal image borders will be tighter
  453. // than vertical ones, messing up curvature and overscan. Fixing the
  454. // padding first corrects this.
  455. // Overscan: Amount to "zoom in" before cropping. You can zoom uniformly
  456. // or adjust x/y independently to e.g. readd horizontal padding, as noted
  457. // above: Values < 1.0 zoom out; range (0, inf)
  458. static const float2 geom_overscan_static = float2(1.0, 1.0);// * 1.005 * (1.0, 240/224.0)
  459. // Compute a proper pixel-space to texture-space matrix even without ddx()/
  460. // ddy()? This is ~8.5% slower but improves antialiasing/subpixel filtering
  461. // with strong curvature (static option only for now).
  462. static const bool geom_force_correct_tangent_matrix = true;
  463. // BORDERS:
  464. // Rounded border size in texture uv coords:
  465. static const float border_size_static = 0.015; // range [0, 0.5]
  466. // Border darkness: Moderate values darken the border smoothly, and high
  467. // values make the image very dark just inside the border:
  468. static const float border_darkness_static = 2.0; // range [0, inf)
  469. // Border compression: High numbers compress border transitions, narrowing
  470. // the dark border area.
  471. static const float border_compress_static = 2.5; // range [1, inf)
  472. #endif // USER_SETTINGS_H
  473. ///////////////////////////// END USER-SETTINGS ////////////////////////////
  474. //#include "derived-settings-and-constants.h"
  475. ///////////////////// BEGIN DERIVED-SETTINGS-AND-CONSTANTS ////////////////////
  476. #ifndef DERIVED_SETTINGS_AND_CONSTANTS_H
  477. #define DERIVED_SETTINGS_AND_CONSTANTS_H
  478. ///////////////////////////// GPL LICENSE NOTICE /////////////////////////////
  479. // crt-royale: A full-featured CRT shader, with cheese.
  480. // Copyright (C) 2014 TroggleMonkey <trogglemonkey@gmx.com>
  481. //
  482. // This program is free software; you can redistribute it and/or modify it
  483. // under the terms of the GNU General Public License as published by the Free
  484. // Software Foundation; either version 2 of the License, or any later version.
  485. //
  486. // This program is distributed in the hope that it will be useful, but WITHOUT
  487. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  488. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  489. // more details.
  490. //
  491. // You should have received a copy of the GNU General Public License along with
  492. // this program; if not, write to the Free Software Foundation, Inc., 59 Temple
  493. // Place, Suite 330, Boston, MA 02111-1307 USA
  494. ///////////////////////////////// DESCRIPTION ////////////////////////////////
  495. // These macros and constants can be used across the whole codebase.
  496. // Unlike the values in user-settings.cgh, end users shouldn't modify these.
  497. /////////////////////////////// BEGIN INCLUDES ///////////////////////////////
  498. //#include "../user-settings.h"
  499. ///////////////////////////// BEGIN USER-SETTINGS ////////////////////////////
  500. #ifndef USER_SETTINGS_H
  501. #define USER_SETTINGS_H
  502. ///////////////////////////// DRIVER CAPABILITIES ////////////////////////////
  503. // The Cg compiler uses different "profiles" with different capabilities.
  504. // This shader requires a Cg compilation profile >= arbfp1, but a few options
  505. // require higher profiles like fp30 or fp40. The shader can't detect profile
  506. // or driver capabilities, so instead you must comment or uncomment the lines
  507. // below with "//" before "#define." Disable an option if you get compilation
  508. // errors resembling those listed. Generally speaking, all of these options
  509. // will run on nVidia cards, but only DRIVERS_ALLOW_TEX2DBIAS (if that) is
  510. // likely to run on ATI/AMD, due to the Cg compiler's profile limitations.
  511. // Derivatives: Unsupported on fp20, ps_1_1, ps_1_2, ps_1_3, and arbfp1.
  512. // Among other things, derivatives help us fix anisotropic filtering artifacts
  513. // with curved manually tiled phosphor mask coords. Related errors:
  514. // error C3004: function "float2 ddx(float2);" not supported in this profile
  515. // error C3004: function "float2 ddy(float2);" not supported in this profile
  516. //#define DRIVERS_ALLOW_DERIVATIVES
  517. // Fine derivatives: Unsupported on older ATI cards.
  518. // Fine derivatives enable 2x2 fragment block communication, letting us perform
  519. // fast single-pass blur operations. If your card uses coarse derivatives and
  520. // these are enabled, blurs could look broken. Derivatives are a prerequisite.
  521. #ifdef DRIVERS_ALLOW_DERIVATIVES
  522. #define DRIVERS_ALLOW_FINE_DERIVATIVES
  523. #endif
  524. // Dynamic looping: Requires an fp30 or newer profile.
  525. // This makes phosphor mask resampling faster in some cases. Related errors:
  526. // error C5013: profile does not support "for" statements and "for" could not
  527. // be unrolled
  528. //#define DRIVERS_ALLOW_DYNAMIC_BRANCHES
  529. // Without DRIVERS_ALLOW_DYNAMIC_BRANCHES, we need to use unrollable loops.
  530. // Using one static loop avoids overhead if the user is right, but if the user
  531. // is wrong (loops are allowed), breaking a loop into if-blocked pieces with a
  532. // binary search can potentially save some iterations. However, it may fail:
  533. // error C6001: Temporary register limit of 32 exceeded; 35 registers
  534. // needed to compile program
  535. //#define ACCOMODATE_POSSIBLE_DYNAMIC_LOOPS
  536. // tex2Dlod: Requires an fp40 or newer profile. This can be used to disable
  537. // anisotropic filtering, thereby fixing related artifacts. Related errors:
  538. // error C3004: function "float4 tex2Dlod(sampler2D, float4);" not supported in
  539. // this profile
  540. //#define DRIVERS_ALLOW_TEX2DLOD
  541. // tex2Dbias: Requires an fp30 or newer profile. This can be used to alleviate
  542. // artifacts from anisotropic filtering and mipmapping. Related errors:
  543. // error C3004: function "float4 tex2Dbias(sampler2D, float4);" not supported
  544. // in this profile
  545. //#define DRIVERS_ALLOW_TEX2DBIAS
  546. // Integrated graphics compatibility: Integrated graphics like Intel HD 4000
  547. // impose stricter limitations on register counts and instructions. Enable
  548. // INTEGRATED_GRAPHICS_COMPATIBILITY_MODE if you still see error C6001 or:
  549. // error C6002: Instruction limit of 1024 exceeded: 1523 instructions needed
  550. // to compile program.
  551. // Enabling integrated graphics compatibility mode will automatically disable:
  552. // 1.) PHOSPHOR_MASK_MANUALLY_RESIZE: The phosphor mask will be softer.
  553. // (This may be reenabled in a later release.)
  554. // 2.) RUNTIME_GEOMETRY_MODE
  555. // 3.) The high-quality 4x4 Gaussian resize for the bloom approximation
  556. //#define INTEGRATED_GRAPHICS_COMPATIBILITY_MODE
  557. //////////////////////////// USER CODEPATH OPTIONS ///////////////////////////
  558. // To disable a #define option, turn its line into a comment with "//."
  559. // RUNTIME VS. COMPILE-TIME OPTIONS (Major Performance Implications):
  560. // Enable runtime shader parameters in the Retroarch (etc.) GUI? They override
  561. // many of the options in this file and allow real-time tuning, but many of
  562. // them are slower. Disabling them and using this text file will boost FPS.
  563. #define RUNTIME_SHADER_PARAMS_ENABLE
  564. // Specify the phosphor bloom sigma at runtime? This option is 10% slower, but
  565. // it's the only way to do a wide-enough full bloom with a runtime dot pitch.
  566. #define RUNTIME_PHOSPHOR_BLOOM_SIGMA
  567. // Specify antialiasing weight parameters at runtime? (Costs ~20% with cubics)
  568. #define RUNTIME_ANTIALIAS_WEIGHTS
  569. // Specify subpixel offsets at runtime? (WARNING: EXTREMELY EXPENSIVE!)
  570. //#define RUNTIME_ANTIALIAS_SUBPIXEL_OFFSETS
  571. // Make beam_horiz_filter and beam_horiz_linear_rgb_weight into runtime shader
  572. // parameters? This will require more math or dynamic branching.
  573. #define RUNTIME_SCANLINES_HORIZ_FILTER_COLORSPACE
  574. // Specify the tilt at runtime? This makes things about 3% slower.
  575. #define RUNTIME_GEOMETRY_TILT
  576. // Specify the geometry mode at runtime?
  577. #define RUNTIME_GEOMETRY_MODE
  578. // Specify the phosphor mask type (aperture grille, slot mask, shadow mask) and
  579. // mode (Lanczos-resize, hardware resize, or tile 1:1) at runtime, even without
  580. // dynamic branches? This is cheap if mask_resize_viewport_scale is small.
  581. #define FORCE_RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  582. // PHOSPHOR MASK:
  583. // Manually resize the phosphor mask for best results (slower)? Disabling this
  584. // removes the option to do so, but it may be faster without dynamic branches.
  585. #define PHOSPHOR_MASK_MANUALLY_RESIZE
  586. // If we sinc-resize the mask, should we Lanczos-window it (slower but better)?
  587. #define PHOSPHOR_MASK_RESIZE_LANCZOS_WINDOW
  588. // Larger blurs are expensive, but we need them to blur larger triads. We can
  589. // detect the right blur if the triad size is static or our profile allows
  590. // dynamic branches, but otherwise we use the largest blur the user indicates
  591. // they might need:
  592. #define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_3_PIXELS
  593. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_6_PIXELS
  594. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_9_PIXELS
  595. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_12_PIXELS
  596. // Here's a helpful chart:
  597. // MaxTriadSize BlurSize MinTriadCountsByResolution
  598. // 3.0 9.0 480/640/960/1920 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  599. // 6.0 17.0 240/320/480/960 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  600. // 9.0 25.0 160/213/320/640 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  601. // 12.0 31.0 120/160/240/480 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  602. // 18.0 43.0 80/107/160/320 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  603. /////////////////////////////// USER PARAMETERS //////////////////////////////
  604. // Note: Many of these static parameters are overridden by runtime shader
  605. // parameters when those are enabled. However, many others are static codepath
  606. // options that were cleaner or more convert to code as static constants.
  607. // GAMMA:
  608. static const float crt_gamma_static = 2.5; // range [1, 5]
  609. static const float lcd_gamma_static = 2.2; // range [1, 5]
  610. // LEVELS MANAGEMENT:
  611. // Control the final multiplicative image contrast:
  612. static const float levels_contrast_static = 1.0; // range [0, 4)
  613. // We auto-dim to avoid clipping between passes and restore brightness
  614. // later. Control the dim factor here: Lower values clip less but crush
  615. // blacks more (static only for now).
  616. static const float levels_autodim_temp = 0.5; // range (0, 1] default is 0.5 but that was unnecessarily dark for me, so I set it to 1.0
  617. // HALATION/DIFFUSION/BLOOM:
  618. // Halation weight: How much energy should be lost to electrons bounding
  619. // around under the CRT glass and exciting random phosphors?
  620. static const float halation_weight_static = 0.0; // range [0, 1]
  621. // Refractive diffusion weight: How much light should spread/diffuse from
  622. // refracting through the CRT glass?
  623. static const float diffusion_weight_static = 0.075; // range [0, 1]
  624. // Underestimate brightness: Bright areas bloom more, but we can base the
  625. // bloom brightpass on a lower brightness to sharpen phosphors, or a higher
  626. // brightness to soften them. Low values clip, but >= 0.8 looks okay.
  627. static const float bloom_underestimate_levels_static = 0.8; // range [0, 5]
  628. // Blur all colors more than necessary for a softer phosphor bloom?
  629. static const float bloom_excess_static = 0.0; // range [0, 1]
  630. // The BLOOM_APPROX pass approximates a phosphor blur early on with a small
  631. // blurred resize of the input (convergence offsets are applied as well).
  632. // There are three filter options (static option only for now):
  633. // 0.) Bilinear resize: A fast, close approximation to a 4x4 resize
  634. // if min_allowed_viewport_triads and the BLOOM_APPROX resolution are sane
  635. // and beam_max_sigma is low.
  636. // 1.) 3x3 resize blur: Medium speed, soft/smeared from bilinear blurring,
  637. // always uses a static sigma regardless of beam_max_sigma or
  638. // mask_num_triads_desired.
  639. // 2.) True 4x4 Gaussian resize: Slowest, technically correct.
  640. // These options are more pronounced for the fast, unbloomed shader version.
  641. #ifndef RADEON_FIX
  642. static const float bloom_approx_filter_static = 2.0;
  643. #else
  644. static const float bloom_approx_filter_static = 1.0;
  645. #endif
  646. // ELECTRON BEAM SCANLINE DISTRIBUTION:
  647. // How many scanlines should contribute light to each pixel? Using more
  648. // scanlines is slower (especially for a generalized Gaussian) but less
  649. // distorted with larger beam sigmas (especially for a pure Gaussian). The
  650. // max_beam_sigma at which the closest unused weight is guaranteed <
  651. // 1.0/255.0 (for a 3x antialiased pure Gaussian) is:
  652. // 2 scanlines: max_beam_sigma = 0.2089; distortions begin ~0.34; 141.7 FPS pure, 131.9 FPS generalized
  653. // 3 scanlines, max_beam_sigma = 0.3879; distortions begin ~0.52; 137.5 FPS pure; 123.8 FPS generalized
  654. // 4 scanlines, max_beam_sigma = 0.5723; distortions begin ~0.70; 134.7 FPS pure; 117.2 FPS generalized
  655. // 5 scanlines, max_beam_sigma = 0.7591; distortions begin ~0.89; 131.6 FPS pure; 112.1 FPS generalized
  656. // 6 scanlines, max_beam_sigma = 0.9483; distortions begin ~1.08; 127.9 FPS pure; 105.6 FPS generalized
  657. static const float beam_num_scanlines = 3.0; // range [2, 6]
  658. // A generalized Gaussian beam varies shape with color too, now just width.
  659. // It's slower but more flexible (static option only for now).
  660. static const bool beam_generalized_gaussian = true;
  661. // What kind of scanline antialiasing do you want?
  662. // 0: Sample weights at 1x; 1: Sample weights at 3x; 2: Compute an integral
  663. // Integrals are slow (especially for generalized Gaussians) and rarely any
  664. // better than 3x antialiasing (static option only for now).
  665. static const float beam_antialias_level = 1.0; // range [0, 2]
  666. // Min/max standard deviations for scanline beams: Higher values widen and
  667. // soften scanlines. Depending on other options, low min sigmas can alias.
  668. static const float beam_min_sigma_static = 0.02; // range (0, 1]
  669. static const float beam_max_sigma_static = 0.3; // range (0, 1]
  670. // Beam width varies as a function of color: A power function (0) is more
  671. // configurable, but a spherical function (1) gives the widest beam
  672. // variability without aliasing (static option only for now).
  673. static const float beam_spot_shape_function = 0.0;
  674. // Spot shape power: Powers <= 1 give smoother spot shapes but lower
  675. // sharpness. Powers >= 1.0 are awful unless mix/max sigmas are close.
  676. static const float beam_spot_power_static = 1.0/3.0; // range (0, 16]
  677. // Generalized Gaussian max shape parameters: Higher values give flatter
  678. // scanline plateaus and steeper dropoffs, simultaneously widening and
  679. // sharpening scanlines at the cost of aliasing. 2.0 is pure Gaussian, and
  680. // values > ~40.0 cause artifacts with integrals.
  681. static const float beam_min_shape_static = 2.0; // range [2, 32]
  682. static const float beam_max_shape_static = 4.0; // range [2, 32]
  683. // Generalized Gaussian shape power: Affects how quickly the distribution
  684. // changes shape from Gaussian to steep/plateaued as color increases from 0
  685. // to 1.0. Higher powers appear softer for most colors, and lower powers
  686. // appear sharper for most colors.
  687. static const float beam_shape_power_static = 1.0/4.0; // range (0, 16]
  688. // What filter should be used to sample scanlines horizontally?
  689. // 0: Quilez (fast), 1: Gaussian (configurable), 2: Lanczos2 (sharp)
  690. static const float beam_horiz_filter_static = 0.0;
  691. // Standard deviation for horizontal Gaussian resampling:
  692. static const float beam_horiz_sigma_static = 0.35; // range (0, 2/3]
  693. // Do horizontal scanline sampling in linear RGB (correct light mixing),
  694. // gamma-encoded RGB (darker, hard spot shape, may better match bandwidth-
  695. // limiting circuitry in some CRT's), or a weighted avg.?
  696. static const float beam_horiz_linear_rgb_weight_static = 1.0; // range [0, 1]
  697. // Simulate scanline misconvergence? This needs 3x horizontal texture
  698. // samples and 3x texture samples of BLOOM_APPROX and HALATION_BLUR in
  699. // later passes (static option only for now).
  700. static const bool beam_misconvergence = true;
  701. // Convergence offsets in x/y directions for R/G/B scanline beams in units
  702. // of scanlines. Positive offsets go right/down; ranges [-2, 2]
  703. static const float2 convergence_offsets_r_static = float2(0.1, 0.2);
  704. static const float2 convergence_offsets_g_static = float2(0.3, 0.4);
  705. static const float2 convergence_offsets_b_static = float2(0.5, 0.6);
  706. // Detect interlacing (static option only for now)?
  707. static const bool interlace_detect = true;
  708. // Assume 1080-line sources are interlaced?
  709. static const bool interlace_1080i_static = false;
  710. // For interlaced sources, assume TFF (top-field first) or BFF order?
  711. // (Whether this matters depends on the nature of the interlaced input.)
  712. static const bool interlace_bff_static = false;
  713. // ANTIALIASING:
  714. // What AA level do you want for curvature/overscan/subpixels? Options:
  715. // 0x (none), 1x (sample subpixels), 4x, 5x, 6x, 7x, 8x, 12x, 16x, 20x, 24x
  716. // (Static option only for now)
  717. static const float aa_level = 12.0; // range [0, 24]
  718. // What antialiasing filter do you want (static option only)? Options:
  719. // 0: Box (separable), 1: Box (cylindrical),
  720. // 2: Tent (separable), 3: Tent (cylindrical),
  721. // 4: Gaussian (separable), 5: Gaussian (cylindrical),
  722. // 6: Cubic* (separable), 7: Cubic* (cylindrical, poor)
  723. // 8: Lanczos Sinc (separable), 9: Lanczos Jinc (cylindrical, poor)
  724. // * = Especially slow with RUNTIME_ANTIALIAS_WEIGHTS
  725. static const float aa_filter = 6.0; // range [0, 9]
  726. // Flip the sample grid on odd/even frames (static option only for now)?
  727. static const bool aa_temporal = false;
  728. // Use RGB subpixel offsets for antialiasing? The pixel is at green, and
  729. // the blue offset is the negative r offset; range [0, 0.5]
  730. static const float2 aa_subpixel_r_offset_static = float2(-1.0/3.0, 0.0);//float2(0.0);
  731. // Cubics: See http://www.imagemagick.org/Usage/filter/#mitchell
  732. // 1.) "Keys cubics" with B = 1 - 2C are considered the highest quality.
  733. // 2.) C = 0.5 (default) is Catmull-Rom; higher C's apply sharpening.
  734. // 3.) C = 1.0/3.0 is the Mitchell-Netravali filter.
  735. // 4.) C = 0.0 is a soft spline filter.
  736. static const float aa_cubic_c_static = 0.5; // range [0, 4]
  737. // Standard deviation for Gaussian antialiasing: Try 0.5/aa_pixel_diameter.
  738. static const float aa_gauss_sigma_static = 0.5; // range [0.0625, 1.0]
  739. // PHOSPHOR MASK:
  740. // Mask type: 0 = aperture grille, 1 = slot mask, 2 = EDP shadow mask
  741. static const float mask_type_static = 1.0; // range [0, 2]
  742. // We can sample the mask three ways. Pick 2/3 from: Pretty/Fast/Flexible.
  743. // 0.) Sinc-resize to the desired dot pitch manually (pretty/slow/flexible).
  744. // This requires PHOSPHOR_MASK_MANUALLY_RESIZE to be #defined.
  745. // 1.) Hardware-resize to the desired dot pitch (ugly/fast/flexible). This
  746. // is halfway decent with LUT mipmapping but atrocious without it.
  747. // 2.) Tile it without resizing at a 1:1 texel:pixel ratio for flat coords
  748. // (pretty/fast/inflexible). Each input LUT has a fixed dot pitch.
  749. // This mode reuses the same masks, so triads will be enormous unless
  750. // you change the mask LUT filenames in your .cgp file.
  751. static const float mask_sample_mode_static = 0.0; // range [0, 2]
  752. // Prefer setting the triad size (0.0) or number on the screen (1.0)?
  753. // If RUNTIME_PHOSPHOR_BLOOM_SIGMA isn't #defined, the specified triad size
  754. // will always be used to calculate the full bloom sigma statically.
  755. static const float mask_specify_num_triads_static = 0.0; // range [0, 1]
  756. // Specify the phosphor triad size, in pixels. Each tile (usually with 8
  757. // triads) will be rounded to the nearest integer tile size and clamped to
  758. // obey minimum size constraints (imposed to reduce downsize taps) and
  759. // maximum size constraints (imposed to have a sane MASK_RESIZE FBO size).
  760. // To increase the size limit, double the viewport-relative scales for the
  761. // two MASK_RESIZE passes in crt-royale.cgp and user-cgp-contants.h.
  762. // range [1, mask_texture_small_size/mask_triads_per_tile]
  763. static const float mask_triad_size_desired_static = 24.0 / 8.0;
  764. // If mask_specify_num_triads is 1.0/true, we'll go by this instead (the
  765. // final size will be rounded and constrained as above); default 480.0
  766. static const float mask_num_triads_desired_static = 480.0;
  767. // How many lobes should the sinc/Lanczos resizer use? More lobes require
  768. // more samples and avoid moire a bit better, but some is unavoidable
  769. // depending on the destination size (static option for now).
  770. static const float mask_sinc_lobes = 3.0; // range [2, 4]
  771. // The mask is resized using a variable number of taps in each dimension,
  772. // but some Cg profiles always fetch a constant number of taps no matter
  773. // what (no dynamic branching). We can limit the maximum number of taps if
  774. // we statically limit the minimum phosphor triad size. Larger values are
  775. // faster, but the limit IS enforced (static option only, forever);
  776. // range [1, mask_texture_small_size/mask_triads_per_tile]
  777. // TODO: Make this 1.0 and compensate with smarter sampling!
  778. static const float mask_min_allowed_triad_size = 2.0;
  779. // GEOMETRY:
  780. // Geometry mode:
  781. // 0: Off (default), 1: Spherical mapping (like cgwg's),
  782. // 2: Alt. spherical mapping (more bulbous), 3: Cylindrical/Trinitron
  783. static const float geom_mode_static = 0.0; // range [0, 3]
  784. // Radius of curvature: Measured in units of your viewport's diagonal size.
  785. static const float geom_radius_static = 2.0; // range [1/(2*pi), 1024]
  786. // View dist is the distance from the player to their physical screen, in
  787. // units of the viewport's diagonal size. It controls the field of view.
  788. static const float geom_view_dist_static = 2.0; // range [0.5, 1024]
  789. // Tilt angle in radians (clockwise around up and right vectors):
  790. static const float2 geom_tilt_angle_static = float2(0.0, 0.0); // range [-pi, pi]
  791. // Aspect ratio: When the true viewport size is unknown, this value is used
  792. // to help convert between the phosphor triad size and count, along with
  793. // the mask_resize_viewport_scale constant from user-cgp-constants.h. Set
  794. // this equal to Retroarch's display aspect ratio (DAR) for best results;
  795. // range [1, geom_max_aspect_ratio from user-cgp-constants.h];
  796. // default (256/224)*(54/47) = 1.313069909 (see below)
  797. static const float geom_aspect_ratio_static = 1.313069909;
  798. // Before getting into overscan, here's some general aspect ratio info:
  799. // - DAR = display aspect ratio = SAR * PAR; as in your Retroarch setting
  800. // - SAR = storage aspect ratio = DAR / PAR; square pixel emulator frame AR
  801. // - PAR = pixel aspect ratio = DAR / SAR; holds regardless of cropping
  802. // Geometry processing has to "undo" the screen-space 2D DAR to calculate
  803. // 3D view vectors, then reapplies the aspect ratio to the simulated CRT in
  804. // uv-space. To ensure the source SAR is intended for a ~4:3 DAR, either:
  805. // a.) Enable Retroarch's "Crop Overscan"
  806. // b.) Readd horizontal padding: Set overscan to e.g. N*(1.0, 240.0/224.0)
  807. // Real consoles use horizontal black padding in the signal, but emulators
  808. // often crop this without cropping the vertical padding; a 256x224 [S]NES
  809. // frame (8:7 SAR) is intended for a ~4:3 DAR, but a 256x240 frame is not.
  810. // The correct [S]NES PAR is 54:47, found by blargg and NewRisingSun:
  811. // http://board.zsnes.com/phpBB3/viewtopic.php?f=22&t=11928&start=50
  812. // http://forums.nesdev.com/viewtopic.php?p=24815#p24815
  813. // For flat output, it's okay to set DAR = [existing] SAR * [correct] PAR
  814. // without doing a. or b., but horizontal image borders will be tighter
  815. // than vertical ones, messing up curvature and overscan. Fixing the
  816. // padding first corrects this.
  817. // Overscan: Amount to "zoom in" before cropping. You can zoom uniformly
  818. // or adjust x/y independently to e.g. readd horizontal padding, as noted
  819. // above: Values < 1.0 zoom out; range (0, inf)
  820. static const float2 geom_overscan_static = float2(1.0, 1.0);// * 1.005 * (1.0, 240/224.0)
  821. // Compute a proper pixel-space to texture-space matrix even without ddx()/
  822. // ddy()? This is ~8.5% slower but improves antialiasing/subpixel filtering
  823. // with strong curvature (static option only for now).
  824. static const bool geom_force_correct_tangent_matrix = true;
  825. // BORDERS:
  826. // Rounded border size in texture uv coords:
  827. static const float border_size_static = 0.015; // range [0, 0.5]
  828. // Border darkness: Moderate values darken the border smoothly, and high
  829. // values make the image very dark just inside the border:
  830. static const float border_darkness_static = 2.0; // range [0, inf)
  831. // Border compression: High numbers compress border transitions, narrowing
  832. // the dark border area.
  833. static const float border_compress_static = 2.5; // range [1, inf)
  834. #endif // USER_SETTINGS_H
  835. ///////////////////////////// END USER-SETTINGS ////////////////////////////
  836. //#include "user-cgp-constants.h"
  837. ///////////////////////// BEGIN USER-CGP-CONSTANTS /////////////////////////
  838. #ifndef USER_CGP_CONSTANTS_H
  839. #define USER_CGP_CONSTANTS_H
  840. // IMPORTANT:
  841. // These constants MUST be set appropriately for the settings in crt-royale.cgp
  842. // (or whatever related .cgp file you're using). If they aren't, you're likely
  843. // to get artifacts, the wrong phosphor mask size, etc. I wish these could be
  844. // set directly in the .cgp file to make things easier, but...they can't.
  845. // PASS SCALES AND RELATED CONSTANTS:
  846. // Copy the absolute scale_x for BLOOM_APPROX. There are two major versions of
  847. // this shader: One does a viewport-scale bloom, and the other skips it. The
  848. // latter benefits from a higher bloom_approx_scale_x, so save both separately:
  849. static const float bloom_approx_size_x = 320.0;
  850. static const float bloom_approx_size_x_for_fake = 400.0;
  851. // Copy the viewport-relative scales of the phosphor mask resize passes
  852. // (MASK_RESIZE and the pass immediately preceding it):
  853. static const float2 mask_resize_viewport_scale = float2(0.0625, 0.0625);
  854. // Copy the geom_max_aspect_ratio used to calculate the MASK_RESIZE scales, etc.:
  855. static const float geom_max_aspect_ratio = 4.0/3.0;
  856. // PHOSPHOR MASK TEXTURE CONSTANTS:
  857. // Set the following constants to reflect the properties of the phosphor mask
  858. // texture named in crt-royale.cgp. The shader optionally resizes a mask tile
  859. // based on user settings, then repeats a single tile until filling the screen.
  860. // The shader must know the input texture size (default 64x64), and to manually
  861. // resize, it must also know the horizontal triads per tile (default 8).
  862. static const float2 mask_texture_small_size = float2(64.0, 64.0);
  863. static const float2 mask_texture_large_size = float2(512.0, 512.0);
  864. static const float mask_triads_per_tile = 8.0;
  865. // We need the average brightness of the phosphor mask to compensate for the
  866. // dimming it causes. The following four values are roughly correct for the
  867. // masks included with the shader. Update the value for any LUT texture you
  868. // change. [Un]comment "#define PHOSPHOR_MASK_GRILLE14" depending on whether
  869. // the loaded aperture grille uses 14-pixel or 15-pixel stripes (default 15).
  870. //#define PHOSPHOR_MASK_GRILLE14
  871. static const float mask_grille14_avg_color = 50.6666666/255.0;
  872. // TileableLinearApertureGrille14Wide7d33Spacing*.png
  873. // TileableLinearApertureGrille14Wide10And6Spacing*.png
  874. static const float mask_grille15_avg_color = 53.0/255.0;
  875. // TileableLinearApertureGrille15Wide6d33Spacing*.png
  876. // TileableLinearApertureGrille15Wide8And5d5Spacing*.png
  877. static const float mask_slot_avg_color = 46.0/255.0;
  878. // TileableLinearSlotMask15Wide9And4d5Horizontal8VerticalSpacing*.png
  879. // TileableLinearSlotMaskTall15Wide9And4d5Horizontal9d14VerticalSpacing*.png
  880. static const float mask_shadow_avg_color = 41.0/255.0;
  881. // TileableLinearShadowMask*.png
  882. // TileableLinearShadowMaskEDP*.png
  883. #ifdef PHOSPHOR_MASK_GRILLE14
  884. static const float mask_grille_avg_color = mask_grille14_avg_color;
  885. #else
  886. static const float mask_grille_avg_color = mask_grille15_avg_color;
  887. #endif
  888. #endif // USER_CGP_CONSTANTS_H
  889. ////////////////////////// END USER-CGP-CONSTANTS //////////////////////////
  890. //////////////////////////////// END INCLUDES ////////////////////////////////
  891. /////////////////////////////// FIXED SETTINGS ///////////////////////////////
  892. // Avoid dividing by zero; using a macro overloads for float, float2, etc.:
  893. #define FIX_ZERO(c) (max(abs(c), 0.0000152587890625)) // 2^-16
  894. // Ensure the first pass decodes CRT gamma and the last encodes LCD gamma.
  895. #ifndef SIMULATE_CRT_ON_LCD
  896. #define SIMULATE_CRT_ON_LCD
  897. #endif
  898. // Manually tiling a manually resized texture creates texture coord derivative
  899. // discontinuities and confuses anisotropic filtering, causing discolored tile
  900. // seams in the phosphor mask. Workarounds:
  901. // a.) Using tex2Dlod disables anisotropic filtering for tiled masks. It's
  902. // downgraded to tex2Dbias without DRIVERS_ALLOW_TEX2DLOD #defined and
  903. // disabled without DRIVERS_ALLOW_TEX2DBIAS #defined either.
  904. // b.) "Tile flat twice" requires drawing two full tiles without border padding
  905. // to the resized mask FBO, and it's incompatible with same-pass curvature.
  906. // (Same-pass curvature isn't used but could be in the future...maybe.)
  907. // c.) "Fix discontinuities" requires derivatives and drawing one tile with
  908. // border padding to the resized mask FBO, but it works with same-pass
  909. // curvature. It's disabled without DRIVERS_ALLOW_DERIVATIVES #defined.
  910. // Precedence: a, then, b, then c (if multiple strategies are #defined).
  911. #define ANISOTROPIC_TILING_COMPAT_TEX2DLOD // 129.7 FPS, 4x, flat; 101.8 at fullscreen
  912. #define ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE // 128.1 FPS, 4x, flat; 101.5 at fullscreen
  913. #define ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES // 124.4 FPS, 4x, flat; 97.4 at fullscreen
  914. // Also, manually resampling the phosphor mask is slightly blurrier with
  915. // anisotropic filtering. (Resampling with mipmapping is even worse: It
  916. // creates artifacts, but only with the fully bloomed shader.) The difference
  917. // is subtle with small triads, but you can fix it for a small cost.
  918. //#define ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  919. ////////////////////////////// DERIVED SETTINGS //////////////////////////////
  920. // Intel HD 4000 GPU's can't handle manual mask resizing (for now), setting the
  921. // geometry mode at runtime, or a 4x4 true Gaussian resize. Disable
  922. // incompatible settings ASAP. (INTEGRATED_GRAPHICS_COMPATIBILITY_MODE may be
  923. // #defined by either user-settings.h or a wrapper .cg that #includes the
  924. // current .cg pass.)
  925. #ifdef INTEGRATED_GRAPHICS_COMPATIBILITY_MODE
  926. #ifdef PHOSPHOR_MASK_MANUALLY_RESIZE
  927. #undef PHOSPHOR_MASK_MANUALLY_RESIZE
  928. #endif
  929. #ifdef RUNTIME_GEOMETRY_MODE
  930. #undef RUNTIME_GEOMETRY_MODE
  931. #endif
  932. // Mode 2 (4x4 Gaussian resize) won't work, and mode 1 (3x3 blur) is
  933. // inferior in most cases, so replace 2.0 with 0.0:
  934. static const float bloom_approx_filter =
  935. bloom_approx_filter_static > 1.5 ? 0.0 : bloom_approx_filter_static;
  936. #else
  937. static const float bloom_approx_filter = bloom_approx_filter_static;
  938. #endif
  939. // Disable slow runtime paths if static parameters are used. Most of these
  940. // won't be a problem anyway once the params are disabled, but some will.
  941. #ifndef RUNTIME_SHADER_PARAMS_ENABLE
  942. #ifdef RUNTIME_PHOSPHOR_BLOOM_SIGMA
  943. #undef RUNTIME_PHOSPHOR_BLOOM_SIGMA
  944. #endif
  945. #ifdef RUNTIME_ANTIALIAS_WEIGHTS
  946. #undef RUNTIME_ANTIALIAS_WEIGHTS
  947. #endif
  948. #ifdef RUNTIME_ANTIALIAS_SUBPIXEL_OFFSETS
  949. #undef RUNTIME_ANTIALIAS_SUBPIXEL_OFFSETS
  950. #endif
  951. #ifdef RUNTIME_SCANLINES_HORIZ_FILTER_COLORSPACE
  952. #undef RUNTIME_SCANLINES_HORIZ_FILTER_COLORSPACE
  953. #endif
  954. #ifdef RUNTIME_GEOMETRY_TILT
  955. #undef RUNTIME_GEOMETRY_TILT
  956. #endif
  957. #ifdef RUNTIME_GEOMETRY_MODE
  958. #undef RUNTIME_GEOMETRY_MODE
  959. #endif
  960. #ifdef FORCE_RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  961. #undef FORCE_RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  962. #endif
  963. #endif
  964. // Make tex2Dbias a backup for tex2Dlod for wider compatibility.
  965. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DLOD
  966. #define ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  967. #endif
  968. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  969. #define ANISOTROPIC_RESAMPLING_COMPAT_TEX2DBIAS
  970. #endif
  971. // Rule out unavailable anisotropic compatibility strategies:
  972. #ifndef DRIVERS_ALLOW_DERIVATIVES
  973. #ifdef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  974. #undef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  975. #endif
  976. #endif
  977. #ifndef DRIVERS_ALLOW_TEX2DLOD
  978. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DLOD
  979. #undef ANISOTROPIC_TILING_COMPAT_TEX2DLOD
  980. #endif
  981. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  982. #undef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  983. #endif
  984. #ifdef ANTIALIAS_DISABLE_ANISOTROPIC
  985. #undef ANTIALIAS_DISABLE_ANISOTROPIC
  986. #endif
  987. #endif
  988. #ifndef DRIVERS_ALLOW_TEX2DBIAS
  989. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  990. #undef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  991. #endif
  992. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DBIAS
  993. #undef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DBIAS
  994. #endif
  995. #endif
  996. // Prioritize anisotropic tiling compatibility strategies by performance and
  997. // disable unused strategies. This concentrates all the nesting in one place.
  998. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DLOD
  999. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  1000. #undef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  1001. #endif
  1002. #ifdef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  1003. #undef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  1004. #endif
  1005. #ifdef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  1006. #undef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  1007. #endif
  1008. #else
  1009. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  1010. #ifdef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  1011. #undef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  1012. #endif
  1013. #ifdef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  1014. #undef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  1015. #endif
  1016. #else
  1017. // ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE is only compatible with
  1018. // flat texture coords in the same pass, but that's all we use.
  1019. #ifdef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  1020. #ifdef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  1021. #undef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  1022. #endif
  1023. #endif
  1024. #endif
  1025. #endif
  1026. // The tex2Dlod and tex2Dbias strategies share a lot in common, and we can
  1027. // reduce some #ifdef nesting in the next section by essentially OR'ing them:
  1028. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DLOD
  1029. #define ANISOTROPIC_TILING_COMPAT_TEX2DLOD_FAMILY
  1030. #endif
  1031. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  1032. #define ANISOTROPIC_TILING_COMPAT_TEX2DLOD_FAMILY
  1033. #endif
  1034. // Prioritize anisotropic resampling compatibility strategies the same way:
  1035. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  1036. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DBIAS
  1037. #undef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DBIAS
  1038. #endif
  1039. #endif
  1040. /////////////////////// DERIVED PHOSPHOR MASK CONSTANTS //////////////////////
  1041. // If we can use the large mipmapped LUT without mipmapping artifacts, we
  1042. // should: It gives us more options for using fewer samples.
  1043. #ifdef DRIVERS_ALLOW_TEX2DLOD
  1044. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  1045. // TODO: Take advantage of this!
  1046. #define PHOSPHOR_MASK_RESIZE_MIPMAPPED_LUT
  1047. static const float2 mask_resize_src_lut_size = mask_texture_large_size;
  1048. #else
  1049. static const float2 mask_resize_src_lut_size = mask_texture_small_size;
  1050. #endif
  1051. #else
  1052. static const float2 mask_resize_src_lut_size = mask_texture_small_size;
  1053. #endif
  1054. // tex2D's sampler2D parameter MUST be a uniform global, a uniform input to
  1055. // main_fragment, or a static alias of one of the above. This makes it hard
  1056. // to select the phosphor mask at runtime: We can't even assign to a uniform
  1057. // global in the vertex shader or select a sampler2D in the vertex shader and
  1058. // pass it to the fragment shader (even with explicit TEXUNIT# bindings),
  1059. // because it just gives us the input texture or a black screen. However, we
  1060. // can get around these limitations by calling tex2D three times with different
  1061. // uniform samplers (or resizing the phosphor mask three times altogether).
  1062. // With dynamic branches, we can process only one of these branches on top of
  1063. // quickly discarding fragments we don't need (cgc seems able to overcome
  1064. // limigations around dependent texture fetches inside of branches). Without
  1065. // dynamic branches, we have to process every branch for every fragment...which
  1066. // is slower. Runtime sampling mode selection is slower without dynamic
  1067. // branches as well. Let the user's static #defines decide if it's worth it.
  1068. #ifdef DRIVERS_ALLOW_DYNAMIC_BRANCHES
  1069. #define RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  1070. #else
  1071. #ifdef FORCE_RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  1072. #define RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  1073. #endif
  1074. #endif
  1075. // We need to render some minimum number of tiles in the resize passes.
  1076. // We need at least 1.0 just to repeat a single tile, and we need extra
  1077. // padding beyond that for anisotropic filtering, discontinuitity fixing,
  1078. // antialiasing, same-pass curvature (not currently used), etc. First
  1079. // determine how many border texels and tiles we need, based on how the result
  1080. // will be sampled:
  1081. #ifdef GEOMETRY_EARLY
  1082. static const float max_subpixel_offset = aa_subpixel_r_offset_static.x;
  1083. // Most antialiasing filters have a base radius of 4.0 pixels:
  1084. static const float max_aa_base_pixel_border = 4.0 +
  1085. max_subpixel_offset;
  1086. #else
  1087. static const float max_aa_base_pixel_border = 0.0;
  1088. #endif
  1089. // Anisotropic filtering adds about 0.5 to the pixel border:
  1090. #ifndef ANISOTROPIC_TILING_COMPAT_TEX2DLOD_FAMILY
  1091. static const float max_aniso_pixel_border = max_aa_base_pixel_border + 0.5;
  1092. #else
  1093. static const float max_aniso_pixel_border = max_aa_base_pixel_border;
  1094. #endif
  1095. // Fixing discontinuities adds 1.0 more to the pixel border:
  1096. #ifdef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  1097. static const float max_tiled_pixel_border = max_aniso_pixel_border + 1.0;
  1098. #else
  1099. static const float max_tiled_pixel_border = max_aniso_pixel_border;
  1100. #endif
  1101. // Convert the pixel border to an integer texel border. Assume same-pass
  1102. // curvature about triples the texel frequency:
  1103. #ifdef GEOMETRY_EARLY
  1104. static const float max_mask_texel_border =
  1105. ceil(max_tiled_pixel_border * 3.0);
  1106. #else
  1107. static const float max_mask_texel_border = ceil(max_tiled_pixel_border);
  1108. #endif
  1109. // Convert the texel border to a tile border using worst-case assumptions:
  1110. static const float max_mask_tile_border = max_mask_texel_border/
  1111. (mask_min_allowed_triad_size * mask_triads_per_tile);
  1112. // Finally, set the number of resized tiles to render to MASK_RESIZE, and set
  1113. // the starting texel (inside borders) for sampling it.
  1114. #ifndef GEOMETRY_EARLY
  1115. #ifdef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  1116. // Special case: Render two tiles without borders. Anisotropic
  1117. // filtering doesn't seem to be a problem here.
  1118. static const float mask_resize_num_tiles = 1.0 + 1.0;
  1119. static const float mask_start_texels = 0.0;
  1120. #else
  1121. static const float mask_resize_num_tiles = 1.0 +
  1122. 2.0 * max_mask_tile_border;
  1123. static const float mask_start_texels = max_mask_texel_border;
  1124. #endif
  1125. #else
  1126. static const float mask_resize_num_tiles = 1.0 + 2.0*max_mask_tile_border;
  1127. static const float mask_start_texels = max_mask_texel_border;
  1128. #endif
  1129. // We have to fit mask_resize_num_tiles into an FBO with a viewport scale of
  1130. // mask_resize_viewport_scale. This limits the maximum final triad size.
  1131. // Estimate the minimum number of triads we can split the screen into in each
  1132. // dimension (we'll be as correct as mask_resize_viewport_scale is):
  1133. static const float mask_resize_num_triads =
  1134. mask_resize_num_tiles * mask_triads_per_tile;
  1135. static const float2 min_allowed_viewport_triads =
  1136. float2(mask_resize_num_triads) / mask_resize_viewport_scale;
  1137. //////////////////////// COMMON MATHEMATICAL CONSTANTS ///////////////////////
  1138. static const float pi = 3.141592653589;
  1139. // We often want to find the location of the previous texel, e.g.:
  1140. // const float2 curr_texel = uv * texture_size;
  1141. // const float2 prev_texel = floor(curr_texel - float2(0.5)) + float2(0.5);
  1142. // const float2 prev_texel_uv = prev_texel / texture_size;
  1143. // However, many GPU drivers round incorrectly around exact texel locations.
  1144. // We need to subtract a little less than 0.5 before flooring, and some GPU's
  1145. // require this value to be farther from 0.5 than others; define it here.
  1146. // const float2 prev_texel =
  1147. // floor(curr_texel - float2(under_half)) + float2(0.5);
  1148. static const float under_half = 0.4995;
  1149. #endif // DERIVED_SETTINGS_AND_CONSTANTS_H
  1150. //////////////////// END DERIVED-SETTINGS-AND-CONSTANTS /////////////////////
  1151. //////////////////////////////// END INCLUDES ////////////////////////////////
  1152. // Override some parameters for gamma-management.h and tex2Dantialias.h:
  1153. #define OVERRIDE_DEVICE_GAMMA
  1154. static const float gba_gamma = 3.5; // Irrelevant but necessary to define.
  1155. #define ANTIALIAS_OVERRIDE_BASICS
  1156. #define ANTIALIAS_OVERRIDE_PARAMETERS
  1157. // Provide accessors for vector constants that pack scalar uniforms:
  1158. inline float2 get_aspect_vector(const float geom_aspect_ratio)
  1159. {
  1160. // Get an aspect ratio vector. Enforce geom_max_aspect_ratio, and prevent
  1161. // the absolute scale from affecting the uv-mapping for curvature:
  1162. const float geom_clamped_aspect_ratio =
  1163. min(geom_aspect_ratio, geom_max_aspect_ratio);
  1164. const float2 geom_aspect =
  1165. normalize(float2(geom_clamped_aspect_ratio, 1.0));
  1166. return geom_aspect;
  1167. }
  1168. inline float2 get_geom_overscan_vector()
  1169. {
  1170. return float2(geom_overscan_x, geom_overscan_y);
  1171. }
  1172. inline float2 get_geom_tilt_angle_vector()
  1173. {
  1174. return float2(geom_tilt_angle_x, geom_tilt_angle_y);
  1175. }
  1176. inline float3 get_convergence_offsets_x_vector()
  1177. {
  1178. return float3(convergence_offset_x_r, convergence_offset_x_g,
  1179. convergence_offset_x_b);
  1180. }
  1181. inline float3 get_convergence_offsets_y_vector()
  1182. {
  1183. return float3(convergence_offset_y_r, convergence_offset_y_g,
  1184. convergence_offset_y_b);
  1185. }
  1186. inline float2 get_convergence_offsets_r_vector()
  1187. {
  1188. return float2(convergence_offset_x_r, convergence_offset_y_r);
  1189. }
  1190. inline float2 get_convergence_offsets_g_vector()
  1191. {
  1192. return float2(convergence_offset_x_g, convergence_offset_y_g);
  1193. }
  1194. inline float2 get_convergence_offsets_b_vector()
  1195. {
  1196. return float2(convergence_offset_x_b, convergence_offset_y_b);
  1197. }
  1198. inline float2 get_aa_subpixel_r_offset()
  1199. {
  1200. #ifdef RUNTIME_ANTIALIAS_WEIGHTS
  1201. #ifdef RUNTIME_ANTIALIAS_SUBPIXEL_OFFSETS
  1202. // WARNING: THIS IS EXTREMELY EXPENSIVE.
  1203. return float2(aa_subpixel_r_offset_x_runtime,
  1204. aa_subpixel_r_offset_y_runtime);
  1205. #else
  1206. return aa_subpixel_r_offset_static;
  1207. #endif
  1208. #else
  1209. return aa_subpixel_r_offset_static;
  1210. #endif
  1211. }
  1212. // Provide accessors settings which still need "cooking:"
  1213. inline float get_mask_amplify()
  1214. {
  1215. static const float mask_grille_amplify = 1.0/mask_grille_avg_color;
  1216. static const float mask_slot_amplify = 1.0/mask_slot_avg_color;
  1217. static const float mask_shadow_amplify = 1.0/mask_shadow_avg_color;
  1218. return mask_type < 0.5 ? mask_grille_amplify :
  1219. mask_type < 1.5 ? mask_slot_amplify :
  1220. mask_shadow_amplify;
  1221. }
  1222. inline float get_mask_sample_mode()
  1223. {
  1224. #ifdef RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  1225. #ifdef PHOSPHOR_MASK_MANUALLY_RESIZE
  1226. return mask_sample_mode_desired;
  1227. #else
  1228. return clamp(mask_sample_mode_desired, 1.0, 2.0);
  1229. #endif
  1230. #else
  1231. #ifdef PHOSPHOR_MASK_MANUALLY_RESIZE
  1232. return mask_sample_mode_static;
  1233. #else
  1234. return clamp(mask_sample_mode_static, 1.0, 2.0);
  1235. #endif
  1236. #endif
  1237. }
  1238. #endif // BIND_SHADER_PARAMS_H
  1239. //////////////////////////// END BIND-SHADER-PARAMS ///////////////////////////
  1240. //#include "../../../../include/gamma-management.h"
  1241. //////////////////////////// BEGIN GAMMA-MANAGEMENT //////////////////////////
  1242. #ifndef GAMMA_MANAGEMENT_H
  1243. #define GAMMA_MANAGEMENT_H
  1244. ///////////////////////////////// MIT LICENSE ////////////////////////////////
  1245. // Copyright (C) 2014 TroggleMonkey
  1246. //
  1247. // Permission is hereby granted, free of charge, to any person obtaining a copy
  1248. // of this software and associated documentation files (the "Software"), to
  1249. // deal in the Software without restriction, including without limitation the
  1250. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  1251. // sell copies of the Software, and to permit persons to whom the Software is
  1252. // furnished to do so, subject to the following conditions:
  1253. //
  1254. // The above copyright notice and this permission notice shall be included in
  1255. // all copies or substantial portions of the Software.
  1256. //
  1257. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  1258. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  1259. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  1260. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  1261. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  1262. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  1263. // IN THE SOFTWARE.
  1264. ///////////////////////////////// DESCRIPTION ////////////////////////////////
  1265. // This file provides gamma-aware tex*D*() and encode_output() functions.
  1266. // Requires: Before #include-ing this file, the including file must #define
  1267. // the following macros when applicable and follow their rules:
  1268. // 1.) #define FIRST_PASS if this is the first pass.
  1269. // 2.) #define LAST_PASS if this is the last pass.
  1270. // 3.) If sRGB is available, set srgb_framebufferN = "true" for
  1271. // every pass except the last in your .cgp preset.
  1272. // 4.) If sRGB isn't available but you want gamma-correctness with
  1273. // no banding, #define GAMMA_ENCODE_EVERY_FBO each pass.
  1274. // 5.) #define SIMULATE_CRT_ON_LCD if desired (precedence over 5-7)
  1275. // 6.) #define SIMULATE_GBA_ON_LCD if desired (precedence over 6-7)
  1276. // 7.) #define SIMULATE_LCD_ON_CRT if desired (precedence over 7)
  1277. // 8.) #define SIMULATE_GBA_ON_CRT if desired (precedence over -)
  1278. // If an option in [5, 8] is #defined in the first or last pass, it
  1279. // should be #defined for both. It shouldn't make a difference
  1280. // whether it's #defined for intermediate passes or not.
  1281. // Optional: The including file (or an earlier included file) may optionally
  1282. // #define a number of macros indicating it will override certain
  1283. // macros and associated constants are as follows:
  1284. // static constants with either static or uniform constants. The
  1285. // 1.) OVERRIDE_STANDARD_GAMMA: The user must first define:
  1286. // static const float ntsc_gamma
  1287. // static const float pal_gamma
  1288. // static const float crt_reference_gamma_high
  1289. // static const float crt_reference_gamma_low
  1290. // static const float lcd_reference_gamma
  1291. // static const float crt_office_gamma
  1292. // static const float lcd_office_gamma
  1293. // 2.) OVERRIDE_DEVICE_GAMMA: The user must first define:
  1294. // static const float crt_gamma
  1295. // static const float gba_gamma
  1296. // static const float lcd_gamma
  1297. // 3.) OVERRIDE_FINAL_GAMMA: The user must first define:
  1298. // static const float input_gamma
  1299. // static const float intermediate_gamma
  1300. // static const float output_gamma
  1301. // (intermediate_gamma is for GAMMA_ENCODE_EVERY_FBO.)
  1302. // 4.) OVERRIDE_ALPHA_ASSUMPTIONS: The user must first define:
  1303. // static const bool assume_opaque_alpha
  1304. // The gamma constant overrides must be used in every pass or none,
  1305. // and OVERRIDE_FINAL_GAMMA bypasses all of the SIMULATE* macros.
  1306. // OVERRIDE_ALPHA_ASSUMPTIONS may be set on a per-pass basis.
  1307. // Usage: After setting macros appropriately, ignore gamma correction and
  1308. // replace all tex*D*() calls with equivalent gamma-aware
  1309. // tex*D*_linearize calls, except:
  1310. // 1.) When you read an LUT, use regular tex*D or a gamma-specified
  1311. // function, depending on its gamma encoding:
  1312. // tex*D*_linearize_gamma (takes a runtime gamma parameter)
  1313. // 2.) If you must read pass0's original input in a later pass, use
  1314. // tex2D_linearize_ntsc_gamma. If you want to read pass0's
  1315. // input with gamma-corrected bilinear filtering, consider
  1316. // creating a first linearizing pass and reading from the input
  1317. // of pass1 later.
  1318. // Then, return encode_output(color) from every fragment shader.
  1319. // Finally, use the global gamma_aware_bilinear boolean if you want
  1320. // to statically branch based on whether bilinear filtering is
  1321. // gamma-correct or not (e.g. for placing Gaussian blur samples).
  1322. //
  1323. // Detailed Policy:
  1324. // tex*D*_linearize() functions enforce a consistent gamma-management policy
  1325. // based on the FIRST_PASS and GAMMA_ENCODE_EVERY_FBO settings. They assume
  1326. // their input texture has the same encoding characteristics as the input for
  1327. // the current pass (which doesn't apply to the exceptions listed above).
  1328. // Similarly, encode_output() enforces a policy based on the LAST_PASS and
  1329. // GAMMA_ENCODE_EVERY_FBO settings. Together, they result in one of the
  1330. // following two pipelines.
  1331. // Typical pipeline with intermediate sRGB framebuffers:
  1332. // linear_color = pow(pass0_encoded_color, input_gamma);
  1333. // intermediate_output = linear_color; // Automatic sRGB encoding
  1334. // linear_color = intermediate_output; // Automatic sRGB decoding
  1335. // final_output = pow(intermediate_output, 1.0/output_gamma);
  1336. // Typical pipeline without intermediate sRGB framebuffers:
  1337. // linear_color = pow(pass0_encoded_color, input_gamma);
  1338. // intermediate_output = pow(linear_color, 1.0/intermediate_gamma);
  1339. // linear_color = pow(intermediate_output, intermediate_gamma);
  1340. // final_output = pow(intermediate_output, 1.0/output_gamma);
  1341. // Using GAMMA_ENCODE_EVERY_FBO is much slower, but it's provided as a way to
  1342. // easily get gamma-correctness without banding on devices where sRGB isn't
  1343. // supported.
  1344. //
  1345. // Use This Header to Maximize Code Reuse:
  1346. // The purpose of this header is to provide a consistent interface for texture
  1347. // reads and output gamma-encoding that localizes and abstracts away all the
  1348. // annoying details. This greatly reduces the amount of code in each shader
  1349. // pass that depends on the pass number in the .cgp preset or whether sRGB
  1350. // FBO's are being used: You can trivially change the gamma behavior of your
  1351. // whole pass by commenting or uncommenting 1-3 #defines. To reuse the same
  1352. // code in your first, Nth, and last passes, you can even put it all in another
  1353. // header file and #include it from skeleton .cg files that #define the
  1354. // appropriate pass-specific settings.
  1355. //
  1356. // Rationale for Using Three Macros:
  1357. // This file uses GAMMA_ENCODE_EVERY_FBO instead of an opposite macro like
  1358. // SRGB_PIPELINE to ensure sRGB is assumed by default, which hopefully imposes
  1359. // a lower maintenance burden on each pass. At first glance it seems we could
  1360. // accomplish everything with two macros: GAMMA_CORRECT_IN / GAMMA_CORRECT_OUT.
  1361. // This works for simple use cases where input_gamma == output_gamma, but it
  1362. // breaks down for more complex scenarios like CRT simulation, where the pass
  1363. // number determines the gamma encoding of the input and output.
  1364. /////////////////////////////// BASE CONSTANTS ///////////////////////////////
  1365. // Set standard gamma constants, but allow users to override them:
  1366. #ifndef OVERRIDE_STANDARD_GAMMA
  1367. // Standard encoding gammas:
  1368. static const float ntsc_gamma = 2.2; // Best to use NTSC for PAL too?
  1369. static const float pal_gamma = 2.8; // Never actually 2.8 in practice
  1370. // Typical device decoding gammas (only use for emulating devices):
  1371. // CRT/LCD reference gammas are higher than NTSC and Rec.709 video standard
  1372. // gammas: The standards purposely undercorrected for an analog CRT's
  1373. // assumed 2.5 reference display gamma to maintain contrast in assumed
  1374. // [dark] viewing conditions: http://www.poynton.com/PDFs/GammaFAQ.pdf
  1375. // These unstated assumptions about display gamma and perceptual rendering
  1376. // intent caused a lot of confusion, and more modern CRT's seemed to target
  1377. // NTSC 2.2 gamma with circuitry. LCD displays seem to have followed suit
  1378. // (they struggle near black with 2.5 gamma anyway), especially PC/laptop
  1379. // displays designed to view sRGB in bright environments. (Standards are
  1380. // also in flux again with BT.1886, but it's underspecified for displays.)
  1381. static const float crt_reference_gamma_high = 2.5; // In (2.35, 2.55)
  1382. static const float crt_reference_gamma_low = 2.35; // In (2.35, 2.55)
  1383. static const float lcd_reference_gamma = 2.5; // To match CRT
  1384. static const float crt_office_gamma = 2.2; // Circuitry-adjusted for NTSC
  1385. static const float lcd_office_gamma = 2.2; // Approximates sRGB
  1386. #endif // OVERRIDE_STANDARD_GAMMA
  1387. // Assuming alpha == 1.0 might make it easier for users to avoid some bugs,
  1388. // but only if they're aware of it.
  1389. #ifndef OVERRIDE_ALPHA_ASSUMPTIONS
  1390. static const bool assume_opaque_alpha = false;
  1391. #endif
  1392. /////////////////////// DERIVED CONSTANTS AS FUNCTIONS ///////////////////////
  1393. // gamma-management.h should be compatible with overriding gamma values with
  1394. // runtime user parameters, but we can only define other global constants in
  1395. // terms of static constants, not uniform user parameters. To get around this
  1396. // limitation, we need to define derived constants using functions.
  1397. // Set device gamma constants, but allow users to override them:
  1398. #ifdef OVERRIDE_DEVICE_GAMMA
  1399. // The user promises to globally define the appropriate constants:
  1400. inline float get_crt_gamma() { return crt_gamma; }
  1401. inline float get_gba_gamma() { return gba_gamma; }
  1402. inline float get_lcd_gamma() { return lcd_gamma; }
  1403. #else
  1404. inline float get_crt_gamma() { return crt_reference_gamma_high; }
  1405. inline float get_gba_gamma() { return 3.5; } // Game Boy Advance; in (3.0, 4.0)
  1406. inline float get_lcd_gamma() { return lcd_office_gamma; }
  1407. #endif // OVERRIDE_DEVICE_GAMMA
  1408. // Set decoding/encoding gammas for the first/lass passes, but allow overrides:
  1409. #ifdef OVERRIDE_FINAL_GAMMA
  1410. // The user promises to globally define the appropriate constants:
  1411. inline float get_intermediate_gamma() { return intermediate_gamma; }
  1412. inline float get_input_gamma() { return input_gamma; }
  1413. inline float get_output_gamma() { return output_gamma; }
  1414. #else
  1415. // If we gamma-correct every pass, always use ntsc_gamma between passes to
  1416. // ensure middle passes don't need to care if anything is being simulated:
  1417. inline float get_intermediate_gamma() { return ntsc_gamma; }
  1418. #ifdef SIMULATE_CRT_ON_LCD
  1419. inline float get_input_gamma() { return get_crt_gamma(); }
  1420. inline float get_output_gamma() { return get_lcd_gamma(); }
  1421. #else
  1422. #ifdef SIMULATE_GBA_ON_LCD
  1423. inline float get_input_gamma() { return get_gba_gamma(); }
  1424. inline float get_output_gamma() { return get_lcd_gamma(); }
  1425. #else
  1426. #ifdef SIMULATE_LCD_ON_CRT
  1427. inline float get_input_gamma() { return get_lcd_gamma(); }
  1428. inline float get_output_gamma() { return get_crt_gamma(); }
  1429. #else
  1430. #ifdef SIMULATE_GBA_ON_CRT
  1431. inline float get_input_gamma() { return get_gba_gamma(); }
  1432. inline float get_output_gamma() { return get_crt_gamma(); }
  1433. #else // Don't simulate anything:
  1434. inline float get_input_gamma() { return ntsc_gamma; }
  1435. inline float get_output_gamma() { return ntsc_gamma; }
  1436. #endif // SIMULATE_GBA_ON_CRT
  1437. #endif // SIMULATE_LCD_ON_CRT
  1438. #endif // SIMULATE_GBA_ON_LCD
  1439. #endif // SIMULATE_CRT_ON_LCD
  1440. #endif // OVERRIDE_FINAL_GAMMA
  1441. // Set decoding/encoding gammas for the current pass. Use static constants for
  1442. // linearize_input and gamma_encode_output, because they aren't derived, and
  1443. // they let the compiler do dead-code elimination.
  1444. #ifndef GAMMA_ENCODE_EVERY_FBO
  1445. #ifdef FIRST_PASS
  1446. static const bool linearize_input = true;
  1447. inline float get_pass_input_gamma() { return get_input_gamma(); }
  1448. #else
  1449. static const bool linearize_input = false;
  1450. inline float get_pass_input_gamma() { return 1.0; }
  1451. #endif
  1452. #ifdef LAST_PASS
  1453. static const bool gamma_encode_output = true;
  1454. inline float get_pass_output_gamma() { return get_output_gamma(); }
  1455. #else
  1456. static const bool gamma_encode_output = false;
  1457. inline float get_pass_output_gamma() { return 1.0; }
  1458. #endif
  1459. #else
  1460. static const bool linearize_input = true;
  1461. static const bool gamma_encode_output = true;
  1462. #ifdef FIRST_PASS
  1463. inline float get_pass_input_gamma() { return get_input_gamma(); }
  1464. #else
  1465. inline float get_pass_input_gamma() { return get_intermediate_gamma(); }
  1466. #endif
  1467. #ifdef LAST_PASS
  1468. inline float get_pass_output_gamma() { return get_output_gamma(); }
  1469. #else
  1470. inline float get_pass_output_gamma() { return get_intermediate_gamma(); }
  1471. #endif
  1472. #endif
  1473. // Users might want to know if bilinear filtering will be gamma-correct:
  1474. static const bool gamma_aware_bilinear = !linearize_input;
  1475. ////////////////////// COLOR ENCODING/DECODING FUNCTIONS /////////////////////
  1476. inline float4 encode_output(const float4 color)
  1477. {
  1478. if(gamma_encode_output)
  1479. {
  1480. if(assume_opaque_alpha)
  1481. {
  1482. return float4(pow(color.rgb, float3(1.0/get_pass_output_gamma())), 1.0);
  1483. }
  1484. else
  1485. {
  1486. return float4(pow(color.rgb, float3(1.0/get_pass_output_gamma())), color.a);
  1487. }
  1488. }
  1489. else
  1490. {
  1491. return color;
  1492. }
  1493. }
  1494. inline float4 decode_input(const float4 color)
  1495. {
  1496. if(linearize_input)
  1497. {
  1498. if(assume_opaque_alpha)
  1499. {
  1500. return float4(pow(color.rgb, float3(get_pass_input_gamma())), 1.0);
  1501. }
  1502. else
  1503. {
  1504. return float4(pow(color.rgb, float3(get_pass_input_gamma())), color.a);
  1505. }
  1506. }
  1507. else
  1508. {
  1509. return color;
  1510. }
  1511. }
  1512. inline float4 decode_gamma_input(const float4 color, const float3 gamma)
  1513. {
  1514. if(assume_opaque_alpha)
  1515. {
  1516. return float4(pow(color.rgb, gamma), 1.0);
  1517. }
  1518. else
  1519. {
  1520. return float4(pow(color.rgb, gamma), color.a);
  1521. }
  1522. }
  1523. //TODO/FIXME: I have no idea why replacing the lookup wrappers with this macro fixes the blurs being offset ¯\_(ツ)_/¯
  1524. //#define tex2D_linearize(C, D) decode_input(vec4(texture(C, D)))
  1525. // EDIT: it's the 'const' in front of the coords that's doing it
  1526. /////////////////////////// TEXTURE LOOKUP WRAPPERS //////////////////////////
  1527. // "SMART" LINEARIZING TEXTURE LOOKUP FUNCTIONS:
  1528. // Provide a wide array of linearizing texture lookup wrapper functions. The
  1529. // Cg shader spec Retroarch uses only allows for 2D textures, but 1D and 3D
  1530. // lookups are provided for completeness in case that changes someday. Nobody
  1531. // is likely to use the *fetch and *proj functions, but they're included just
  1532. // in case. The only tex*D texture sampling functions omitted are:
  1533. // - tex*Dcmpbias
  1534. // - tex*Dcmplod
  1535. // - tex*DARRAY*
  1536. // - tex*DMS*
  1537. // - Variants returning integers
  1538. // Standard line length restrictions are ignored below for vertical brevity.
  1539. /*
  1540. // tex1D:
  1541. inline float4 tex1D_linearize(const sampler1D tex, const float tex_coords)
  1542. { return decode_input(tex1D(tex, tex_coords)); }
  1543. inline float4 tex1D_linearize(const sampler1D tex, const float2 tex_coords)
  1544. { return decode_input(tex1D(tex, tex_coords)); }
  1545. inline float4 tex1D_linearize(const sampler1D tex, const float tex_coords, const int texel_off)
  1546. { return decode_input(tex1D(tex, tex_coords, texel_off)); }
  1547. inline float4 tex1D_linearize(const sampler1D tex, const float2 tex_coords, const int texel_off)
  1548. { return decode_input(tex1D(tex, tex_coords, texel_off)); }
  1549. inline float4 tex1D_linearize(const sampler1D tex, const float tex_coords, const float dx, const float dy)
  1550. { return decode_input(tex1D(tex, tex_coords, dx, dy)); }
  1551. inline float4 tex1D_linearize(const sampler1D tex, const float2 tex_coords, const float dx, const float dy)
  1552. { return decode_input(tex1D(tex, tex_coords, dx, dy)); }
  1553. inline float4 tex1D_linearize(const sampler1D tex, const float tex_coords, const float dx, const float dy, const int texel_off)
  1554. { return decode_input(tex1D(tex, tex_coords, dx, dy, texel_off)); }
  1555. inline float4 tex1D_linearize(const sampler1D tex, const float2 tex_coords, const float dx, const float dy, const int texel_off)
  1556. { return decode_input(tex1D(tex, tex_coords, dx, dy, texel_off)); }
  1557. // tex1Dbias:
  1558. inline float4 tex1Dbias_linearize(const sampler1D tex, const float4 tex_coords)
  1559. { return decode_input(tex1Dbias(tex, tex_coords)); }
  1560. inline float4 tex1Dbias_linearize(const sampler1D tex, const float4 tex_coords, const int texel_off)
  1561. { return decode_input(tex1Dbias(tex, tex_coords, texel_off)); }
  1562. // tex1Dfetch:
  1563. inline float4 tex1Dfetch_linearize(const sampler1D tex, const int4 tex_coords)
  1564. { return decode_input(tex1Dfetch(tex, tex_coords)); }
  1565. inline float4 tex1Dfetch_linearize(const sampler1D tex, const int4 tex_coords, const int texel_off)
  1566. { return decode_input(tex1Dfetch(tex, tex_coords, texel_off)); }
  1567. // tex1Dlod:
  1568. inline float4 tex1Dlod_linearize(const sampler1D tex, const float4 tex_coords)
  1569. { return decode_input(tex1Dlod(tex, tex_coords)); }
  1570. inline float4 tex1Dlod_linearize(const sampler1D tex, const float4 tex_coords, const int texel_off)
  1571. { return decode_input(tex1Dlod(tex, tex_coords, texel_off)); }
  1572. // tex1Dproj:
  1573. inline float4 tex1Dproj_linearize(const sampler1D tex, const float2 tex_coords)
  1574. { return decode_input(tex1Dproj(tex, tex_coords)); }
  1575. inline float4 tex1Dproj_linearize(const sampler1D tex, const float3 tex_coords)
  1576. { return decode_input(tex1Dproj(tex, tex_coords)); }
  1577. inline float4 tex1Dproj_linearize(const sampler1D tex, const float2 tex_coords, const int texel_off)
  1578. { return decode_input(tex1Dproj(tex, tex_coords, texel_off)); }
  1579. inline float4 tex1Dproj_linearize(const sampler1D tex, const float3 tex_coords, const int texel_off)
  1580. { return decode_input(tex1Dproj(tex, tex_coords, texel_off)); }
  1581. */
  1582. // tex2D:
  1583. inline float4 tex2D_linearize(const sampler2D tex, float2 tex_coords)
  1584. { return decode_input(COMPAT_TEXTURE(tex, tex_coords)); }
  1585. inline float4 tex2D_linearize(const sampler2D tex, float3 tex_coords)
  1586. { return decode_input(COMPAT_TEXTURE(tex, tex_coords.xy)); }
  1587. inline float4 tex2D_linearize(const sampler2D tex, float2 tex_coords, int texel_off)
  1588. { return decode_input(textureLod(tex, tex_coords, texel_off)); }
  1589. inline float4 tex2D_linearize(const sampler2D tex, float3 tex_coords, int texel_off)
  1590. { return decode_input(textureLod(tex, tex_coords.xy, texel_off)); }
  1591. //inline float4 tex2D_linearize(const sampler2D tex, const float2 tex_coords, const float2 dx, const float2 dy)
  1592. //{ return decode_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy)); }
  1593. //inline float4 tex2D_linearize(const sampler2D tex, const float3 tex_coords, const float2 dx, const float2 dy)
  1594. //{ return decode_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy)); }
  1595. //inline float4 tex2D_linearize(const sampler2D tex, const float2 tex_coords, const float2 dx, const float2 dy, const int texel_off)
  1596. //{ return decode_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy, texel_off)); }
  1597. //inline float4 tex2D_linearize(const sampler2D tex, const float3 tex_coords, const float2 dx, const float2 dy, const int texel_off)
  1598. //{ return decode_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy, texel_off)); }
  1599. // tex2Dbias:
  1600. //inline float4 tex2Dbias_linearize(const sampler2D tex, const float4 tex_coords)
  1601. //{ return decode_input(tex2Dbias(tex, tex_coords)); }
  1602. //inline float4 tex2Dbias_linearize(const sampler2D tex, const float4 tex_coords, const int texel_off)
  1603. //{ return decode_input(tex2Dbias(tex, tex_coords, texel_off)); }
  1604. // tex2Dfetch:
  1605. //inline float4 tex2Dfetch_linearize(const sampler2D tex, const int4 tex_coords)
  1606. //{ return decode_input(tex2Dfetch(tex, tex_coords)); }
  1607. //inline float4 tex2Dfetch_linearize(const sampler2D tex, const int4 tex_coords, const int texel_off)
  1608. //{ return decode_input(tex2Dfetch(tex, tex_coords, texel_off)); }
  1609. // tex2Dlod:
  1610. inline float4 tex2Dlod_linearize(const sampler2D tex, float4 tex_coords)
  1611. { return decode_input(textureLod(tex, tex_coords.xy, 0.0)); }
  1612. inline float4 tex2Dlod_linearize(const sampler2D tex, float4 tex_coords, int texel_off)
  1613. { return decode_input(textureLod(tex, tex_coords.xy, texel_off)); }
  1614. /*
  1615. // tex2Dproj:
  1616. inline float4 tex2Dproj_linearize(const sampler2D tex, const float3 tex_coords)
  1617. { return decode_input(tex2Dproj(tex, tex_coords)); }
  1618. inline float4 tex2Dproj_linearize(const sampler2D tex, const float4 tex_coords)
  1619. { return decode_input(tex2Dproj(tex, tex_coords)); }
  1620. inline float4 tex2Dproj_linearize(const sampler2D tex, const float3 tex_coords, const int texel_off)
  1621. { return decode_input(tex2Dproj(tex, tex_coords, texel_off)); }
  1622. inline float4 tex2Dproj_linearize(const sampler2D tex, const float4 tex_coords, const int texel_off)
  1623. { return decode_input(tex2Dproj(tex, tex_coords, texel_off)); }
  1624. */
  1625. /*
  1626. // tex3D:
  1627. inline float4 tex3D_linearize(const sampler3D tex, const float3 tex_coords)
  1628. { return decode_input(tex3D(tex, tex_coords)); }
  1629. inline float4 tex3D_linearize(const sampler3D tex, const float3 tex_coords, const int texel_off)
  1630. { return decode_input(tex3D(tex, tex_coords, texel_off)); }
  1631. inline float4 tex3D_linearize(const sampler3D tex, const float3 tex_coords, const float3 dx, const float3 dy)
  1632. { return decode_input(tex3D(tex, tex_coords, dx, dy)); }
  1633. inline float4 tex3D_linearize(const sampler3D tex, const float3 tex_coords, const float3 dx, const float3 dy, const int texel_off)
  1634. { return decode_input(tex3D(tex, tex_coords, dx, dy, texel_off)); }
  1635. // tex3Dbias:
  1636. inline float4 tex3Dbias_linearize(const sampler3D tex, const float4 tex_coords)
  1637. { return decode_input(tex3Dbias(tex, tex_coords)); }
  1638. inline float4 tex3Dbias_linearize(const sampler3D tex, const float4 tex_coords, const int texel_off)
  1639. { return decode_input(tex3Dbias(tex, tex_coords, texel_off)); }
  1640. // tex3Dfetch:
  1641. inline float4 tex3Dfetch_linearize(const sampler3D tex, const int4 tex_coords)
  1642. { return decode_input(tex3Dfetch(tex, tex_coords)); }
  1643. inline float4 tex3Dfetch_linearize(const sampler3D tex, const int4 tex_coords, const int texel_off)
  1644. { return decode_input(tex3Dfetch(tex, tex_coords, texel_off)); }
  1645. // tex3Dlod:
  1646. inline float4 tex3Dlod_linearize(const sampler3D tex, const float4 tex_coords)
  1647. { return decode_input(tex3Dlod(tex, tex_coords)); }
  1648. inline float4 tex3Dlod_linearize(const sampler3D tex, const float4 tex_coords, const int texel_off)
  1649. { return decode_input(tex3Dlod(tex, tex_coords, texel_off)); }
  1650. // tex3Dproj:
  1651. inline float4 tex3Dproj_linearize(const sampler3D tex, const float4 tex_coords)
  1652. { return decode_input(tex3Dproj(tex, tex_coords)); }
  1653. inline float4 tex3Dproj_linearize(const sampler3D tex, const float4 tex_coords, const int texel_off)
  1654. { return decode_input(tex3Dproj(tex, tex_coords, texel_off)); }
  1655. /////////*
  1656. // NONSTANDARD "SMART" LINEARIZING TEXTURE LOOKUP FUNCTIONS:
  1657. // This narrow selection of nonstandard tex2D* functions can be useful:
  1658. // tex2Dlod0: Automatically fill in the tex2D LOD parameter for mip level 0.
  1659. //inline float4 tex2Dlod0_linearize(const sampler2D tex, const float2 tex_coords)
  1660. //{ return decode_input(tex2Dlod(tex, float4(tex_coords, 0.0, 0.0))); }
  1661. //inline float4 tex2Dlod0_linearize(const sampler2D tex, const float2 tex_coords, const int texel_off)
  1662. //{ return decode_input(tex2Dlod(tex, float4(tex_coords, 0.0, 0.0), texel_off)); }
  1663. // MANUALLY LINEARIZING TEXTURE LOOKUP FUNCTIONS:
  1664. // Provide a narrower selection of tex2D* wrapper functions that decode an
  1665. // input sample with a specified gamma value. These are useful for reading
  1666. // LUT's and for reading the input of pass0 in a later pass.
  1667. // tex2D:
  1668. inline float4 tex2D_linearize_gamma(const sampler2D tex, const float2 tex_coords, const float3 gamma)
  1669. { return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords), gamma); }
  1670. inline float4 tex2D_linearize_gamma(const sampler2D tex, const float3 tex_coords, const float3 gamma)
  1671. { return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords.xy), gamma); }
  1672. //inline float4 tex2D_linearize_gamma(const sampler2D tex, const float2 tex_coords, const int texel_off, const float3 gamma)
  1673. //{ return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords, texel_off), gamma); }
  1674. //inline float4 tex2D_linearize_gamma(const sampler2D tex, const float3 tex_coords, const int texel_off, const float3 gamma)
  1675. //{ return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords, texel_off), gamma); }
  1676. //inline float4 tex2D_linearize_gamma(const sampler2D tex, const float2 tex_coords, const float2 dx, const float2 dy, const float3 gamma)
  1677. //{ return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy), gamma); }
  1678. //inline float4 tex2D_linearize_gamma(const sampler2D tex, const float3 tex_coords, const float2 dx, const float2 dy, const float3 gamma)
  1679. //{ return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy), gamma); }
  1680. //inline float4 tex2D_linearize_gamma(const sampler2D tex, const float2 tex_coords, const float2 dx, const float2 dy, const int texel_off, const float3 gamma)
  1681. //{ return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy, texel_off), gamma); }
  1682. //inline float4 tex2D_linearize_gamma(const sampler2D tex, const float3 tex_coords, const float2 dx, const float2 dy, const int texel_off, const float3 gamma)
  1683. //{ return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy, texel_off), gamma); }
  1684. /*
  1685. // tex2Dbias:
  1686. inline float4 tex2Dbias_linearize_gamma(const sampler2D tex, const float4 tex_coords, const float3 gamma)
  1687. { return decode_gamma_input(tex2Dbias(tex, tex_coords), gamma); }
  1688. inline float4 tex2Dbias_linearize_gamma(const sampler2D tex, const float4 tex_coords, const int texel_off, const float3 gamma)
  1689. { return decode_gamma_input(tex2Dbias(tex, tex_coords, texel_off), gamma); }
  1690. // tex2Dfetch:
  1691. inline float4 tex2Dfetch_linearize_gamma(const sampler2D tex, const int4 tex_coords, const float3 gamma)
  1692. { return decode_gamma_input(tex2Dfetch(tex, tex_coords), gamma); }
  1693. inline float4 tex2Dfetch_linearize_gamma(const sampler2D tex, const int4 tex_coords, const int texel_off, const float3 gamma)
  1694. { return decode_gamma_input(tex2Dfetch(tex, tex_coords, texel_off), gamma); }
  1695. */
  1696. // tex2Dlod:
  1697. inline float4 tex2Dlod_linearize_gamma(const sampler2D tex, float4 tex_coords, float3 gamma)
  1698. { return decode_gamma_input(textureLod(tex, tex_coords.xy, 0.0), gamma); }
  1699. inline float4 tex2Dlod_linearize_gamma(const sampler2D tex, float4 tex_coords, int texel_off, float3 gamma)
  1700. { return decode_gamma_input(textureLod(tex, tex_coords.xy, texel_off), gamma); }
  1701. #endif // GAMMA_MANAGEMENT_H
  1702. //////////////////////////// END GAMMA-MANAGEMENT //////////////////////////
  1703. //#include "scanline-functions.h"
  1704. ///////////////////////////// BEGIN SCANLINE-FUNCTIONS ////////////////////////////
  1705. #ifndef SCANLINE_FUNCTIONS_H
  1706. #define SCANLINE_FUNCTIONS_H
  1707. ///////////////////////////// GPL LICENSE NOTICE /////////////////////////////
  1708. // crt-royale: A full-featured CRT shader, with cheese.
  1709. // Copyright (C) 2014 TroggleMonkey <trogglemonkey@gmx.com>
  1710. //
  1711. // This program is free software; you can redistribute it and/or modify it
  1712. // under the terms of the GNU General Public License as published by the Free
  1713. // Software Foundation; either version 2 of the License, or any later version.
  1714. //
  1715. // This program is distributed in the hope that it will be useful, but WITHOUT
  1716. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  1717. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  1718. // more details.
  1719. //
  1720. // You should have received a copy of the GNU General Public License along with
  1721. // this program; if not, write to the Free Software Foundation, Inc., 59 Temple
  1722. // Place, Suite 330, Boston, MA 02111-1307 USA
  1723. /////////////////////////////// BEGIN INCLUDES ///////////////////////////////
  1724. //#include "../user-settings.h"
  1725. ///////////////////////////// BEGIN USER-SETTINGS ////////////////////////////
  1726. #ifndef USER_SETTINGS_H
  1727. #define USER_SETTINGS_H
  1728. ///////////////////////////// DRIVER CAPABILITIES ////////////////////////////
  1729. // The Cg compiler uses different "profiles" with different capabilities.
  1730. // This shader requires a Cg compilation profile >= arbfp1, but a few options
  1731. // require higher profiles like fp30 or fp40. The shader can't detect profile
  1732. // or driver capabilities, so instead you must comment or uncomment the lines
  1733. // below with "//" before "#define." Disable an option if you get compilation
  1734. // errors resembling those listed. Generally speaking, all of these options
  1735. // will run on nVidia cards, but only DRIVERS_ALLOW_TEX2DBIAS (if that) is
  1736. // likely to run on ATI/AMD, due to the Cg compiler's profile limitations.
  1737. // Derivatives: Unsupported on fp20, ps_1_1, ps_1_2, ps_1_3, and arbfp1.
  1738. // Among other things, derivatives help us fix anisotropic filtering artifacts
  1739. // with curved manually tiled phosphor mask coords. Related errors:
  1740. // error C3004: function "float2 ddx(float2);" not supported in this profile
  1741. // error C3004: function "float2 ddy(float2);" not supported in this profile
  1742. //#define DRIVERS_ALLOW_DERIVATIVES
  1743. // Fine derivatives: Unsupported on older ATI cards.
  1744. // Fine derivatives enable 2x2 fragment block communication, letting us perform
  1745. // fast single-pass blur operations. If your card uses coarse derivatives and
  1746. // these are enabled, blurs could look broken. Derivatives are a prerequisite.
  1747. #ifdef DRIVERS_ALLOW_DERIVATIVES
  1748. #define DRIVERS_ALLOW_FINE_DERIVATIVES
  1749. #endif
  1750. // Dynamic looping: Requires an fp30 or newer profile.
  1751. // This makes phosphor mask resampling faster in some cases. Related errors:
  1752. // error C5013: profile does not support "for" statements and "for" could not
  1753. // be unrolled
  1754. //#define DRIVERS_ALLOW_DYNAMIC_BRANCHES
  1755. // Without DRIVERS_ALLOW_DYNAMIC_BRANCHES, we need to use unrollable loops.
  1756. // Using one static loop avoids overhead if the user is right, but if the user
  1757. // is wrong (loops are allowed), breaking a loop into if-blocked pieces with a
  1758. // binary search can potentially save some iterations. However, it may fail:
  1759. // error C6001: Temporary register limit of 32 exceeded; 35 registers
  1760. // needed to compile program
  1761. //#define ACCOMODATE_POSSIBLE_DYNAMIC_LOOPS
  1762. // tex2Dlod: Requires an fp40 or newer profile. This can be used to disable
  1763. // anisotropic filtering, thereby fixing related artifacts. Related errors:
  1764. // error C3004: function "float4 tex2Dlod(sampler2D, float4);" not supported in
  1765. // this profile
  1766. //#define DRIVERS_ALLOW_TEX2DLOD
  1767. // tex2Dbias: Requires an fp30 or newer profile. This can be used to alleviate
  1768. // artifacts from anisotropic filtering and mipmapping. Related errors:
  1769. // error C3004: function "float4 tex2Dbias(sampler2D, float4);" not supported
  1770. // in this profile
  1771. //#define DRIVERS_ALLOW_TEX2DBIAS
  1772. // Integrated graphics compatibility: Integrated graphics like Intel HD 4000
  1773. // impose stricter limitations on register counts and instructions. Enable
  1774. // INTEGRATED_GRAPHICS_COMPATIBILITY_MODE if you still see error C6001 or:
  1775. // error C6002: Instruction limit of 1024 exceeded: 1523 instructions needed
  1776. // to compile program.
  1777. // Enabling integrated graphics compatibility mode will automatically disable:
  1778. // 1.) PHOSPHOR_MASK_MANUALLY_RESIZE: The phosphor mask will be softer.
  1779. // (This may be reenabled in a later release.)
  1780. // 2.) RUNTIME_GEOMETRY_MODE
  1781. // 3.) The high-quality 4x4 Gaussian resize for the bloom approximation
  1782. //#define INTEGRATED_GRAPHICS_COMPATIBILITY_MODE
  1783. //////////////////////////// USER CODEPATH OPTIONS ///////////////////////////
  1784. // To disable a #define option, turn its line into a comment with "//."
  1785. // RUNTIME VS. COMPILE-TIME OPTIONS (Major Performance Implications):
  1786. // Enable runtime shader parameters in the Retroarch (etc.) GUI? They override
  1787. // many of the options in this file and allow real-time tuning, but many of
  1788. // them are slower. Disabling them and using this text file will boost FPS.
  1789. #define RUNTIME_SHADER_PARAMS_ENABLE
  1790. // Specify the phosphor bloom sigma at runtime? This option is 10% slower, but
  1791. // it's the only way to do a wide-enough full bloom with a runtime dot pitch.
  1792. #define RUNTIME_PHOSPHOR_BLOOM_SIGMA
  1793. // Specify antialiasing weight parameters at runtime? (Costs ~20% with cubics)
  1794. #define RUNTIME_ANTIALIAS_WEIGHTS
  1795. // Specify subpixel offsets at runtime? (WARNING: EXTREMELY EXPENSIVE!)
  1796. //#define RUNTIME_ANTIALIAS_SUBPIXEL_OFFSETS
  1797. // Make beam_horiz_filter and beam_horiz_linear_rgb_weight into runtime shader
  1798. // parameters? This will require more math or dynamic branching.
  1799. #define RUNTIME_SCANLINES_HORIZ_FILTER_COLORSPACE
  1800. // Specify the tilt at runtime? This makes things about 3% slower.
  1801. #define RUNTIME_GEOMETRY_TILT
  1802. // Specify the geometry mode at runtime?
  1803. #define RUNTIME_GEOMETRY_MODE
  1804. // Specify the phosphor mask type (aperture grille, slot mask, shadow mask) and
  1805. // mode (Lanczos-resize, hardware resize, or tile 1:1) at runtime, even without
  1806. // dynamic branches? This is cheap if mask_resize_viewport_scale is small.
  1807. #define FORCE_RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  1808. // PHOSPHOR MASK:
  1809. // Manually resize the phosphor mask for best results (slower)? Disabling this
  1810. // removes the option to do so, but it may be faster without dynamic branches.
  1811. #define PHOSPHOR_MASK_MANUALLY_RESIZE
  1812. // If we sinc-resize the mask, should we Lanczos-window it (slower but better)?
  1813. #define PHOSPHOR_MASK_RESIZE_LANCZOS_WINDOW
  1814. // Larger blurs are expensive, but we need them to blur larger triads. We can
  1815. // detect the right blur if the triad size is static or our profile allows
  1816. // dynamic branches, but otherwise we use the largest blur the user indicates
  1817. // they might need:
  1818. #define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_3_PIXELS
  1819. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_6_PIXELS
  1820. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_9_PIXELS
  1821. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_12_PIXELS
  1822. // Here's a helpful chart:
  1823. // MaxTriadSize BlurSize MinTriadCountsByResolution
  1824. // 3.0 9.0 480/640/960/1920 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  1825. // 6.0 17.0 240/320/480/960 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  1826. // 9.0 25.0 160/213/320/640 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  1827. // 12.0 31.0 120/160/240/480 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  1828. // 18.0 43.0 80/107/160/320 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  1829. /////////////////////////////// USER PARAMETERS //////////////////////////////
  1830. // Note: Many of these static parameters are overridden by runtime shader
  1831. // parameters when those are enabled. However, many others are static codepath
  1832. // options that were cleaner or more convert to code as static constants.
  1833. // GAMMA:
  1834. static const float crt_gamma_static = 2.5; // range [1, 5]
  1835. static const float lcd_gamma_static = 2.2; // range [1, 5]
  1836. // LEVELS MANAGEMENT:
  1837. // Control the final multiplicative image contrast:
  1838. static const float levels_contrast_static = 1.0; // range [0, 4)
  1839. // We auto-dim to avoid clipping between passes and restore brightness
  1840. // later. Control the dim factor here: Lower values clip less but crush
  1841. // blacks more (static only for now).
  1842. static const float levels_autodim_temp = 0.5; // range (0, 1] default is 0.5 but that was unnecessarily dark for me, so I set it to 1.0
  1843. // HALATION/DIFFUSION/BLOOM:
  1844. // Halation weight: How much energy should be lost to electrons bounding
  1845. // around under the CRT glass and exciting random phosphors?
  1846. static const float halation_weight_static = 0.0; // range [0, 1]
  1847. // Refractive diffusion weight: How much light should spread/diffuse from
  1848. // refracting through the CRT glass?
  1849. static const float diffusion_weight_static = 0.075; // range [0, 1]
  1850. // Underestimate brightness: Bright areas bloom more, but we can base the
  1851. // bloom brightpass on a lower brightness to sharpen phosphors, or a higher
  1852. // brightness to soften them. Low values clip, but >= 0.8 looks okay.
  1853. static const float bloom_underestimate_levels_static = 0.8; // range [0, 5]
  1854. // Blur all colors more than necessary for a softer phosphor bloom?
  1855. static const float bloom_excess_static = 0.0; // range [0, 1]
  1856. // The BLOOM_APPROX pass approximates a phosphor blur early on with a small
  1857. // blurred resize of the input (convergence offsets are applied as well).
  1858. // There are three filter options (static option only for now):
  1859. // 0.) Bilinear resize: A fast, close approximation to a 4x4 resize
  1860. // if min_allowed_viewport_triads and the BLOOM_APPROX resolution are sane
  1861. // and beam_max_sigma is low.
  1862. // 1.) 3x3 resize blur: Medium speed, soft/smeared from bilinear blurring,
  1863. // always uses a static sigma regardless of beam_max_sigma or
  1864. // mask_num_triads_desired.
  1865. // 2.) True 4x4 Gaussian resize: Slowest, technically correct.
  1866. // These options are more pronounced for the fast, unbloomed shader version.
  1867. #ifndef RADEON_FIX
  1868. static const float bloom_approx_filter_static = 2.0;
  1869. #else
  1870. static const float bloom_approx_filter_static = 1.0;
  1871. #endif
  1872. // ELECTRON BEAM SCANLINE DISTRIBUTION:
  1873. // How many scanlines should contribute light to each pixel? Using more
  1874. // scanlines is slower (especially for a generalized Gaussian) but less
  1875. // distorted with larger beam sigmas (especially for a pure Gaussian). The
  1876. // max_beam_sigma at which the closest unused weight is guaranteed <
  1877. // 1.0/255.0 (for a 3x antialiased pure Gaussian) is:
  1878. // 2 scanlines: max_beam_sigma = 0.2089; distortions begin ~0.34; 141.7 FPS pure, 131.9 FPS generalized
  1879. // 3 scanlines, max_beam_sigma = 0.3879; distortions begin ~0.52; 137.5 FPS pure; 123.8 FPS generalized
  1880. // 4 scanlines, max_beam_sigma = 0.5723; distortions begin ~0.70; 134.7 FPS pure; 117.2 FPS generalized
  1881. // 5 scanlines, max_beam_sigma = 0.7591; distortions begin ~0.89; 131.6 FPS pure; 112.1 FPS generalized
  1882. // 6 scanlines, max_beam_sigma = 0.9483; distortions begin ~1.08; 127.9 FPS pure; 105.6 FPS generalized
  1883. static const float beam_num_scanlines = 3.0; // range [2, 6]
  1884. // A generalized Gaussian beam varies shape with color too, now just width.
  1885. // It's slower but more flexible (static option only for now).
  1886. static const bool beam_generalized_gaussian = true;
  1887. // What kind of scanline antialiasing do you want?
  1888. // 0: Sample weights at 1x; 1: Sample weights at 3x; 2: Compute an integral
  1889. // Integrals are slow (especially for generalized Gaussians) and rarely any
  1890. // better than 3x antialiasing (static option only for now).
  1891. static const float beam_antialias_level = 1.0; // range [0, 2]
  1892. // Min/max standard deviations for scanline beams: Higher values widen and
  1893. // soften scanlines. Depending on other options, low min sigmas can alias.
  1894. static const float beam_min_sigma_static = 0.02; // range (0, 1]
  1895. static const float beam_max_sigma_static = 0.3; // range (0, 1]
  1896. // Beam width varies as a function of color: A power function (0) is more
  1897. // configurable, but a spherical function (1) gives the widest beam
  1898. // variability without aliasing (static option only for now).
  1899. static const float beam_spot_shape_function = 0.0;
  1900. // Spot shape power: Powers <= 1 give smoother spot shapes but lower
  1901. // sharpness. Powers >= 1.0 are awful unless mix/max sigmas are close.
  1902. static const float beam_spot_power_static = 1.0/3.0; // range (0, 16]
  1903. // Generalized Gaussian max shape parameters: Higher values give flatter
  1904. // scanline plateaus and steeper dropoffs, simultaneously widening and
  1905. // sharpening scanlines at the cost of aliasing. 2.0 is pure Gaussian, and
  1906. // values > ~40.0 cause artifacts with integrals.
  1907. static const float beam_min_shape_static = 2.0; // range [2, 32]
  1908. static const float beam_max_shape_static = 4.0; // range [2, 32]
  1909. // Generalized Gaussian shape power: Affects how quickly the distribution
  1910. // changes shape from Gaussian to steep/plateaued as color increases from 0
  1911. // to 1.0. Higher powers appear softer for most colors, and lower powers
  1912. // appear sharper for most colors.
  1913. static const float beam_shape_power_static = 1.0/4.0; // range (0, 16]
  1914. // What filter should be used to sample scanlines horizontally?
  1915. // 0: Quilez (fast), 1: Gaussian (configurable), 2: Lanczos2 (sharp)
  1916. static const float beam_horiz_filter_static = 0.0;
  1917. // Standard deviation for horizontal Gaussian resampling:
  1918. static const float beam_horiz_sigma_static = 0.35; // range (0, 2/3]
  1919. // Do horizontal scanline sampling in linear RGB (correct light mixing),
  1920. // gamma-encoded RGB (darker, hard spot shape, may better match bandwidth-
  1921. // limiting circuitry in some CRT's), or a weighted avg.?
  1922. static const float beam_horiz_linear_rgb_weight_static = 1.0; // range [0, 1]
  1923. // Simulate scanline misconvergence? This needs 3x horizontal texture
  1924. // samples and 3x texture samples of BLOOM_APPROX and HALATION_BLUR in
  1925. // later passes (static option only for now).
  1926. static const bool beam_misconvergence = true;
  1927. // Convergence offsets in x/y directions for R/G/B scanline beams in units
  1928. // of scanlines. Positive offsets go right/down; ranges [-2, 2]
  1929. static const float2 convergence_offsets_r_static = float2(0.1, 0.2);
  1930. static const float2 convergence_offsets_g_static = float2(0.3, 0.4);
  1931. static const float2 convergence_offsets_b_static = float2(0.5, 0.6);
  1932. // Detect interlacing (static option only for now)?
  1933. static const bool interlace_detect = true;
  1934. // Assume 1080-line sources are interlaced?
  1935. static const bool interlace_1080i_static = false;
  1936. // For interlaced sources, assume TFF (top-field first) or BFF order?
  1937. // (Whether this matters depends on the nature of the interlaced input.)
  1938. static const bool interlace_bff_static = false;
  1939. // ANTIALIASING:
  1940. // What AA level do you want for curvature/overscan/subpixels? Options:
  1941. // 0x (none), 1x (sample subpixels), 4x, 5x, 6x, 7x, 8x, 12x, 16x, 20x, 24x
  1942. // (Static option only for now)
  1943. static const float aa_level = 12.0; // range [0, 24]
  1944. // What antialiasing filter do you want (static option only)? Options:
  1945. // 0: Box (separable), 1: Box (cylindrical),
  1946. // 2: Tent (separable), 3: Tent (cylindrical),
  1947. // 4: Gaussian (separable), 5: Gaussian (cylindrical),
  1948. // 6: Cubic* (separable), 7: Cubic* (cylindrical, poor)
  1949. // 8: Lanczos Sinc (separable), 9: Lanczos Jinc (cylindrical, poor)
  1950. // * = Especially slow with RUNTIME_ANTIALIAS_WEIGHTS
  1951. static const float aa_filter = 6.0; // range [0, 9]
  1952. // Flip the sample grid on odd/even frames (static option only for now)?
  1953. static const bool aa_temporal = false;
  1954. // Use RGB subpixel offsets for antialiasing? The pixel is at green, and
  1955. // the blue offset is the negative r offset; range [0, 0.5]
  1956. static const float2 aa_subpixel_r_offset_static = float2(-1.0/3.0, 0.0);//float2(0.0);
  1957. // Cubics: See http://www.imagemagick.org/Usage/filter/#mitchell
  1958. // 1.) "Keys cubics" with B = 1 - 2C are considered the highest quality.
  1959. // 2.) C = 0.5 (default) is Catmull-Rom; higher C's apply sharpening.
  1960. // 3.) C = 1.0/3.0 is the Mitchell-Netravali filter.
  1961. // 4.) C = 0.0 is a soft spline filter.
  1962. static const float aa_cubic_c_static = 0.5; // range [0, 4]
  1963. // Standard deviation for Gaussian antialiasing: Try 0.5/aa_pixel_diameter.
  1964. static const float aa_gauss_sigma_static = 0.5; // range [0.0625, 1.0]
  1965. // PHOSPHOR MASK:
  1966. // Mask type: 0 = aperture grille, 1 = slot mask, 2 = EDP shadow mask
  1967. static const float mask_type_static = 1.0; // range [0, 2]
  1968. // We can sample the mask three ways. Pick 2/3 from: Pretty/Fast/Flexible.
  1969. // 0.) Sinc-resize to the desired dot pitch manually (pretty/slow/flexible).
  1970. // This requires PHOSPHOR_MASK_MANUALLY_RESIZE to be #defined.
  1971. // 1.) Hardware-resize to the desired dot pitch (ugly/fast/flexible). This
  1972. // is halfway decent with LUT mipmapping but atrocious without it.
  1973. // 2.) Tile it without resizing at a 1:1 texel:pixel ratio for flat coords
  1974. // (pretty/fast/inflexible). Each input LUT has a fixed dot pitch.
  1975. // This mode reuses the same masks, so triads will be enormous unless
  1976. // you change the mask LUT filenames in your .cgp file.
  1977. static const float mask_sample_mode_static = 0.0; // range [0, 2]
  1978. // Prefer setting the triad size (0.0) or number on the screen (1.0)?
  1979. // If RUNTIME_PHOSPHOR_BLOOM_SIGMA isn't #defined, the specified triad size
  1980. // will always be used to calculate the full bloom sigma statically.
  1981. static const float mask_specify_num_triads_static = 0.0; // range [0, 1]
  1982. // Specify the phosphor triad size, in pixels. Each tile (usually with 8
  1983. // triads) will be rounded to the nearest integer tile size and clamped to
  1984. // obey minimum size constraints (imposed to reduce downsize taps) and
  1985. // maximum size constraints (imposed to have a sane MASK_RESIZE FBO size).
  1986. // To increase the size limit, double the viewport-relative scales for the
  1987. // two MASK_RESIZE passes in crt-royale.cgp and user-cgp-contants.h.
  1988. // range [1, mask_texture_small_size/mask_triads_per_tile]
  1989. static const float mask_triad_size_desired_static = 24.0 / 8.0;
  1990. // If mask_specify_num_triads is 1.0/true, we'll go by this instead (the
  1991. // final size will be rounded and constrained as above); default 480.0
  1992. static const float mask_num_triads_desired_static = 480.0;
  1993. // How many lobes should the sinc/Lanczos resizer use? More lobes require
  1994. // more samples and avoid moire a bit better, but some is unavoidable
  1995. // depending on the destination size (static option for now).
  1996. static const float mask_sinc_lobes = 3.0; // range [2, 4]
  1997. // The mask is resized using a variable number of taps in each dimension,
  1998. // but some Cg profiles always fetch a constant number of taps no matter
  1999. // what (no dynamic branching). We can limit the maximum number of taps if
  2000. // we statically limit the minimum phosphor triad size. Larger values are
  2001. // faster, but the limit IS enforced (static option only, forever);
  2002. // range [1, mask_texture_small_size/mask_triads_per_tile]
  2003. // TODO: Make this 1.0 and compensate with smarter sampling!
  2004. static const float mask_min_allowed_triad_size = 2.0;
  2005. // GEOMETRY:
  2006. // Geometry mode:
  2007. // 0: Off (default), 1: Spherical mapping (like cgwg's),
  2008. // 2: Alt. spherical mapping (more bulbous), 3: Cylindrical/Trinitron
  2009. static const float geom_mode_static = 0.0; // range [0, 3]
  2010. // Radius of curvature: Measured in units of your viewport's diagonal size.
  2011. static const float geom_radius_static = 2.0; // range [1/(2*pi), 1024]
  2012. // View dist is the distance from the player to their physical screen, in
  2013. // units of the viewport's diagonal size. It controls the field of view.
  2014. static const float geom_view_dist_static = 2.0; // range [0.5, 1024]
  2015. // Tilt angle in radians (clockwise around up and right vectors):
  2016. static const float2 geom_tilt_angle_static = float2(0.0, 0.0); // range [-pi, pi]
  2017. // Aspect ratio: When the true viewport size is unknown, this value is used
  2018. // to help convert between the phosphor triad size and count, along with
  2019. // the mask_resize_viewport_scale constant from user-cgp-constants.h. Set
  2020. // this equal to Retroarch's display aspect ratio (DAR) for best results;
  2021. // range [1, geom_max_aspect_ratio from user-cgp-constants.h];
  2022. // default (256/224)*(54/47) = 1.313069909 (see below)
  2023. static const float geom_aspect_ratio_static = 1.313069909;
  2024. // Before getting into overscan, here's some general aspect ratio info:
  2025. // - DAR = display aspect ratio = SAR * PAR; as in your Retroarch setting
  2026. // - SAR = storage aspect ratio = DAR / PAR; square pixel emulator frame AR
  2027. // - PAR = pixel aspect ratio = DAR / SAR; holds regardless of cropping
  2028. // Geometry processing has to "undo" the screen-space 2D DAR to calculate
  2029. // 3D view vectors, then reapplies the aspect ratio to the simulated CRT in
  2030. // uv-space. To ensure the source SAR is intended for a ~4:3 DAR, either:
  2031. // a.) Enable Retroarch's "Crop Overscan"
  2032. // b.) Readd horizontal padding: Set overscan to e.g. N*(1.0, 240.0/224.0)
  2033. // Real consoles use horizontal black padding in the signal, but emulators
  2034. // often crop this without cropping the vertical padding; a 256x224 [S]NES
  2035. // frame (8:7 SAR) is intended for a ~4:3 DAR, but a 256x240 frame is not.
  2036. // The correct [S]NES PAR is 54:47, found by blargg and NewRisingSun:
  2037. // http://board.zsnes.com/phpBB3/viewtopic.php?f=22&t=11928&start=50
  2038. // http://forums.nesdev.com/viewtopic.php?p=24815#p24815
  2039. // For flat output, it's okay to set DAR = [existing] SAR * [correct] PAR
  2040. // without doing a. or b., but horizontal image borders will be tighter
  2041. // than vertical ones, messing up curvature and overscan. Fixing the
  2042. // padding first corrects this.
  2043. // Overscan: Amount to "zoom in" before cropping. You can zoom uniformly
  2044. // or adjust x/y independently to e.g. readd horizontal padding, as noted
  2045. // above: Values < 1.0 zoom out; range (0, inf)
  2046. static const float2 geom_overscan_static = float2(1.0, 1.0);// * 1.005 * (1.0, 240/224.0)
  2047. // Compute a proper pixel-space to texture-space matrix even without ddx()/
  2048. // ddy()? This is ~8.5% slower but improves antialiasing/subpixel filtering
  2049. // with strong curvature (static option only for now).
  2050. static const bool geom_force_correct_tangent_matrix = true;
  2051. // BORDERS:
  2052. // Rounded border size in texture uv coords:
  2053. static const float border_size_static = 0.015; // range [0, 0.5]
  2054. // Border darkness: Moderate values darken the border smoothly, and high
  2055. // values make the image very dark just inside the border:
  2056. static const float border_darkness_static = 2.0; // range [0, inf)
  2057. // Border compression: High numbers compress border transitions, narrowing
  2058. // the dark border area.
  2059. static const float border_compress_static = 2.5; // range [1, inf)
  2060. #endif // USER_SETTINGS_H
  2061. //////////////////////////// END USER-SETTINGS //////////////////////////
  2062. //#include "derived-settings-and-constants.h"
  2063. //////////////////// BEGIN DERIVED-SETTINGS-AND-CONSTANTS ////////////////////
  2064. #ifndef DERIVED_SETTINGS_AND_CONSTANTS_H
  2065. #define DERIVED_SETTINGS_AND_CONSTANTS_H
  2066. ///////////////////////////// GPL LICENSE NOTICE /////////////////////////////
  2067. // crt-royale: A full-featured CRT shader, with cheese.
  2068. // Copyright (C) 2014 TroggleMonkey <trogglemonkey@gmx.com>
  2069. //
  2070. // This program is free software; you can redistribute it and/or modify it
  2071. // under the terms of the GNU General Public License as published by the Free
  2072. // Software Foundation; either version 2 of the License, or any later version.
  2073. //
  2074. // This program is distributed in the hope that it will be useful, but WITHOUT
  2075. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  2076. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  2077. // more details.
  2078. //
  2079. // You should have received a copy of the GNU General Public License along with
  2080. // this program; if not, write to the Free Software Foundation, Inc., 59 Temple
  2081. // Place, Suite 330, Boston, MA 02111-1307 USA
  2082. ///////////////////////////////// DESCRIPTION ////////////////////////////////
  2083. // These macros and constants can be used across the whole codebase.
  2084. // Unlike the values in user-settings.cgh, end users shouldn't modify these.
  2085. /////////////////////////////// BEGIN INCLUDES ///////////////////////////////
  2086. //#include "../user-settings.h"
  2087. ///////////////////////////// BEGIN USER-SETTINGS ////////////////////////////
  2088. #ifndef USER_SETTINGS_H
  2089. #define USER_SETTINGS_H
  2090. ///////////////////////////// DRIVER CAPABILITIES ////////////////////////////
  2091. // The Cg compiler uses different "profiles" with different capabilities.
  2092. // This shader requires a Cg compilation profile >= arbfp1, but a few options
  2093. // require higher profiles like fp30 or fp40. The shader can't detect profile
  2094. // or driver capabilities, so instead you must comment or uncomment the lines
  2095. // below with "//" before "#define." Disable an option if you get compilation
  2096. // errors resembling those listed. Generally speaking, all of these options
  2097. // will run on nVidia cards, but only DRIVERS_ALLOW_TEX2DBIAS (if that) is
  2098. // likely to run on ATI/AMD, due to the Cg compiler's profile limitations.
  2099. // Derivatives: Unsupported on fp20, ps_1_1, ps_1_2, ps_1_3, and arbfp1.
  2100. // Among other things, derivatives help us fix anisotropic filtering artifacts
  2101. // with curved manually tiled phosphor mask coords. Related errors:
  2102. // error C3004: function "float2 ddx(float2);" not supported in this profile
  2103. // error C3004: function "float2 ddy(float2);" not supported in this profile
  2104. //#define DRIVERS_ALLOW_DERIVATIVES
  2105. // Fine derivatives: Unsupported on older ATI cards.
  2106. // Fine derivatives enable 2x2 fragment block communication, letting us perform
  2107. // fast single-pass blur operations. If your card uses coarse derivatives and
  2108. // these are enabled, blurs could look broken. Derivatives are a prerequisite.
  2109. #ifdef DRIVERS_ALLOW_DERIVATIVES
  2110. #define DRIVERS_ALLOW_FINE_DERIVATIVES
  2111. #endif
  2112. // Dynamic looping: Requires an fp30 or newer profile.
  2113. // This makes phosphor mask resampling faster in some cases. Related errors:
  2114. // error C5013: profile does not support "for" statements and "for" could not
  2115. // be unrolled
  2116. //#define DRIVERS_ALLOW_DYNAMIC_BRANCHES
  2117. // Without DRIVERS_ALLOW_DYNAMIC_BRANCHES, we need to use unrollable loops.
  2118. // Using one static loop avoids overhead if the user is right, but if the user
  2119. // is wrong (loops are allowed), breaking a loop into if-blocked pieces with a
  2120. // binary search can potentially save some iterations. However, it may fail:
  2121. // error C6001: Temporary register limit of 32 exceeded; 35 registers
  2122. // needed to compile program
  2123. //#define ACCOMODATE_POSSIBLE_DYNAMIC_LOOPS
  2124. // tex2Dlod: Requires an fp40 or newer profile. This can be used to disable
  2125. // anisotropic filtering, thereby fixing related artifacts. Related errors:
  2126. // error C3004: function "float4 tex2Dlod(sampler2D, float4);" not supported in
  2127. // this profile
  2128. //#define DRIVERS_ALLOW_TEX2DLOD
  2129. // tex2Dbias: Requires an fp30 or newer profile. This can be used to alleviate
  2130. // artifacts from anisotropic filtering and mipmapping. Related errors:
  2131. // error C3004: function "float4 tex2Dbias(sampler2D, float4);" not supported
  2132. // in this profile
  2133. //#define DRIVERS_ALLOW_TEX2DBIAS
  2134. // Integrated graphics compatibility: Integrated graphics like Intel HD 4000
  2135. // impose stricter limitations on register counts and instructions. Enable
  2136. // INTEGRATED_GRAPHICS_COMPATIBILITY_MODE if you still see error C6001 or:
  2137. // error C6002: Instruction limit of 1024 exceeded: 1523 instructions needed
  2138. // to compile program.
  2139. // Enabling integrated graphics compatibility mode will automatically disable:
  2140. // 1.) PHOSPHOR_MASK_MANUALLY_RESIZE: The phosphor mask will be softer.
  2141. // (This may be reenabled in a later release.)
  2142. // 2.) RUNTIME_GEOMETRY_MODE
  2143. // 3.) The high-quality 4x4 Gaussian resize for the bloom approximation
  2144. //#define INTEGRATED_GRAPHICS_COMPATIBILITY_MODE
  2145. //////////////////////////// USER CODEPATH OPTIONS ///////////////////////////
  2146. // To disable a #define option, turn its line into a comment with "//."
  2147. // RUNTIME VS. COMPILE-TIME OPTIONS (Major Performance Implications):
  2148. // Enable runtime shader parameters in the Retroarch (etc.) GUI? They override
  2149. // many of the options in this file and allow real-time tuning, but many of
  2150. // them are slower. Disabling them and using this text file will boost FPS.
  2151. #define RUNTIME_SHADER_PARAMS_ENABLE
  2152. // Specify the phosphor bloom sigma at runtime? This option is 10% slower, but
  2153. // it's the only way to do a wide-enough full bloom with a runtime dot pitch.
  2154. #define RUNTIME_PHOSPHOR_BLOOM_SIGMA
  2155. // Specify antialiasing weight parameters at runtime? (Costs ~20% with cubics)
  2156. #define RUNTIME_ANTIALIAS_WEIGHTS
  2157. // Specify subpixel offsets at runtime? (WARNING: EXTREMELY EXPENSIVE!)
  2158. //#define RUNTIME_ANTIALIAS_SUBPIXEL_OFFSETS
  2159. // Make beam_horiz_filter and beam_horiz_linear_rgb_weight into runtime shader
  2160. // parameters? This will require more math or dynamic branching.
  2161. #define RUNTIME_SCANLINES_HORIZ_FILTER_COLORSPACE
  2162. // Specify the tilt at runtime? This makes things about 3% slower.
  2163. #define RUNTIME_GEOMETRY_TILT
  2164. // Specify the geometry mode at runtime?
  2165. #define RUNTIME_GEOMETRY_MODE
  2166. // Specify the phosphor mask type (aperture grille, slot mask, shadow mask) and
  2167. // mode (Lanczos-resize, hardware resize, or tile 1:1) at runtime, even without
  2168. // dynamic branches? This is cheap if mask_resize_viewport_scale is small.
  2169. #define FORCE_RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  2170. // PHOSPHOR MASK:
  2171. // Manually resize the phosphor mask for best results (slower)? Disabling this
  2172. // removes the option to do so, but it may be faster without dynamic branches.
  2173. #define PHOSPHOR_MASK_MANUALLY_RESIZE
  2174. // If we sinc-resize the mask, should we Lanczos-window it (slower but better)?
  2175. #define PHOSPHOR_MASK_RESIZE_LANCZOS_WINDOW
  2176. // Larger blurs are expensive, but we need them to blur larger triads. We can
  2177. // detect the right blur if the triad size is static or our profile allows
  2178. // dynamic branches, but otherwise we use the largest blur the user indicates
  2179. // they might need:
  2180. #define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_3_PIXELS
  2181. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_6_PIXELS
  2182. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_9_PIXELS
  2183. //#define PHOSPHOR_BLOOM_TRIADS_LARGER_THAN_12_PIXELS
  2184. // Here's a helpful chart:
  2185. // MaxTriadSize BlurSize MinTriadCountsByResolution
  2186. // 3.0 9.0 480/640/960/1920 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  2187. // 6.0 17.0 240/320/480/960 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  2188. // 9.0 25.0 160/213/320/640 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  2189. // 12.0 31.0 120/160/240/480 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  2190. // 18.0 43.0 80/107/160/320 triads at 1080p/1440p/2160p/4320p, 4:3 aspect
  2191. /////////////////////////////// USER PARAMETERS //////////////////////////////
  2192. // Note: Many of these static parameters are overridden by runtime shader
  2193. // parameters when those are enabled. However, many others are static codepath
  2194. // options that were cleaner or more convert to code as static constants.
  2195. // GAMMA:
  2196. static const float crt_gamma_static = 2.5; // range [1, 5]
  2197. static const float lcd_gamma_static = 2.2; // range [1, 5]
  2198. // LEVELS MANAGEMENT:
  2199. // Control the final multiplicative image contrast:
  2200. static const float levels_contrast_static = 1.0; // range [0, 4)
  2201. // We auto-dim to avoid clipping between passes and restore brightness
  2202. // later. Control the dim factor here: Lower values clip less but crush
  2203. // blacks more (static only for now).
  2204. static const float levels_autodim_temp = 0.5; // range (0, 1] default is 0.5 but that was unnecessarily dark for me, so I set it to 1.0
  2205. // HALATION/DIFFUSION/BLOOM:
  2206. // Halation weight: How much energy should be lost to electrons bounding
  2207. // around under the CRT glass and exciting random phosphors?
  2208. static const float halation_weight_static = 0.0; // range [0, 1]
  2209. // Refractive diffusion weight: How much light should spread/diffuse from
  2210. // refracting through the CRT glass?
  2211. static const float diffusion_weight_static = 0.075; // range [0, 1]
  2212. // Underestimate brightness: Bright areas bloom more, but we can base the
  2213. // bloom brightpass on a lower brightness to sharpen phosphors, or a higher
  2214. // brightness to soften them. Low values clip, but >= 0.8 looks okay.
  2215. static const float bloom_underestimate_levels_static = 0.8; // range [0, 5]
  2216. // Blur all colors more than necessary for a softer phosphor bloom?
  2217. static const float bloom_excess_static = 0.0; // range [0, 1]
  2218. // The BLOOM_APPROX pass approximates a phosphor blur early on with a small
  2219. // blurred resize of the input (convergence offsets are applied as well).
  2220. // There are three filter options (static option only for now):
  2221. // 0.) Bilinear resize: A fast, close approximation to a 4x4 resize
  2222. // if min_allowed_viewport_triads and the BLOOM_APPROX resolution are sane
  2223. // and beam_max_sigma is low.
  2224. // 1.) 3x3 resize blur: Medium speed, soft/smeared from bilinear blurring,
  2225. // always uses a static sigma regardless of beam_max_sigma or
  2226. // mask_num_triads_desired.
  2227. // 2.) True 4x4 Gaussian resize: Slowest, technically correct.
  2228. // These options are more pronounced for the fast, unbloomed shader version.
  2229. #ifndef RADEON_FIX
  2230. static const float bloom_approx_filter_static = 2.0;
  2231. #else
  2232. static const float bloom_approx_filter_static = 1.0;
  2233. #endif
  2234. // ELECTRON BEAM SCANLINE DISTRIBUTION:
  2235. // How many scanlines should contribute light to each pixel? Using more
  2236. // scanlines is slower (especially for a generalized Gaussian) but less
  2237. // distorted with larger beam sigmas (especially for a pure Gaussian). The
  2238. // max_beam_sigma at which the closest unused weight is guaranteed <
  2239. // 1.0/255.0 (for a 3x antialiased pure Gaussian) is:
  2240. // 2 scanlines: max_beam_sigma = 0.2089; distortions begin ~0.34; 141.7 FPS pure, 131.9 FPS generalized
  2241. // 3 scanlines, max_beam_sigma = 0.3879; distortions begin ~0.52; 137.5 FPS pure; 123.8 FPS generalized
  2242. // 4 scanlines, max_beam_sigma = 0.5723; distortions begin ~0.70; 134.7 FPS pure; 117.2 FPS generalized
  2243. // 5 scanlines, max_beam_sigma = 0.7591; distortions begin ~0.89; 131.6 FPS pure; 112.1 FPS generalized
  2244. // 6 scanlines, max_beam_sigma = 0.9483; distortions begin ~1.08; 127.9 FPS pure; 105.6 FPS generalized
  2245. static const float beam_num_scanlines = 3.0; // range [2, 6]
  2246. // A generalized Gaussian beam varies shape with color too, now just width.
  2247. // It's slower but more flexible (static option only for now).
  2248. static const bool beam_generalized_gaussian = true;
  2249. // What kind of scanline antialiasing do you want?
  2250. // 0: Sample weights at 1x; 1: Sample weights at 3x; 2: Compute an integral
  2251. // Integrals are slow (especially for generalized Gaussians) and rarely any
  2252. // better than 3x antialiasing (static option only for now).
  2253. static const float beam_antialias_level = 1.0; // range [0, 2]
  2254. // Min/max standard deviations for scanline beams: Higher values widen and
  2255. // soften scanlines. Depending on other options, low min sigmas can alias.
  2256. static const float beam_min_sigma_static = 0.02; // range (0, 1]
  2257. static const float beam_max_sigma_static = 0.3; // range (0, 1]
  2258. // Beam width varies as a function of color: A power function (0) is more
  2259. // configurable, but a spherical function (1) gives the widest beam
  2260. // variability without aliasing (static option only for now).
  2261. static const float beam_spot_shape_function = 0.0;
  2262. // Spot shape power: Powers <= 1 give smoother spot shapes but lower
  2263. // sharpness. Powers >= 1.0 are awful unless mix/max sigmas are close.
  2264. static const float beam_spot_power_static = 1.0/3.0; // range (0, 16]
  2265. // Generalized Gaussian max shape parameters: Higher values give flatter
  2266. // scanline plateaus and steeper dropoffs, simultaneously widening and
  2267. // sharpening scanlines at the cost of aliasing. 2.0 is pure Gaussian, and
  2268. // values > ~40.0 cause artifacts with integrals.
  2269. static const float beam_min_shape_static = 2.0; // range [2, 32]
  2270. static const float beam_max_shape_static = 4.0; // range [2, 32]
  2271. // Generalized Gaussian shape power: Affects how quickly the distribution
  2272. // changes shape from Gaussian to steep/plateaued as color increases from 0
  2273. // to 1.0. Higher powers appear softer for most colors, and lower powers
  2274. // appear sharper for most colors.
  2275. static const float beam_shape_power_static = 1.0/4.0; // range (0, 16]
  2276. // What filter should be used to sample scanlines horizontally?
  2277. // 0: Quilez (fast), 1: Gaussian (configurable), 2: Lanczos2 (sharp)
  2278. static const float beam_horiz_filter_static = 0.0;
  2279. // Standard deviation for horizontal Gaussian resampling:
  2280. static const float beam_horiz_sigma_static = 0.35; // range (0, 2/3]
  2281. // Do horizontal scanline sampling in linear RGB (correct light mixing),
  2282. // gamma-encoded RGB (darker, hard spot shape, may better match bandwidth-
  2283. // limiting circuitry in some CRT's), or a weighted avg.?
  2284. static const float beam_horiz_linear_rgb_weight_static = 1.0; // range [0, 1]
  2285. // Simulate scanline misconvergence? This needs 3x horizontal texture
  2286. // samples and 3x texture samples of BLOOM_APPROX and HALATION_BLUR in
  2287. // later passes (static option only for now).
  2288. static const bool beam_misconvergence = true;
  2289. // Convergence offsets in x/y directions for R/G/B scanline beams in units
  2290. // of scanlines. Positive offsets go right/down; ranges [-2, 2]
  2291. static const float2 convergence_offsets_r_static = float2(0.1, 0.2);
  2292. static const float2 convergence_offsets_g_static = float2(0.3, 0.4);
  2293. static const float2 convergence_offsets_b_static = float2(0.5, 0.6);
  2294. // Detect interlacing (static option only for now)?
  2295. static const bool interlace_detect = true;
  2296. // Assume 1080-line sources are interlaced?
  2297. static const bool interlace_1080i_static = false;
  2298. // For interlaced sources, assume TFF (top-field first) or BFF order?
  2299. // (Whether this matters depends on the nature of the interlaced input.)
  2300. static const bool interlace_bff_static = false;
  2301. // ANTIALIASING:
  2302. // What AA level do you want for curvature/overscan/subpixels? Options:
  2303. // 0x (none), 1x (sample subpixels), 4x, 5x, 6x, 7x, 8x, 12x, 16x, 20x, 24x
  2304. // (Static option only for now)
  2305. static const float aa_level = 12.0; // range [0, 24]
  2306. // What antialiasing filter do you want (static option only)? Options:
  2307. // 0: Box (separable), 1: Box (cylindrical),
  2308. // 2: Tent (separable), 3: Tent (cylindrical),
  2309. // 4: Gaussian (separable), 5: Gaussian (cylindrical),
  2310. // 6: Cubic* (separable), 7: Cubic* (cylindrical, poor)
  2311. // 8: Lanczos Sinc (separable), 9: Lanczos Jinc (cylindrical, poor)
  2312. // * = Especially slow with RUNTIME_ANTIALIAS_WEIGHTS
  2313. static const float aa_filter = 6.0; // range [0, 9]
  2314. // Flip the sample grid on odd/even frames (static option only for now)?
  2315. static const bool aa_temporal = false;
  2316. // Use RGB subpixel offsets for antialiasing? The pixel is at green, and
  2317. // the blue offset is the negative r offset; range [0, 0.5]
  2318. static const float2 aa_subpixel_r_offset_static = float2(-1.0/3.0, 0.0);//float2(0.0);
  2319. // Cubics: See http://www.imagemagick.org/Usage/filter/#mitchell
  2320. // 1.) "Keys cubics" with B = 1 - 2C are considered the highest quality.
  2321. // 2.) C = 0.5 (default) is Catmull-Rom; higher C's apply sharpening.
  2322. // 3.) C = 1.0/3.0 is the Mitchell-Netravali filter.
  2323. // 4.) C = 0.0 is a soft spline filter.
  2324. static const float aa_cubic_c_static = 0.5; // range [0, 4]
  2325. // Standard deviation for Gaussian antialiasing: Try 0.5/aa_pixel_diameter.
  2326. static const float aa_gauss_sigma_static = 0.5; // range [0.0625, 1.0]
  2327. // PHOSPHOR MASK:
  2328. // Mask type: 0 = aperture grille, 1 = slot mask, 2 = EDP shadow mask
  2329. static const float mask_type_static = 1.0; // range [0, 2]
  2330. // We can sample the mask three ways. Pick 2/3 from: Pretty/Fast/Flexible.
  2331. // 0.) Sinc-resize to the desired dot pitch manually (pretty/slow/flexible).
  2332. // This requires PHOSPHOR_MASK_MANUALLY_RESIZE to be #defined.
  2333. // 1.) Hardware-resize to the desired dot pitch (ugly/fast/flexible). This
  2334. // is halfway decent with LUT mipmapping but atrocious without it.
  2335. // 2.) Tile it without resizing at a 1:1 texel:pixel ratio for flat coords
  2336. // (pretty/fast/inflexible). Each input LUT has a fixed dot pitch.
  2337. // This mode reuses the same masks, so triads will be enormous unless
  2338. // you change the mask LUT filenames in your .cgp file.
  2339. static const float mask_sample_mode_static = 0.0; // range [0, 2]
  2340. // Prefer setting the triad size (0.0) or number on the screen (1.0)?
  2341. // If RUNTIME_PHOSPHOR_BLOOM_SIGMA isn't #defined, the specified triad size
  2342. // will always be used to calculate the full bloom sigma statically.
  2343. static const float mask_specify_num_triads_static = 0.0; // range [0, 1]
  2344. // Specify the phosphor triad size, in pixels. Each tile (usually with 8
  2345. // triads) will be rounded to the nearest integer tile size and clamped to
  2346. // obey minimum size constraints (imposed to reduce downsize taps) and
  2347. // maximum size constraints (imposed to have a sane MASK_RESIZE FBO size).
  2348. // To increase the size limit, double the viewport-relative scales for the
  2349. // two MASK_RESIZE passes in crt-royale.cgp and user-cgp-contants.h.
  2350. // range [1, mask_texture_small_size/mask_triads_per_tile]
  2351. static const float mask_triad_size_desired_static = 24.0 / 8.0;
  2352. // If mask_specify_num_triads is 1.0/true, we'll go by this instead (the
  2353. // final size will be rounded and constrained as above); default 480.0
  2354. static const float mask_num_triads_desired_static = 480.0;
  2355. // How many lobes should the sinc/Lanczos resizer use? More lobes require
  2356. // more samples and avoid moire a bit better, but some is unavoidable
  2357. // depending on the destination size (static option for now).
  2358. static const float mask_sinc_lobes = 3.0; // range [2, 4]
  2359. // The mask is resized using a variable number of taps in each dimension,
  2360. // but some Cg profiles always fetch a constant number of taps no matter
  2361. // what (no dynamic branching). We can limit the maximum number of taps if
  2362. // we statically limit the minimum phosphor triad size. Larger values are
  2363. // faster, but the limit IS enforced (static option only, forever);
  2364. // range [1, mask_texture_small_size/mask_triads_per_tile]
  2365. // TODO: Make this 1.0 and compensate with smarter sampling!
  2366. static const float mask_min_allowed_triad_size = 2.0;
  2367. // GEOMETRY:
  2368. // Geometry mode:
  2369. // 0: Off (default), 1: Spherical mapping (like cgwg's),
  2370. // 2: Alt. spherical mapping (more bulbous), 3: Cylindrical/Trinitron
  2371. static const float geom_mode_static = 0.0; // range [0, 3]
  2372. // Radius of curvature: Measured in units of your viewport's diagonal size.
  2373. static const float geom_radius_static = 2.0; // range [1/(2*pi), 1024]
  2374. // View dist is the distance from the player to their physical screen, in
  2375. // units of the viewport's diagonal size. It controls the field of view.
  2376. static const float geom_view_dist_static = 2.0; // range [0.5, 1024]
  2377. // Tilt angle in radians (clockwise around up and right vectors):
  2378. static const float2 geom_tilt_angle_static = float2(0.0, 0.0); // range [-pi, pi]
  2379. // Aspect ratio: When the true viewport size is unknown, this value is used
  2380. // to help convert between the phosphor triad size and count, along with
  2381. // the mask_resize_viewport_scale constant from user-cgp-constants.h. Set
  2382. // this equal to Retroarch's display aspect ratio (DAR) for best results;
  2383. // range [1, geom_max_aspect_ratio from user-cgp-constants.h];
  2384. // default (256/224)*(54/47) = 1.313069909 (see below)
  2385. static const float geom_aspect_ratio_static = 1.313069909;
  2386. // Before getting into overscan, here's some general aspect ratio info:
  2387. // - DAR = display aspect ratio = SAR * PAR; as in your Retroarch setting
  2388. // - SAR = storage aspect ratio = DAR / PAR; square pixel emulator frame AR
  2389. // - PAR = pixel aspect ratio = DAR / SAR; holds regardless of cropping
  2390. // Geometry processing has to "undo" the screen-space 2D DAR to calculate
  2391. // 3D view vectors, then reapplies the aspect ratio to the simulated CRT in
  2392. // uv-space. To ensure the source SAR is intended for a ~4:3 DAR, either:
  2393. // a.) Enable Retroarch's "Crop Overscan"
  2394. // b.) Readd horizontal padding: Set overscan to e.g. N*(1.0, 240.0/224.0)
  2395. // Real consoles use horizontal black padding in the signal, but emulators
  2396. // often crop this without cropping the vertical padding; a 256x224 [S]NES
  2397. // frame (8:7 SAR) is intended for a ~4:3 DAR, but a 256x240 frame is not.
  2398. // The correct [S]NES PAR is 54:47, found by blargg and NewRisingSun:
  2399. // http://board.zsnes.com/phpBB3/viewtopic.php?f=22&t=11928&start=50
  2400. // http://forums.nesdev.com/viewtopic.php?p=24815#p24815
  2401. // For flat output, it's okay to set DAR = [existing] SAR * [correct] PAR
  2402. // without doing a. or b., but horizontal image borders will be tighter
  2403. // than vertical ones, messing up curvature and overscan. Fixing the
  2404. // padding first corrects this.
  2405. // Overscan: Amount to "zoom in" before cropping. You can zoom uniformly
  2406. // or adjust x/y independently to e.g. readd horizontal padding, as noted
  2407. // above: Values < 1.0 zoom out; range (0, inf)
  2408. static const float2 geom_overscan_static = float2(1.0, 1.0);// * 1.005 * (1.0, 240/224.0)
  2409. // Compute a proper pixel-space to texture-space matrix even without ddx()/
  2410. // ddy()? This is ~8.5% slower but improves antialiasing/subpixel filtering
  2411. // with strong curvature (static option only for now).
  2412. static const bool geom_force_correct_tangent_matrix = true;
  2413. // BORDERS:
  2414. // Rounded border size in texture uv coords:
  2415. static const float border_size_static = 0.015; // range [0, 0.5]
  2416. // Border darkness: Moderate values darken the border smoothly, and high
  2417. // values make the image very dark just inside the border:
  2418. static const float border_darkness_static = 2.0; // range [0, inf)
  2419. // Border compression: High numbers compress border transitions, narrowing
  2420. // the dark border area.
  2421. static const float border_compress_static = 2.5; // range [1, inf)
  2422. #endif // USER_SETTINGS_H
  2423. ///////////////////////////// END USER-SETTINGS ////////////////////////////
  2424. //#include "user-cgp-constants.h"
  2425. ///////////////////////// BEGIN USER-CGP-CONSTANTS /////////////////////////
  2426. #ifndef USER_CGP_CONSTANTS_H
  2427. #define USER_CGP_CONSTANTS_H
  2428. // IMPORTANT:
  2429. // These constants MUST be set appropriately for the settings in crt-royale.cgp
  2430. // (or whatever related .cgp file you're using). If they aren't, you're likely
  2431. // to get artifacts, the wrong phosphor mask size, etc. I wish these could be
  2432. // set directly in the .cgp file to make things easier, but...they can't.
  2433. // PASS SCALES AND RELATED CONSTANTS:
  2434. // Copy the absolute scale_x for BLOOM_APPROX. There are two major versions of
  2435. // this shader: One does a viewport-scale bloom, and the other skips it. The
  2436. // latter benefits from a higher bloom_approx_scale_x, so save both separately:
  2437. static const float bloom_approx_size_x = 320.0;
  2438. static const float bloom_approx_size_x_for_fake = 400.0;
  2439. // Copy the viewport-relative scales of the phosphor mask resize passes
  2440. // (MASK_RESIZE and the pass immediately preceding it):
  2441. static const float2 mask_resize_viewport_scale = float2(0.0625, 0.0625);
  2442. // Copy the geom_max_aspect_ratio used to calculate the MASK_RESIZE scales, etc.:
  2443. static const float geom_max_aspect_ratio = 4.0/3.0;
  2444. // PHOSPHOR MASK TEXTURE CONSTANTS:
  2445. // Set the following constants to reflect the properties of the phosphor mask
  2446. // texture named in crt-royale.cgp. The shader optionally resizes a mask tile
  2447. // based on user settings, then repeats a single tile until filling the screen.
  2448. // The shader must know the input texture size (default 64x64), and to manually
  2449. // resize, it must also know the horizontal triads per tile (default 8).
  2450. static const float2 mask_texture_small_size = float2(64.0, 64.0);
  2451. static const float2 mask_texture_large_size = float2(512.0, 512.0);
  2452. static const float mask_triads_per_tile = 8.0;
  2453. // We need the average brightness of the phosphor mask to compensate for the
  2454. // dimming it causes. The following four values are roughly correct for the
  2455. // masks included with the shader. Update the value for any LUT texture you
  2456. // change. [Un]comment "#define PHOSPHOR_MASK_GRILLE14" depending on whether
  2457. // the loaded aperture grille uses 14-pixel or 15-pixel stripes (default 15).
  2458. //#define PHOSPHOR_MASK_GRILLE14
  2459. static const float mask_grille14_avg_color = 50.6666666/255.0;
  2460. // TileableLinearApertureGrille14Wide7d33Spacing*.png
  2461. // TileableLinearApertureGrille14Wide10And6Spacing*.png
  2462. static const float mask_grille15_avg_color = 53.0/255.0;
  2463. // TileableLinearApertureGrille15Wide6d33Spacing*.png
  2464. // TileableLinearApertureGrille15Wide8And5d5Spacing*.png
  2465. static const float mask_slot_avg_color = 46.0/255.0;
  2466. // TileableLinearSlotMask15Wide9And4d5Horizontal8VerticalSpacing*.png
  2467. // TileableLinearSlotMaskTall15Wide9And4d5Horizontal9d14VerticalSpacing*.png
  2468. static const float mask_shadow_avg_color = 41.0/255.0;
  2469. // TileableLinearShadowMask*.png
  2470. // TileableLinearShadowMaskEDP*.png
  2471. #ifdef PHOSPHOR_MASK_GRILLE14
  2472. static const float mask_grille_avg_color = mask_grille14_avg_color;
  2473. #else
  2474. static const float mask_grille_avg_color = mask_grille15_avg_color;
  2475. #endif
  2476. #endif // USER_CGP_CONSTANTS_H
  2477. ////////////////////////// END USER-CGP-CONSTANTS //////////////////////////
  2478. //////////////////////////////// END INCLUDES ////////////////////////////////
  2479. /////////////////////////////// FIXED SETTINGS ///////////////////////////////
  2480. // Avoid dividing by zero; using a macro overloads for float, float2, etc.:
  2481. #define FIX_ZERO(c) (max(abs(c), 0.0000152587890625)) // 2^-16
  2482. // Ensure the first pass decodes CRT gamma and the last encodes LCD gamma.
  2483. #ifndef SIMULATE_CRT_ON_LCD
  2484. #define SIMULATE_CRT_ON_LCD
  2485. #endif
  2486. // Manually tiling a manually resized texture creates texture coord derivative
  2487. // discontinuities and confuses anisotropic filtering, causing discolored tile
  2488. // seams in the phosphor mask. Workarounds:
  2489. // a.) Using tex2Dlod disables anisotropic filtering for tiled masks. It's
  2490. // downgraded to tex2Dbias without DRIVERS_ALLOW_TEX2DLOD #defined and
  2491. // disabled without DRIVERS_ALLOW_TEX2DBIAS #defined either.
  2492. // b.) "Tile flat twice" requires drawing two full tiles without border padding
  2493. // to the resized mask FBO, and it's incompatible with same-pass curvature.
  2494. // (Same-pass curvature isn't used but could be in the future...maybe.)
  2495. // c.) "Fix discontinuities" requires derivatives and drawing one tile with
  2496. // border padding to the resized mask FBO, but it works with same-pass
  2497. // curvature. It's disabled without DRIVERS_ALLOW_DERIVATIVES #defined.
  2498. // Precedence: a, then, b, then c (if multiple strategies are #defined).
  2499. #define ANISOTROPIC_TILING_COMPAT_TEX2DLOD // 129.7 FPS, 4x, flat; 101.8 at fullscreen
  2500. #define ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE // 128.1 FPS, 4x, flat; 101.5 at fullscreen
  2501. #define ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES // 124.4 FPS, 4x, flat; 97.4 at fullscreen
  2502. // Also, manually resampling the phosphor mask is slightly blurrier with
  2503. // anisotropic filtering. (Resampling with mipmapping is even worse: It
  2504. // creates artifacts, but only with the fully bloomed shader.) The difference
  2505. // is subtle with small triads, but you can fix it for a small cost.
  2506. //#define ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  2507. ////////////////////////////// DERIVED SETTINGS //////////////////////////////
  2508. // Intel HD 4000 GPU's can't handle manual mask resizing (for now), setting the
  2509. // geometry mode at runtime, or a 4x4 true Gaussian resize. Disable
  2510. // incompatible settings ASAP. (INTEGRATED_GRAPHICS_COMPATIBILITY_MODE may be
  2511. // #defined by either user-settings.h or a wrapper .cg that #includes the
  2512. // current .cg pass.)
  2513. #ifdef INTEGRATED_GRAPHICS_COMPATIBILITY_MODE
  2514. #ifdef PHOSPHOR_MASK_MANUALLY_RESIZE
  2515. #undef PHOSPHOR_MASK_MANUALLY_RESIZE
  2516. #endif
  2517. #ifdef RUNTIME_GEOMETRY_MODE
  2518. #undef RUNTIME_GEOMETRY_MODE
  2519. #endif
  2520. // Mode 2 (4x4 Gaussian resize) won't work, and mode 1 (3x3 blur) is
  2521. // inferior in most cases, so replace 2.0 with 0.0:
  2522. static const float bloom_approx_filter =
  2523. bloom_approx_filter_static > 1.5 ? 0.0 : bloom_approx_filter_static;
  2524. #else
  2525. static const float bloom_approx_filter = bloom_approx_filter_static;
  2526. #endif
  2527. // Disable slow runtime paths if static parameters are used. Most of these
  2528. // won't be a problem anyway once the params are disabled, but some will.
  2529. #ifndef RUNTIME_SHADER_PARAMS_ENABLE
  2530. #ifdef RUNTIME_PHOSPHOR_BLOOM_SIGMA
  2531. #undef RUNTIME_PHOSPHOR_BLOOM_SIGMA
  2532. #endif
  2533. #ifdef RUNTIME_ANTIALIAS_WEIGHTS
  2534. #undef RUNTIME_ANTIALIAS_WEIGHTS
  2535. #endif
  2536. #ifdef RUNTIME_ANTIALIAS_SUBPIXEL_OFFSETS
  2537. #undef RUNTIME_ANTIALIAS_SUBPIXEL_OFFSETS
  2538. #endif
  2539. #ifdef RUNTIME_SCANLINES_HORIZ_FILTER_COLORSPACE
  2540. #undef RUNTIME_SCANLINES_HORIZ_FILTER_COLORSPACE
  2541. #endif
  2542. #ifdef RUNTIME_GEOMETRY_TILT
  2543. #undef RUNTIME_GEOMETRY_TILT
  2544. #endif
  2545. #ifdef RUNTIME_GEOMETRY_MODE
  2546. #undef RUNTIME_GEOMETRY_MODE
  2547. #endif
  2548. #ifdef FORCE_RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  2549. #undef FORCE_RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  2550. #endif
  2551. #endif
  2552. // Make tex2Dbias a backup for tex2Dlod for wider compatibility.
  2553. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DLOD
  2554. #define ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  2555. #endif
  2556. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  2557. #define ANISOTROPIC_RESAMPLING_COMPAT_TEX2DBIAS
  2558. #endif
  2559. // Rule out unavailable anisotropic compatibility strategies:
  2560. #ifndef DRIVERS_ALLOW_DERIVATIVES
  2561. #ifdef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  2562. #undef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  2563. #endif
  2564. #endif
  2565. #ifndef DRIVERS_ALLOW_TEX2DLOD
  2566. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DLOD
  2567. #undef ANISOTROPIC_TILING_COMPAT_TEX2DLOD
  2568. #endif
  2569. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  2570. #undef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  2571. #endif
  2572. #ifdef ANTIALIAS_DISABLE_ANISOTROPIC
  2573. #undef ANTIALIAS_DISABLE_ANISOTROPIC
  2574. #endif
  2575. #endif
  2576. #ifndef DRIVERS_ALLOW_TEX2DBIAS
  2577. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  2578. #undef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  2579. #endif
  2580. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DBIAS
  2581. #undef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DBIAS
  2582. #endif
  2583. #endif
  2584. // Prioritize anisotropic tiling compatibility strategies by performance and
  2585. // disable unused strategies. This concentrates all the nesting in one place.
  2586. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DLOD
  2587. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  2588. #undef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  2589. #endif
  2590. #ifdef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  2591. #undef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  2592. #endif
  2593. #ifdef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  2594. #undef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  2595. #endif
  2596. #else
  2597. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  2598. #ifdef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  2599. #undef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  2600. #endif
  2601. #ifdef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  2602. #undef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  2603. #endif
  2604. #else
  2605. // ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE is only compatible with
  2606. // flat texture coords in the same pass, but that's all we use.
  2607. #ifdef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  2608. #ifdef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  2609. #undef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  2610. #endif
  2611. #endif
  2612. #endif
  2613. #endif
  2614. // The tex2Dlod and tex2Dbias strategies share a lot in common, and we can
  2615. // reduce some #ifdef nesting in the next section by essentially OR'ing them:
  2616. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DLOD
  2617. #define ANISOTROPIC_TILING_COMPAT_TEX2DLOD_FAMILY
  2618. #endif
  2619. #ifdef ANISOTROPIC_TILING_COMPAT_TEX2DBIAS
  2620. #define ANISOTROPIC_TILING_COMPAT_TEX2DLOD_FAMILY
  2621. #endif
  2622. // Prioritize anisotropic resampling compatibility strategies the same way:
  2623. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  2624. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DBIAS
  2625. #undef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DBIAS
  2626. #endif
  2627. #endif
  2628. /////////////////////// DERIVED PHOSPHOR MASK CONSTANTS //////////////////////
  2629. // If we can use the large mipmapped LUT without mipmapping artifacts, we
  2630. // should: It gives us more options for using fewer samples.
  2631. #ifdef DRIVERS_ALLOW_TEX2DLOD
  2632. #ifdef ANISOTROPIC_RESAMPLING_COMPAT_TEX2DLOD
  2633. // TODO: Take advantage of this!
  2634. #define PHOSPHOR_MASK_RESIZE_MIPMAPPED_LUT
  2635. static const float2 mask_resize_src_lut_size = mask_texture_large_size;
  2636. #else
  2637. static const float2 mask_resize_src_lut_size = mask_texture_small_size;
  2638. #endif
  2639. #else
  2640. static const float2 mask_resize_src_lut_size = mask_texture_small_size;
  2641. #endif
  2642. // tex2D's sampler2D parameter MUST be a uniform global, a uniform input to
  2643. // main_fragment, or a static alias of one of the above. This makes it hard
  2644. // to select the phosphor mask at runtime: We can't even assign to a uniform
  2645. // global in the vertex shader or select a sampler2D in the vertex shader and
  2646. // pass it to the fragment shader (even with explicit TEXUNIT# bindings),
  2647. // because it just gives us the input texture or a black screen. However, we
  2648. // can get around these limitations by calling tex2D three times with different
  2649. // uniform samplers (or resizing the phosphor mask three times altogether).
  2650. // With dynamic branches, we can process only one of these branches on top of
  2651. // quickly discarding fragments we don't need (cgc seems able to overcome
  2652. // limigations around dependent texture fetches inside of branches). Without
  2653. // dynamic branches, we have to process every branch for every fragment...which
  2654. // is slower. Runtime sampling mode selection is slower without dynamic
  2655. // branches as well. Let the user's static #defines decide if it's worth it.
  2656. #ifdef DRIVERS_ALLOW_DYNAMIC_BRANCHES
  2657. #define RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  2658. #else
  2659. #ifdef FORCE_RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  2660. #define RUNTIME_PHOSPHOR_MASK_MODE_TYPE_SELECT
  2661. #endif
  2662. #endif
  2663. // We need to render some minimum number of tiles in the resize passes.
  2664. // We need at least 1.0 just to repeat a single tile, and we need extra
  2665. // padding beyond that for anisotropic filtering, discontinuitity fixing,
  2666. // antialiasing, same-pass curvature (not currently used), etc. First
  2667. // determine how many border texels and tiles we need, based on how the result
  2668. // will be sampled:
  2669. #ifdef GEOMETRY_EARLY
  2670. static const float max_subpixel_offset = aa_subpixel_r_offset_static.x;
  2671. // Most antialiasing filters have a base radius of 4.0 pixels:
  2672. static const float max_aa_base_pixel_border = 4.0 +
  2673. max_subpixel_offset;
  2674. #else
  2675. static const float max_aa_base_pixel_border = 0.0;
  2676. #endif
  2677. // Anisotropic filtering adds about 0.5 to the pixel border:
  2678. #ifndef ANISOTROPIC_TILING_COMPAT_TEX2DLOD_FAMILY
  2679. static const float max_aniso_pixel_border = max_aa_base_pixel_border + 0.5;
  2680. #else
  2681. static const float max_aniso_pixel_border = max_aa_base_pixel_border;
  2682. #endif
  2683. // Fixing discontinuities adds 1.0 more to the pixel border:
  2684. #ifdef ANISOTROPIC_TILING_COMPAT_FIX_DISCONTINUITIES
  2685. static const float max_tiled_pixel_border = max_aniso_pixel_border + 1.0;
  2686. #else
  2687. static const float max_tiled_pixel_border = max_aniso_pixel_border;
  2688. #endif
  2689. // Convert the pixel border to an integer texel border. Assume same-pass
  2690. // curvature about triples the texel frequency:
  2691. #ifdef GEOMETRY_EARLY
  2692. static const float max_mask_texel_border =
  2693. ceil(max_tiled_pixel_border * 3.0);
  2694. #else
  2695. static const float max_mask_texel_border = ceil(max_tiled_pixel_border);
  2696. #endif
  2697. // Convert the texel border to a tile border using worst-case assumptions:
  2698. static const float max_mask_tile_border = max_mask_texel_border/
  2699. (mask_min_allowed_triad_size * mask_triads_per_tile);
  2700. // Finally, set the number of resized tiles to render to MASK_RESIZE, and set
  2701. // the starting texel (inside borders) for sampling it.
  2702. #ifndef GEOMETRY_EARLY
  2703. #ifdef ANISOTROPIC_TILING_COMPAT_TILE_FLAT_TWICE
  2704. // Special case: Render two tiles without borders. Anisotropic
  2705. // filtering doesn't seem to be a problem here.
  2706. static const float mask_resize_num_tiles = 1.0 + 1.0;
  2707. static const float mask_start_texels = 0.0;
  2708. #else
  2709. static const float mask_resize_num_tiles = 1.0 +
  2710. 2.0 * max_mask_tile_border;
  2711. static const float mask_start_texels = max_mask_texel_border;
  2712. #endif
  2713. #else
  2714. static const float mask_resize_num_tiles = 1.0 + 2.0*max_mask_tile_border;
  2715. static const float mask_start_texels = max_mask_texel_border;
  2716. #endif
  2717. // We have to fit mask_resize_num_tiles into an FBO with a viewport scale of
  2718. // mask_resize_viewport_scale. This limits the maximum final triad size.
  2719. // Estimate the minimum number of triads we can split the screen into in each
  2720. // dimension (we'll be as correct as mask_resize_viewport_scale is):
  2721. static const float mask_resize_num_triads =
  2722. mask_resize_num_tiles * mask_triads_per_tile;
  2723. static const float2 min_allowed_viewport_triads =
  2724. float2(mask_resize_num_triads) / mask_resize_viewport_scale;
  2725. //////////////////////// COMMON MATHEMATICAL CONSTANTS ///////////////////////
  2726. static const float pi = 3.141592653589;
  2727. // We often want to find the location of the previous texel, e.g.:
  2728. // const float2 curr_texel = uv * texture_size;
  2729. // const float2 prev_texel = floor(curr_texel - float2(0.5)) + float2(0.5);
  2730. // const float2 prev_texel_uv = prev_texel / texture_size;
  2731. // However, many GPU drivers round incorrectly around exact texel locations.
  2732. // We need to subtract a little less than 0.5 before flooring, and some GPU's
  2733. // require this value to be farther from 0.5 than others; define it here.
  2734. // const float2 prev_texel =
  2735. // floor(curr_texel - float2(under_half)) + float2(0.5);
  2736. static const float under_half = 0.4995;
  2737. #endif // DERIVED_SETTINGS_AND_CONSTANTS_H
  2738. ///////////////////////////// END DERIVED-SETTINGS-AND-CONSTANTS ////////////////////////////
  2739. //#include "../../../../include/special-functions.h"
  2740. /////////////////////////// BEGIN SPECIAL-FUNCTIONS //////////////////////////
  2741. #ifndef SPECIAL_FUNCTIONS_H
  2742. #define SPECIAL_FUNCTIONS_H
  2743. ///////////////////////////////// MIT LICENSE ////////////////////////////////
  2744. // Copyright (C) 2014 TroggleMonkey
  2745. //
  2746. // Permission is hereby granted, free of charge, to any person obtaining a copy
  2747. // of this software and associated documentation files (the "Software"), to
  2748. // deal in the Software without restriction, including without limitation the
  2749. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  2750. // sell copies of the Software, and to permit persons to whom the Software is
  2751. // furnished to do so, subject to the following conditions:
  2752. //
  2753. // The above copyright notice and this permission notice shall be included in
  2754. // all copies or substantial portions of the Software.
  2755. //
  2756. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  2757. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  2758. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  2759. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  2760. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  2761. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  2762. // IN THE SOFTWARE.
  2763. ///////////////////////////////// DESCRIPTION ////////////////////////////////
  2764. // This file implements the following mathematical special functions:
  2765. // 1.) erf() = 2/sqrt(pi) * indefinite_integral(e**(-x**2))
  2766. // 2.) gamma(s), a real-numbered extension of the integer factorial function
  2767. // It also implements normalized_ligamma(s, z), a normalized lower incomplete
  2768. // gamma function for s < 0.5 only. Both gamma() and normalized_ligamma() can
  2769. // be called with an _impl suffix to use an implementation version with a few
  2770. // extra precomputed parameters (which may be useful for the caller to reuse).
  2771. // See below for details.
  2772. //
  2773. // Design Rationale:
  2774. // Pretty much every line of code in this file is duplicated four times for
  2775. // different input types (float4/float3/float2/float). This is unfortunate,
  2776. // but Cg doesn't allow function templates. Macros would be far less verbose,
  2777. // but they would make the code harder to document and read. I don't expect
  2778. // these functions will require a whole lot of maintenance changes unless
  2779. // someone ever has need for more robust incomplete gamma functions, so code
  2780. // duplication seems to be the lesser evil in this case.
  2781. /////////////////////////// GAUSSIAN ERROR FUNCTION //////////////////////////
  2782. float4 erf6(float4 x)
  2783. {
  2784. // Requires: x is the standard parameter to erf().
  2785. // Returns: Return an Abramowitz/Stegun approximation of erf(), where:
  2786. // erf(x) = 2/sqrt(pi) * integral(e**(-x**2))
  2787. // This approximation has a max absolute error of 2.5*10**-5
  2788. // with solid numerical robustness and efficiency. See:
  2789. // https://en.wikipedia.org/wiki/Error_function#Approximation_with_elementary_functions
  2790. static const float4 one = float4(1.0);
  2791. const float4 sign_x = sign(x);
  2792. const float4 t = one/(one + 0.47047*abs(x));
  2793. const float4 result = one - t*(0.3480242 + t*(-0.0958798 + t*0.7478556))*
  2794. exp(-(x*x));
  2795. return result * sign_x;
  2796. }
  2797. float3 erf6(const float3 x)
  2798. {
  2799. // Float3 version:
  2800. static const float3 one = float3(1.0);
  2801. const float3 sign_x = sign(x);
  2802. const float3 t = one/(one + 0.47047*abs(x));
  2803. const float3 result = one - t*(0.3480242 + t*(-0.0958798 + t*0.7478556))*
  2804. exp(-(x*x));
  2805. return result * sign_x;
  2806. }
  2807. float2 erf6(const float2 x)
  2808. {
  2809. // Float2 version:
  2810. static const float2 one = float2(1.0);
  2811. const float2 sign_x = sign(x);
  2812. const float2 t = one/(one + 0.47047*abs(x));
  2813. const float2 result = one - t*(0.3480242 + t*(-0.0958798 + t*0.7478556))*
  2814. exp(-(x*x));
  2815. return result * sign_x;
  2816. }
  2817. float erf6(const float x)
  2818. {
  2819. // Float version:
  2820. const float sign_x = sign(x);
  2821. const float t = 1.0/(1.0 + 0.47047*abs(x));
  2822. const float result = 1.0 - t*(0.3480242 + t*(-0.0958798 + t*0.7478556))*
  2823. exp(-(x*x));
  2824. return result * sign_x;
  2825. }
  2826. float4 erft(const float4 x)
  2827. {
  2828. // Requires: x is the standard parameter to erf().
  2829. // Returns: Approximate erf() with the hyperbolic tangent. The error is
  2830. // visually noticeable, but it's blazing fast and perceptually
  2831. // close...at least on ATI hardware. See:
  2832. // http://www.maplesoft.com/applications/view.aspx?SID=5525&view=html
  2833. // Warning: Only use this if your hardware drivers correctly implement
  2834. // tanh(): My nVidia 8800GTS returns garbage output.
  2835. return tanh(1.202760580 * x);
  2836. }
  2837. float3 erft(const float3 x)
  2838. {
  2839. // Float3 version:
  2840. return tanh(1.202760580 * x);
  2841. }
  2842. float2 erft(const float2 x)
  2843. {
  2844. // Float2 version:
  2845. return tanh(1.202760580 * x);
  2846. }
  2847. float erft(const float x)
  2848. {
  2849. // Float version:
  2850. return tanh(1.202760580 * x);
  2851. }
  2852. inline float4 erf(const float4 x)
  2853. {
  2854. // Requires: x is the standard parameter to erf().
  2855. // Returns: Some approximation of erf(x), depending on user settings.
  2856. #ifdef ERF_FAST_APPROXIMATION
  2857. return erft(x);
  2858. #else
  2859. return erf6(x);
  2860. #endif
  2861. }
  2862. inline float3 erf(const float3 x)
  2863. {
  2864. // Float3 version:
  2865. #ifdef ERF_FAST_APPROXIMATION
  2866. return erft(x);
  2867. #else
  2868. return erf6(x);
  2869. #endif
  2870. }
  2871. inline float2 erf(const float2 x)
  2872. {
  2873. // Float2 version:
  2874. #ifdef ERF_FAST_APPROXIMATION
  2875. return erft(x);
  2876. #else
  2877. return erf6(x);
  2878. #endif
  2879. }
  2880. inline float erf(const float x)
  2881. {
  2882. // Float version:
  2883. #ifdef ERF_FAST_APPROXIMATION
  2884. return erft(x);
  2885. #else
  2886. return erf6(x);
  2887. #endif
  2888. }
  2889. /////////////////////////// COMPLETE GAMMA FUNCTION //////////////////////////
  2890. float4 gamma_impl(const float4 s, const float4 s_inv)
  2891. {
  2892. // Requires: 1.) s is the standard parameter to the gamma function, and
  2893. // it should lie in the [0, 36] range.
  2894. // 2.) s_inv = 1.0/s. This implementation function requires
  2895. // the caller to precompute this value, giving users the
  2896. // opportunity to reuse it.
  2897. // Returns: Return approximate gamma function (real-numbered factorial)
  2898. // output using the Lanczos approximation with two coefficients
  2899. // calculated using Paul Godfrey's method here:
  2900. // http://my.fit.edu/~gabdo/gamma.txt
  2901. // An optimal g value for s in [0, 36] is ~1.12906830989, with
  2902. // a maximum relative error of 0.000463 for 2**16 equally
  2903. // evals. We could use three coeffs (0.0000346 error) without
  2904. // hurting latency, but this allows more parallelism with
  2905. // outside instructions.
  2906. static const float4 g = float4(1.12906830989);
  2907. static const float4 c0 = float4(0.8109119309638332633713423362694399653724431);
  2908. static const float4 c1 = float4(0.4808354605142681877121661197951496120000040);
  2909. static const float4 e = float4(2.71828182845904523536028747135266249775724709);
  2910. const float4 sph = s + float4(0.5);
  2911. const float4 lanczos_sum = c0 + c1/(s + float4(1.0));
  2912. const float4 base = (sph + g)/e; // or (s + g + float4(0.5))/e
  2913. // gamma(s + 1) = base**sph * lanczos_sum; divide by s for gamma(s).
  2914. // This has less error for small s's than (s -= 1.0) at the beginning.
  2915. return (pow(base, sph) * lanczos_sum) * s_inv;
  2916. }
  2917. float3 gamma_impl(const float3 s, const float3 s_inv)
  2918. {
  2919. // Float3 version:
  2920. static const float3 g = float3(1.12906830989);
  2921. static const float3 c0 = float3(0.8109119309638332633713423362694399653724431);
  2922. static const float3 c1 = float3(0.4808354605142681877121661197951496120000040);
  2923. static const float3 e = float3(2.71828182845904523536028747135266249775724709);
  2924. const float3 sph = s + float3(0.5);
  2925. const float3 lanczos_sum = c0 + c1/(s + float3(1.0));
  2926. const float3 base = (sph + g)/e;
  2927. return (pow(base, sph) * lanczos_sum) * s_inv;
  2928. }
  2929. float2 gamma_impl(const float2 s, const float2 s_inv)
  2930. {
  2931. // Float2 version:
  2932. static const float2 g = float2(1.12906830989);
  2933. static const float2 c0 = float2(0.8109119309638332633713423362694399653724431);
  2934. static const float2 c1 = float2(0.4808354605142681877121661197951496120000040);
  2935. static const float2 e = float2(2.71828182845904523536028747135266249775724709);
  2936. const float2 sph = s + float2(0.5);
  2937. const float2 lanczos_sum = c0 + c1/(s + float2(1.0));
  2938. const float2 base = (sph + g)/e;
  2939. return (pow(base, sph) * lanczos_sum) * s_inv;
  2940. }
  2941. float gamma_impl(const float s, const float s_inv)
  2942. {
  2943. // Float version:
  2944. static const float g = 1.12906830989;
  2945. static const float c0 = 0.8109119309638332633713423362694399653724431;
  2946. static const float c1 = 0.4808354605142681877121661197951496120000040;
  2947. static const float e = 2.71828182845904523536028747135266249775724709;
  2948. const float sph = s + 0.5;
  2949. const float lanczos_sum = c0 + c1/(s + 1.0);
  2950. const float base = (sph + g)/e;
  2951. return (pow(base, sph) * lanczos_sum) * s_inv;
  2952. }
  2953. float4 gamma(const float4 s)
  2954. {
  2955. // Requires: s is the standard parameter to the gamma function, and it
  2956. // should lie in the [0, 36] range.
  2957. // Returns: Return approximate gamma function output with a maximum
  2958. // relative error of 0.000463. See gamma_impl for details.
  2959. return gamma_impl(s, float4(1.0)/s);
  2960. }
  2961. float3 gamma(const float3 s)
  2962. {
  2963. // Float3 version:
  2964. return gamma_impl(s, float3(1.0)/s);
  2965. }
  2966. float2 gamma(const float2 s)
  2967. {
  2968. // Float2 version:
  2969. return gamma_impl(s, float2(1.0)/s);
  2970. }
  2971. float gamma(const float s)
  2972. {
  2973. // Float version:
  2974. return gamma_impl(s, 1.0/s);
  2975. }
  2976. //////////////// INCOMPLETE GAMMA FUNCTIONS (RESTRICTED INPUT) ///////////////
  2977. // Lower incomplete gamma function for small s and z (implementation):
  2978. float4 ligamma_small_z_impl(const float4 s, const float4 z, const float4 s_inv)
  2979. {
  2980. // Requires: 1.) s < ~0.5
  2981. // 2.) z <= ~0.775075
  2982. // 3.) s_inv = 1.0/s (precomputed for outside reuse)
  2983. // Returns: A series representation for the lower incomplete gamma
  2984. // function for small s and small z (4 terms).
  2985. // The actual "rolled up" summation looks like:
  2986. // last_sign = 1.0; last_pow = 1.0; last_factorial = 1.0;
  2987. // sum = last_sign * last_pow / ((s + k) * last_factorial)
  2988. // for(int i = 0; i < 4; ++i)
  2989. // {
  2990. // last_sign *= -1.0; last_pow *= z; last_factorial *= i;
  2991. // sum += last_sign * last_pow / ((s + k) * last_factorial);
  2992. // }
  2993. // Unrolled, constant-unfolded and arranged for madds and parallelism:
  2994. const float4 scale = pow(z, s);
  2995. float4 sum = s_inv; // Summation iteration 0 result
  2996. // Summation iterations 1, 2, and 3:
  2997. const float4 z_sq = z*z;
  2998. const float4 denom1 = s + float4(1.0);
  2999. const float4 denom2 = 2.0*s + float4(4.0);
  3000. const float4 denom3 = 6.0*s + float4(18.0);
  3001. //float4 denom4 = 24.0*s + float4(96.0);
  3002. sum -= z/denom1;
  3003. sum += z_sq/denom2;
  3004. sum -= z * z_sq/denom3;
  3005. //sum += z_sq * z_sq / denom4;
  3006. // Scale and return:
  3007. return scale * sum;
  3008. }
  3009. float3 ligamma_small_z_impl(const float3 s, const float3 z, const float3 s_inv)
  3010. {
  3011. // Float3 version:
  3012. const float3 scale = pow(z, s);
  3013. float3 sum = s_inv;
  3014. const float3 z_sq = z*z;
  3015. const float3 denom1 = s + float3(1.0);
  3016. const float3 denom2 = 2.0*s + float3(4.0);
  3017. const float3 denom3 = 6.0*s + float3(18.0);
  3018. sum -= z/denom1;
  3019. sum += z_sq/denom2;
  3020. sum -= z * z_sq/denom3;
  3021. return scale * sum;
  3022. }
  3023. float2 ligamma_small_z_impl(const float2 s, const float2 z, const float2 s_inv)
  3024. {
  3025. // Float2 version:
  3026. const float2 scale = pow(z, s);
  3027. float2 sum = s_inv;
  3028. const float2 z_sq = z*z;
  3029. const float2 denom1 = s + float2(1.0);
  3030. const float2 denom2 = 2.0*s + float2(4.0);
  3031. const float2 denom3 = 6.0*s + float2(18.0);
  3032. sum -= z/denom1;
  3033. sum += z_sq/denom2;
  3034. sum -= z * z_sq/denom3;
  3035. return scale * sum;
  3036. }
  3037. float ligamma_small_z_impl(const float s, const float z, const float s_inv)
  3038. {
  3039. // Float version:
  3040. const float scale = pow(z, s);
  3041. float sum = s_inv;
  3042. const float z_sq = z*z;
  3043. const float denom1 = s + 1.0;
  3044. const float denom2 = 2.0*s + 4.0;
  3045. const float denom3 = 6.0*s + 18.0;
  3046. sum -= z/denom1;
  3047. sum += z_sq/denom2;
  3048. sum -= z * z_sq/denom3;
  3049. return scale * sum;
  3050. }
  3051. // Upper incomplete gamma function for small s and large z (implementation):
  3052. float4 uigamma_large_z_impl(const float4 s, const float4 z)
  3053. {
  3054. // Requires: 1.) s < ~0.5
  3055. // 2.) z > ~0.775075
  3056. // Returns: Gauss's continued fraction representation for the upper
  3057. // incomplete gamma function (4 terms).
  3058. // The "rolled up" continued fraction looks like this. The denominator
  3059. // is truncated, and it's calculated "from the bottom up:"
  3060. // denom = float4('inf');
  3061. // float4 one = float4(1.0);
  3062. // for(int i = 4; i > 0; --i)
  3063. // {
  3064. // denom = ((i * 2.0) - one) + z - s + (i * (s - i))/denom;
  3065. // }
  3066. // Unrolled and constant-unfolded for madds and parallelism:
  3067. const float4 numerator = pow(z, s) * exp(-z);
  3068. float4 denom = float4(7.0) + z - s;
  3069. denom = float4(5.0) + z - s + (3.0*s - float4(9.0))/denom;
  3070. denom = float4(3.0) + z - s + (2.0*s - float4(4.0))/denom;
  3071. denom = float4(1.0) + z - s + (s - float4(1.0))/denom;
  3072. return numerator / denom;
  3073. }
  3074. float3 uigamma_large_z_impl(const float3 s, const float3 z)
  3075. {
  3076. // Float3 version:
  3077. const float3 numerator = pow(z, s) * exp(-z);
  3078. float3 denom = float3(7.0) + z - s;
  3079. denom = float3(5.0) + z - s + (3.0*s - float3(9.0))/denom;
  3080. denom = float3(3.0) + z - s + (2.0*s - float3(4.0))/denom;
  3081. denom = float3(1.0) + z - s + (s - float3(1.0))/denom;
  3082. return numerator / denom;
  3083. }
  3084. float2 uigamma_large_z_impl(const float2 s, const float2 z)
  3085. {
  3086. // Float2 version:
  3087. const float2 numerator = pow(z, s) * exp(-z);
  3088. float2 denom = float2(7.0) + z - s;
  3089. denom = float2(5.0) + z - s + (3.0*s - float2(9.0))/denom;
  3090. denom = float2(3.0) + z - s + (2.0*s - float2(4.0))/denom;
  3091. denom = float2(1.0) + z - s + (s - float2(1.0))/denom;
  3092. return numerator / denom;
  3093. }
  3094. float uigamma_large_z_impl(const float s, const float z)
  3095. {
  3096. // Float version:
  3097. const float numerator = pow(z, s) * exp(-z);
  3098. float denom = 7.0 + z - s;
  3099. denom = 5.0 + z - s + (3.0*s - 9.0)/denom;
  3100. denom = 3.0 + z - s + (2.0*s - 4.0)/denom;
  3101. denom = 1.0 + z - s + (s - 1.0)/denom;
  3102. return numerator / denom;
  3103. }
  3104. // Normalized lower incomplete gamma function for small s (implementation):
  3105. float4 normalized_ligamma_impl(const float4 s, const float4 z,
  3106. const float4 s_inv, const float4 gamma_s_inv)
  3107. {
  3108. // Requires: 1.) s < ~0.5
  3109. // 2.) s_inv = 1/s (precomputed for outside reuse)
  3110. // 3.) gamma_s_inv = 1/gamma(s) (precomputed for outside reuse)
  3111. // Returns: Approximate the normalized lower incomplete gamma function
  3112. // for s < 0.5. Since we only care about s < 0.5, we only need
  3113. // to evaluate two branches (not four) based on z. Each branch
  3114. // uses four terms, with a max relative error of ~0.00182. The
  3115. // branch threshold and specifics were adapted for fewer terms
  3116. // from Gil/Segura/Temme's paper here:
  3117. // http://oai.cwi.nl/oai/asset/20433/20433B.pdf
  3118. // Evaluate both branches: Real branches test slower even when available.
  3119. static const float4 thresh = float4(0.775075);
  3120. bool4 z_is_large;
  3121. z_is_large.x = z.x > thresh.x;
  3122. z_is_large.y = z.y > thresh.y;
  3123. z_is_large.z = z.z > thresh.z;
  3124. z_is_large.w = z.w > thresh.w;
  3125. const float4 large_z = float4(1.0) - uigamma_large_z_impl(s, z) * gamma_s_inv;
  3126. const float4 small_z = ligamma_small_z_impl(s, z, s_inv) * gamma_s_inv;
  3127. // Combine the results from both branches:
  3128. bool4 inverse_z_is_large = not(z_is_large);
  3129. return large_z * float4(z_is_large) + small_z * float4(inverse_z_is_large);
  3130. }
  3131. float3 normalized_ligamma_impl(const float3 s, const float3 z,
  3132. const float3 s_inv, const float3 gamma_s_inv)
  3133. {
  3134. // Float3 version:
  3135. static const float3 thresh = float3(0.775075);
  3136. bool3 z_is_large;
  3137. z_is_large.x = z.x > thresh.x;
  3138. z_is_large.y = z.y > thresh.y;
  3139. z_is_large.z = z.z > thresh.z;
  3140. const float3 large_z = float3(1.0) - uigamma_large_z_impl(s, z) * gamma_s_inv;
  3141. const float3 small_z = ligamma_small_z_impl(s, z, s_inv) * gamma_s_inv;
  3142. bool3 inverse_z_is_large = not(z_is_large);
  3143. return large_z * float3(z_is_large) + small_z * float3(inverse_z_is_large);
  3144. }
  3145. float2 normalized_ligamma_impl(const float2 s, const float2 z,
  3146. const float2 s_inv, const float2 gamma_s_inv)
  3147. {
  3148. // Float2 version:
  3149. static const float2 thresh = float2(0.775075);
  3150. bool2 z_is_large;
  3151. z_is_large.x = z.x > thresh.x;
  3152. z_is_large.y = z.y > thresh.y;
  3153. const float2 large_z = float2(1.0) - uigamma_large_z_impl(s, z) * gamma_s_inv;
  3154. const float2 small_z = ligamma_small_z_impl(s, z, s_inv) * gamma_s_inv;
  3155. bool2 inverse_z_is_large = not(z_is_large);
  3156. return large_z * float2(z_is_large) + small_z * float2(inverse_z_is_large);
  3157. }
  3158. float normalized_ligamma_impl(const float s, const float z,
  3159. const float s_inv, const float gamma_s_inv)
  3160. {
  3161. // Float version:
  3162. static const float thresh = 0.775075;
  3163. const bool z_is_large = z > thresh;
  3164. const float large_z = 1.0 - uigamma_large_z_impl(s, z) * gamma_s_inv;
  3165. const float small_z = ligamma_small_z_impl(s, z, s_inv) * gamma_s_inv;
  3166. return large_z * float(z_is_large) + small_z * float(!z_is_large);
  3167. }
  3168. // Normalized lower incomplete gamma function for small s:
  3169. float4 normalized_ligamma(const float4 s, const float4 z)
  3170. {
  3171. // Requires: s < ~0.5
  3172. // Returns: Approximate the normalized lower incomplete gamma function
  3173. // for s < 0.5. See normalized_ligamma_impl() for details.
  3174. const float4 s_inv = float4(1.0)/s;
  3175. const float4 gamma_s_inv = float4(1.0)/gamma_impl(s, s_inv);
  3176. return normalized_ligamma_impl(s, z, s_inv, gamma_s_inv);
  3177. }
  3178. float3 normalized_ligamma(const float3 s, const float3 z)
  3179. {
  3180. // Float3 version:
  3181. const float3 s_inv = float3(1.0)/s;
  3182. const float3 gamma_s_inv = float3(1.0)/gamma_impl(s, s_inv);
  3183. return normalized_ligamma_impl(s, z, s_inv, gamma_s_inv);
  3184. }
  3185. float2 normalized_ligamma(const float2 s, const float2 z)
  3186. {
  3187. // Float2 version:
  3188. const float2 s_inv = float2(1.0)/s;
  3189. const float2 gamma_s_inv = float2(1.0)/gamma_impl(s, s_inv);
  3190. return normalized_ligamma_impl(s, z, s_inv, gamma_s_inv);
  3191. }
  3192. float normalized_ligamma(const float s, const float z)
  3193. {
  3194. // Float version:
  3195. const float s_inv = 1.0/s;
  3196. const float gamma_s_inv = 1.0/gamma_impl(s, s_inv);
  3197. return normalized_ligamma_impl(s, z, s_inv, gamma_s_inv);
  3198. }
  3199. #endif // SPECIAL_FUNCTIONS_H
  3200. //////////////////////////// END SPECIAL-FUNCTIONS ///////////////////////////
  3201. //#include "../../../../include/gamma-management.h"
  3202. //////////////////////////// BEGIN GAMMA-MANAGEMENT //////////////////////////
  3203. #ifndef GAMMA_MANAGEMENT_H
  3204. #define GAMMA_MANAGEMENT_H
  3205. ///////////////////////////////// MIT LICENSE ////////////////////////////////
  3206. // Copyright (C) 2014 TroggleMonkey
  3207. //
  3208. // Permission is hereby granted, free of charge, to any person obtaining a copy
  3209. // of this software and associated documentation files (the "Software"), to
  3210. // deal in the Software without restriction, including without limitation the
  3211. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  3212. // sell copies of the Software, and to permit persons to whom the Software is
  3213. // furnished to do so, subject to the following conditions:
  3214. //
  3215. // The above copyright notice and this permission notice shall be included in
  3216. // all copies or substantial portions of the Software.
  3217. //
  3218. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  3219. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  3220. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  3221. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  3222. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  3223. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  3224. // IN THE SOFTWARE.
  3225. ///////////////////////////////// DESCRIPTION ////////////////////////////////
  3226. // This file provides gamma-aware tex*D*() and encode_output() functions.
  3227. // Requires: Before #include-ing this file, the including file must #define
  3228. // the following macros when applicable and follow their rules:
  3229. // 1.) #define FIRST_PASS if this is the first pass.
  3230. // 2.) #define LAST_PASS if this is the last pass.
  3231. // 3.) If sRGB is available, set srgb_framebufferN = "true" for
  3232. // every pass except the last in your .cgp preset.
  3233. // 4.) If sRGB isn't available but you want gamma-correctness with
  3234. // no banding, #define GAMMA_ENCODE_EVERY_FBO each pass.
  3235. // 5.) #define SIMULATE_CRT_ON_LCD if desired (precedence over 5-7)
  3236. // 6.) #define SIMULATE_GBA_ON_LCD if desired (precedence over 6-7)
  3237. // 7.) #define SIMULATE_LCD_ON_CRT if desired (precedence over 7)
  3238. // 8.) #define SIMULATE_GBA_ON_CRT if desired (precedence over -)
  3239. // If an option in [5, 8] is #defined in the first or last pass, it
  3240. // should be #defined for both. It shouldn't make a difference
  3241. // whether it's #defined for intermediate passes or not.
  3242. // Optional: The including file (or an earlier included file) may optionally
  3243. // #define a number of macros indicating it will override certain
  3244. // macros and associated constants are as follows:
  3245. // static constants with either static or uniform constants. The
  3246. // 1.) OVERRIDE_STANDARD_GAMMA: The user must first define:
  3247. // static const float ntsc_gamma
  3248. // static const float pal_gamma
  3249. // static const float crt_reference_gamma_high
  3250. // static const float crt_reference_gamma_low
  3251. // static const float lcd_reference_gamma
  3252. // static const float crt_office_gamma
  3253. // static const float lcd_office_gamma
  3254. // 2.) OVERRIDE_DEVICE_GAMMA: The user must first define:
  3255. // static const float crt_gamma
  3256. // static const float gba_gamma
  3257. // static const float lcd_gamma
  3258. // 3.) OVERRIDE_FINAL_GAMMA: The user must first define:
  3259. // static const float input_gamma
  3260. // static const float intermediate_gamma
  3261. // static const float output_gamma
  3262. // (intermediate_gamma is for GAMMA_ENCODE_EVERY_FBO.)
  3263. // 4.) OVERRIDE_ALPHA_ASSUMPTIONS: The user must first define:
  3264. // static const bool assume_opaque_alpha
  3265. // The gamma constant overrides must be used in every pass or none,
  3266. // and OVERRIDE_FINAL_GAMMA bypasses all of the SIMULATE* macros.
  3267. // OVERRIDE_ALPHA_ASSUMPTIONS may be set on a per-pass basis.
  3268. // Usage: After setting macros appropriately, ignore gamma correction and
  3269. // replace all tex*D*() calls with equivalent gamma-aware
  3270. // tex*D*_linearize calls, except:
  3271. // 1.) When you read an LUT, use regular tex*D or a gamma-specified
  3272. // function, depending on its gamma encoding:
  3273. // tex*D*_linearize_gamma (takes a runtime gamma parameter)
  3274. // 2.) If you must read pass0's original input in a later pass, use
  3275. // tex2D_linearize_ntsc_gamma. If you want to read pass0's
  3276. // input with gamma-corrected bilinear filtering, consider
  3277. // creating a first linearizing pass and reading from the input
  3278. // of pass1 later.
  3279. // Then, return encode_output(color) from every fragment shader.
  3280. // Finally, use the global gamma_aware_bilinear boolean if you want
  3281. // to statically branch based on whether bilinear filtering is
  3282. // gamma-correct or not (e.g. for placing Gaussian blur samples).
  3283. //
  3284. // Detailed Policy:
  3285. // tex*D*_linearize() functions enforce a consistent gamma-management policy
  3286. // based on the FIRST_PASS and GAMMA_ENCODE_EVERY_FBO settings. They assume
  3287. // their input texture has the same encoding characteristics as the input for
  3288. // the current pass (which doesn't apply to the exceptions listed above).
  3289. // Similarly, encode_output() enforces a policy based on the LAST_PASS and
  3290. // GAMMA_ENCODE_EVERY_FBO settings. Together, they result in one of the
  3291. // following two pipelines.
  3292. // Typical pipeline with intermediate sRGB framebuffers:
  3293. // linear_color = pow(pass0_encoded_color, input_gamma);
  3294. // intermediate_output = linear_color; // Automatic sRGB encoding
  3295. // linear_color = intermediate_output; // Automatic sRGB decoding
  3296. // final_output = pow(intermediate_output, 1.0/output_gamma);
  3297. // Typical pipeline without intermediate sRGB framebuffers:
  3298. // linear_color = pow(pass0_encoded_color, input_gamma);
  3299. // intermediate_output = pow(linear_color, 1.0/intermediate_gamma);
  3300. // linear_color = pow(intermediate_output, intermediate_gamma);
  3301. // final_output = pow(intermediate_output, 1.0/output_gamma);
  3302. // Using GAMMA_ENCODE_EVERY_FBO is much slower, but it's provided as a way to
  3303. // easily get gamma-correctness without banding on devices where sRGB isn't
  3304. // supported.
  3305. //
  3306. // Use This Header to Maximize Code Reuse:
  3307. // The purpose of this header is to provide a consistent interface for texture
  3308. // reads and output gamma-encoding that localizes and abstracts away all the
  3309. // annoying details. This greatly reduces the amount of code in each shader
  3310. // pass that depends on the pass number in the .cgp preset or whether sRGB
  3311. // FBO's are being used: You can trivially change the gamma behavior of your
  3312. // whole pass by commenting or uncommenting 1-3 #defines. To reuse the same
  3313. // code in your first, Nth, and last passes, you can even put it all in another
  3314. // header file and #include it from skeleton .cg files that #define the
  3315. // appropriate pass-specific settings.
  3316. //
  3317. // Rationale for Using Three Macros:
  3318. // This file uses GAMMA_ENCODE_EVERY_FBO instead of an opposite macro like
  3319. // SRGB_PIPELINE to ensure sRGB is assumed by default, which hopefully imposes
  3320. // a lower maintenance burden on each pass. At first glance it seems we could
  3321. // accomplish everything with two macros: GAMMA_CORRECT_IN / GAMMA_CORRECT_OUT.
  3322. // This works for simple use cases where input_gamma == output_gamma, but it
  3323. // breaks down for more complex scenarios like CRT simulation, where the pass
  3324. // number determines the gamma encoding of the input and output.
  3325. /////////////////////////////// BASE CONSTANTS ///////////////////////////////
  3326. // Set standard gamma constants, but allow users to override them:
  3327. #ifndef OVERRIDE_STANDARD_GAMMA
  3328. // Standard encoding gammas:
  3329. static const float ntsc_gamma = 2.2; // Best to use NTSC for PAL too?
  3330. static const float pal_gamma = 2.8; // Never actually 2.8 in practice
  3331. // Typical device decoding gammas (only use for emulating devices):
  3332. // CRT/LCD reference gammas are higher than NTSC and Rec.709 video standard
  3333. // gammas: The standards purposely undercorrected for an analog CRT's
  3334. // assumed 2.5 reference display gamma to maintain contrast in assumed
  3335. // [dark] viewing conditions: http://www.poynton.com/PDFs/GammaFAQ.pdf
  3336. // These unstated assumptions about display gamma and perceptual rendering
  3337. // intent caused a lot of confusion, and more modern CRT's seemed to target
  3338. // NTSC 2.2 gamma with circuitry. LCD displays seem to have followed suit
  3339. // (they struggle near black with 2.5 gamma anyway), especially PC/laptop
  3340. // displays designed to view sRGB in bright environments. (Standards are
  3341. // also in flux again with BT.1886, but it's underspecified for displays.)
  3342. static const float crt_reference_gamma_high = 2.5; // In (2.35, 2.55)
  3343. static const float crt_reference_gamma_low = 2.35; // In (2.35, 2.55)
  3344. static const float lcd_reference_gamma = 2.5; // To match CRT
  3345. static const float crt_office_gamma = 2.2; // Circuitry-adjusted for NTSC
  3346. static const float lcd_office_gamma = 2.2; // Approximates sRGB
  3347. #endif // OVERRIDE_STANDARD_GAMMA
  3348. // Assuming alpha == 1.0 might make it easier for users to avoid some bugs,
  3349. // but only if they're aware of it.
  3350. #ifndef OVERRIDE_ALPHA_ASSUMPTIONS
  3351. static const bool assume_opaque_alpha = false;
  3352. #endif
  3353. /////////////////////// DERIVED CONSTANTS AS FUNCTIONS ///////////////////////
  3354. // gamma-management.h should be compatible with overriding gamma values with
  3355. // runtime user parameters, but we can only define other global constants in
  3356. // terms of static constants, not uniform user parameters. To get around this
  3357. // limitation, we need to define derived constants using functions.
  3358. // Set device gamma constants, but allow users to override them:
  3359. #ifdef OVERRIDE_DEVICE_GAMMA
  3360. // The user promises to globally define the appropriate constants:
  3361. inline float get_crt_gamma() { return crt_gamma; }
  3362. inline float get_gba_gamma() { return gba_gamma; }
  3363. inline float get_lcd_gamma() { return lcd_gamma; }
  3364. #else
  3365. inline float get_crt_gamma() { return crt_reference_gamma_high; }
  3366. inline float get_gba_gamma() { return 3.5; } // Game Boy Advance; in (3.0, 4.0)
  3367. inline float get_lcd_gamma() { return lcd_office_gamma; }
  3368. #endif // OVERRIDE_DEVICE_GAMMA
  3369. // Set decoding/encoding gammas for the first/lass passes, but allow overrides:
  3370. #ifdef OVERRIDE_FINAL_GAMMA
  3371. // The user promises to globally define the appropriate constants:
  3372. inline float get_intermediate_gamma() { return intermediate_gamma; }
  3373. inline float get_input_gamma() { return input_gamma; }
  3374. inline float get_output_gamma() { return output_gamma; }
  3375. #else
  3376. // If we gamma-correct every pass, always use ntsc_gamma between passes to
  3377. // ensure middle passes don't need to care if anything is being simulated:
  3378. inline float get_intermediate_gamma() { return ntsc_gamma; }
  3379. #ifdef SIMULATE_CRT_ON_LCD
  3380. inline float get_input_gamma() { return get_crt_gamma(); }
  3381. inline float get_output_gamma() { return get_lcd_gamma(); }
  3382. #else
  3383. #ifdef SIMULATE_GBA_ON_LCD
  3384. inline float get_input_gamma() { return get_gba_gamma(); }
  3385. inline float get_output_gamma() { return get_lcd_gamma(); }
  3386. #else
  3387. #ifdef SIMULATE_LCD_ON_CRT
  3388. inline float get_input_gamma() { return get_lcd_gamma(); }
  3389. inline float get_output_gamma() { return get_crt_gamma(); }
  3390. #else
  3391. #ifdef SIMULATE_GBA_ON_CRT
  3392. inline float get_input_gamma() { return get_gba_gamma(); }
  3393. inline float get_output_gamma() { return get_crt_gamma(); }
  3394. #else // Don't simulate anything:
  3395. inline float get_input_gamma() { return ntsc_gamma; }
  3396. inline float get_output_gamma() { return ntsc_gamma; }
  3397. #endif // SIMULATE_GBA_ON_CRT
  3398. #endif // SIMULATE_LCD_ON_CRT
  3399. #endif // SIMULATE_GBA_ON_LCD
  3400. #endif // SIMULATE_CRT_ON_LCD
  3401. #endif // OVERRIDE_FINAL_GAMMA
  3402. // Set decoding/encoding gammas for the current pass. Use static constants for
  3403. // linearize_input and gamma_encode_output, because they aren't derived, and
  3404. // they let the compiler do dead-code elimination.
  3405. #ifndef GAMMA_ENCODE_EVERY_FBO
  3406. #ifdef FIRST_PASS
  3407. static const bool linearize_input = true;
  3408. inline float get_pass_input_gamma() { return get_input_gamma(); }
  3409. #else
  3410. static const bool linearize_input = false;
  3411. inline float get_pass_input_gamma() { return 1.0; }
  3412. #endif
  3413. #ifdef LAST_PASS
  3414. static const bool gamma_encode_output = true;
  3415. inline float get_pass_output_gamma() { return get_output_gamma(); }
  3416. #else
  3417. static const bool gamma_encode_output = false;
  3418. inline float get_pass_output_gamma() { return 1.0; }
  3419. #endif
  3420. #else
  3421. static const bool linearize_input = true;
  3422. static const bool gamma_encode_output = true;
  3423. #ifdef FIRST_PASS
  3424. inline float get_pass_input_gamma() { return get_input_gamma(); }
  3425. #else
  3426. inline float get_pass_input_gamma() { return get_intermediate_gamma(); }
  3427. #endif
  3428. #ifdef LAST_PASS
  3429. inline float get_pass_output_gamma() { return get_output_gamma(); }
  3430. #else
  3431. inline float get_pass_output_gamma() { return get_intermediate_gamma(); }
  3432. #endif
  3433. #endif
  3434. // Users might want to know if bilinear filtering will be gamma-correct:
  3435. static const bool gamma_aware_bilinear = !linearize_input;
  3436. ////////////////////// COLOR ENCODING/DECODING FUNCTIONS /////////////////////
  3437. inline float4 encode_output(const float4 color)
  3438. {
  3439. if(gamma_encode_output)
  3440. {
  3441. if(assume_opaque_alpha)
  3442. {
  3443. return float4(pow(color.rgb, float3(1.0/get_pass_output_gamma())), 1.0);
  3444. }
  3445. else
  3446. {
  3447. return float4(pow(color.rgb, float3(1.0/get_pass_output_gamma())), color.a);
  3448. }
  3449. }
  3450. else
  3451. {
  3452. return color;
  3453. }
  3454. }
  3455. inline float4 decode_input(const float4 color)
  3456. {
  3457. if(linearize_input)
  3458. {
  3459. if(assume_opaque_alpha)
  3460. {
  3461. return float4(pow(color.rgb, float3(get_pass_input_gamma())), 1.0);
  3462. }
  3463. else
  3464. {
  3465. return float4(pow(color.rgb, float3(get_pass_input_gamma())), color.a);
  3466. }
  3467. }
  3468. else
  3469. {
  3470. return color;
  3471. }
  3472. }
  3473. inline float4 decode_gamma_input(const float4 color, const float3 gamma)
  3474. {
  3475. if(assume_opaque_alpha)
  3476. {
  3477. return float4(pow(color.rgb, gamma), 1.0);
  3478. }
  3479. else
  3480. {
  3481. return float4(pow(color.rgb, gamma), color.a);
  3482. }
  3483. }
  3484. //TODO/FIXME: I have no idea why replacing the lookup wrappers with this macro fixes the blurs being offset ¯\_(ツ)_/¯
  3485. //#define tex2D_linearize(C, D) decode_input(vec4(texture(C, D)))
  3486. // EDIT: it's the 'const' in front of the coords that's doing it
  3487. /////////////////////////// TEXTURE LOOKUP WRAPPERS //////////////////////////
  3488. // "SMART" LINEARIZING TEXTURE LOOKUP FUNCTIONS:
  3489. // Provide a wide array of linearizing texture lookup wrapper functions. The
  3490. // Cg shader spec Retroarch uses only allows for 2D textures, but 1D and 3D
  3491. // lookups are provided for completeness in case that changes someday. Nobody
  3492. // is likely to use the *fetch and *proj functions, but they're included just
  3493. // in case. The only tex*D texture sampling functions omitted are:
  3494. // - tex*Dcmpbias
  3495. // - tex*Dcmplod
  3496. // - tex*DARRAY*
  3497. // - tex*DMS*
  3498. // - Variants returning integers
  3499. // Standard line length restrictions are ignored below for vertical brevity.
  3500. /*
  3501. // tex1D:
  3502. inline float4 tex1D_linearize(const sampler1D tex, const float tex_coords)
  3503. { return decode_input(tex1D(tex, tex_coords)); }
  3504. inline float4 tex1D_linearize(const sampler1D tex, const float2 tex_coords)
  3505. { return decode_input(tex1D(tex, tex_coords)); }
  3506. inline float4 tex1D_linearize(const sampler1D tex, const float tex_coords, const int texel_off)
  3507. { return decode_input(tex1D(tex, tex_coords, texel_off)); }
  3508. inline float4 tex1D_linearize(const sampler1D tex, const float2 tex_coords, const int texel_off)
  3509. { return decode_input(tex1D(tex, tex_coords, texel_off)); }
  3510. inline float4 tex1D_linearize(const sampler1D tex, const float tex_coords, const float dx, const float dy)
  3511. { return decode_input(tex1D(tex, tex_coords, dx, dy)); }
  3512. inline float4 tex1D_linearize(const sampler1D tex, const float2 tex_coords, const float dx, const float dy)
  3513. { return decode_input(tex1D(tex, tex_coords, dx, dy)); }
  3514. inline float4 tex1D_linearize(const sampler1D tex, const float tex_coords, const float dx, const float dy, const int texel_off)
  3515. { return decode_input(tex1D(tex, tex_coords, dx, dy, texel_off)); }
  3516. inline float4 tex1D_linearize(const sampler1D tex, const float2 tex_coords, const float dx, const float dy, const int texel_off)
  3517. { return decode_input(tex1D(tex, tex_coords, dx, dy, texel_off)); }
  3518. // tex1Dbias:
  3519. inline float4 tex1Dbias_linearize(const sampler1D tex, const float4 tex_coords)
  3520. { return decode_input(tex1Dbias(tex, tex_coords)); }
  3521. inline float4 tex1Dbias_linearize(const sampler1D tex, const float4 tex_coords, const int texel_off)
  3522. { return decode_input(tex1Dbias(tex, tex_coords, texel_off)); }
  3523. // tex1Dfetch:
  3524. inline float4 tex1Dfetch_linearize(const sampler1D tex, const int4 tex_coords)
  3525. { return decode_input(tex1Dfetch(tex, tex_coords)); }
  3526. inline float4 tex1Dfetch_linearize(const sampler1D tex, const int4 tex_coords, const int texel_off)
  3527. { return decode_input(tex1Dfetch(tex, tex_coords, texel_off)); }
  3528. // tex1Dlod:
  3529. inline float4 tex1Dlod_linearize(const sampler1D tex, const float4 tex_coords)
  3530. { return decode_input(tex1Dlod(tex, tex_coords)); }
  3531. inline float4 tex1Dlod_linearize(const sampler1D tex, const float4 tex_coords, const int texel_off)
  3532. { return decode_input(tex1Dlod(tex, tex_coords, texel_off)); }
  3533. // tex1Dproj:
  3534. inline float4 tex1Dproj_linearize(const sampler1D tex, const float2 tex_coords)
  3535. { return decode_input(tex1Dproj(tex, tex_coords)); }
  3536. inline float4 tex1Dproj_linearize(const sampler1D tex, const float3 tex_coords)
  3537. { return decode_input(tex1Dproj(tex, tex_coords)); }
  3538. inline float4 tex1Dproj_linearize(const sampler1D tex, const float2 tex_coords, const int texel_off)
  3539. { return decode_input(tex1Dproj(tex, tex_coords, texel_off)); }
  3540. inline float4 tex1Dproj_linearize(const sampler1D tex, const float3 tex_coords, const int texel_off)
  3541. { return decode_input(tex1Dproj(tex, tex_coords, texel_off)); }
  3542. */
  3543. // tex2D:
  3544. inline float4 tex2D_linearize(const sampler2D tex, float2 tex_coords)
  3545. { return decode_input(COMPAT_TEXTURE(tex, tex_coords)); }
  3546. inline float4 tex2D_linearize(const sampler2D tex, float3 tex_coords)
  3547. { return decode_input(COMPAT_TEXTURE(tex, tex_coords.xy)); }
  3548. inline float4 tex2D_linearize(const sampler2D tex, float2 tex_coords, int texel_off)
  3549. { return decode_input(textureLod(tex, tex_coords, texel_off)); }
  3550. inline float4 tex2D_linearize(const sampler2D tex, float3 tex_coords, int texel_off)
  3551. { return decode_input(textureLod(tex, tex_coords.xy, texel_off)); }
  3552. //inline float4 tex2D_linearize(const sampler2D tex, const float2 tex_coords, const float2 dx, const float2 dy)
  3553. //{ return decode_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy)); }
  3554. //inline float4 tex2D_linearize(const sampler2D tex, const float3 tex_coords, const float2 dx, const float2 dy)
  3555. //{ return decode_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy)); }
  3556. //inline float4 tex2D_linearize(const sampler2D tex, const float2 tex_coords, const float2 dx, const float2 dy, const int texel_off)
  3557. //{ return decode_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy, texel_off)); }
  3558. //inline float4 tex2D_linearize(const sampler2D tex, const float3 tex_coords, const float2 dx, const float2 dy, const int texel_off)
  3559. //{ return decode_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy, texel_off)); }
  3560. // tex2Dbias:
  3561. //inline float4 tex2Dbias_linearize(const sampler2D tex, const float4 tex_coords)
  3562. //{ return decode_input(tex2Dbias(tex, tex_coords)); }
  3563. //inline float4 tex2Dbias_linearize(const sampler2D tex, const float4 tex_coords, const int texel_off)
  3564. //{ return decode_input(tex2Dbias(tex, tex_coords, texel_off)); }
  3565. // tex2Dfetch:
  3566. //inline float4 tex2Dfetch_linearize(const sampler2D tex, const int4 tex_coords)
  3567. //{ return decode_input(tex2Dfetch(tex, tex_coords)); }
  3568. //inline float4 tex2Dfetch_linearize(const sampler2D tex, const int4 tex_coords, const int texel_off)
  3569. //{ return decode_input(tex2Dfetch(tex, tex_coords, texel_off)); }
  3570. // tex2Dlod:
  3571. inline float4 tex2Dlod_linearize(const sampler2D tex, float4 tex_coords)
  3572. { return decode_input(textureLod(tex, tex_coords.xy, 0.0)); }
  3573. inline float4 tex2Dlod_linearize(const sampler2D tex, float4 tex_coords, int texel_off)
  3574. { return decode_input(textureLod(tex, tex_coords.xy, texel_off)); }
  3575. /*
  3576. // tex2Dproj:
  3577. inline float4 tex2Dproj_linearize(const sampler2D tex, const float3 tex_coords)
  3578. { return decode_input(tex2Dproj(tex, tex_coords)); }
  3579. inline float4 tex2Dproj_linearize(const sampler2D tex, const float4 tex_coords)
  3580. { return decode_input(tex2Dproj(tex, tex_coords)); }
  3581. inline float4 tex2Dproj_linearize(const sampler2D tex, const float3 tex_coords, const int texel_off)
  3582. { return decode_input(tex2Dproj(tex, tex_coords, texel_off)); }
  3583. inline float4 tex2Dproj_linearize(const sampler2D tex, const float4 tex_coords, const int texel_off)
  3584. { return decode_input(tex2Dproj(tex, tex_coords, texel_off)); }
  3585. */
  3586. /*
  3587. // tex3D:
  3588. inline float4 tex3D_linearize(const sampler3D tex, const float3 tex_coords)
  3589. { return decode_input(tex3D(tex, tex_coords)); }
  3590. inline float4 tex3D_linearize(const sampler3D tex, const float3 tex_coords, const int texel_off)
  3591. { return decode_input(tex3D(tex, tex_coords, texel_off)); }
  3592. inline float4 tex3D_linearize(const sampler3D tex, const float3 tex_coords, const float3 dx, const float3 dy)
  3593. { return decode_input(tex3D(tex, tex_coords, dx, dy)); }
  3594. inline float4 tex3D_linearize(const sampler3D tex, const float3 tex_coords, const float3 dx, const float3 dy, const int texel_off)
  3595. { return decode_input(tex3D(tex, tex_coords, dx, dy, texel_off)); }
  3596. // tex3Dbias:
  3597. inline float4 tex3Dbias_linearize(const sampler3D tex, const float4 tex_coords)
  3598. { return decode_input(tex3Dbias(tex, tex_coords)); }
  3599. inline float4 tex3Dbias_linearize(const sampler3D tex, const float4 tex_coords, const int texel_off)
  3600. { return decode_input(tex3Dbias(tex, tex_coords, texel_off)); }
  3601. // tex3Dfetch:
  3602. inline float4 tex3Dfetch_linearize(const sampler3D tex, const int4 tex_coords)
  3603. { return decode_input(tex3Dfetch(tex, tex_coords)); }
  3604. inline float4 tex3Dfetch_linearize(const sampler3D tex, const int4 tex_coords, const int texel_off)
  3605. { return decode_input(tex3Dfetch(tex, tex_coords, texel_off)); }
  3606. // tex3Dlod:
  3607. inline float4 tex3Dlod_linearize(const sampler3D tex, const float4 tex_coords)
  3608. { return decode_input(tex3Dlod(tex, tex_coords)); }
  3609. inline float4 tex3Dlod_linearize(const sampler3D tex, const float4 tex_coords, const int texel_off)
  3610. { return decode_input(tex3Dlod(tex, tex_coords, texel_off)); }
  3611. // tex3Dproj:
  3612. inline float4 tex3Dproj_linearize(const sampler3D tex, const float4 tex_coords)
  3613. { return decode_input(tex3Dproj(tex, tex_coords)); }
  3614. inline float4 tex3Dproj_linearize(const sampler3D tex, const float4 tex_coords, const int texel_off)
  3615. { return decode_input(tex3Dproj(tex, tex_coords, texel_off)); }
  3616. /////////*
  3617. // NONSTANDARD "SMART" LINEARIZING TEXTURE LOOKUP FUNCTIONS:
  3618. // This narrow selection of nonstandard tex2D* functions can be useful:
  3619. // tex2Dlod0: Automatically fill in the tex2D LOD parameter for mip level 0.
  3620. //inline float4 tex2Dlod0_linearize(const sampler2D tex, const float2 tex_coords)
  3621. //{ return decode_input(tex2Dlod(tex, float4(tex_coords, 0.0, 0.0))); }
  3622. //inline float4 tex2Dlod0_linearize(const sampler2D tex, const float2 tex_coords, const int texel_off)
  3623. //{ return decode_input(tex2Dlod(tex, float4(tex_coords, 0.0, 0.0), texel_off)); }
  3624. // MANUALLY LINEARIZING TEXTURE LOOKUP FUNCTIONS:
  3625. // Provide a narrower selection of tex2D* wrapper functions that decode an
  3626. // input sample with a specified gamma value. These are useful for reading
  3627. // LUT's and for reading the input of pass0 in a later pass.
  3628. // tex2D:
  3629. inline float4 tex2D_linearize_gamma(const sampler2D tex, const float2 tex_coords, const float3 gamma)
  3630. { return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords), gamma); }
  3631. inline float4 tex2D_linearize_gamma(const sampler2D tex, const float3 tex_coords, const float3 gamma)
  3632. { return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords.xy), gamma); }
  3633. //inline float4 tex2D_linearize_gamma(const sampler2D tex, const float2 tex_coords, const int texel_off, const float3 gamma)
  3634. //{ return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords, texel_off), gamma); }
  3635. //inline float4 tex2D_linearize_gamma(const sampler2D tex, const float3 tex_coords, const int texel_off, const float3 gamma)
  3636. //{ return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords, texel_off), gamma); }
  3637. //inline float4 tex2D_linearize_gamma(const sampler2D tex, const float2 tex_coords, const float2 dx, const float2 dy, const float3 gamma)
  3638. //{ return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy), gamma); }
  3639. //inline float4 tex2D_linearize_gamma(const sampler2D tex, const float3 tex_coords, const float2 dx, const float2 dy, const float3 gamma)
  3640. //{ return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy), gamma); }
  3641. //inline float4 tex2D_linearize_gamma(const sampler2D tex, const float2 tex_coords, const float2 dx, const float2 dy, const int texel_off, const float3 gamma)
  3642. //{ return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy, texel_off), gamma); }
  3643. //inline float4 tex2D_linearize_gamma(const sampler2D tex, const float3 tex_coords, const float2 dx, const float2 dy, const int texel_off, const float3 gamma)
  3644. //{ return decode_gamma_input(COMPAT_TEXTURE(tex, tex_coords, dx, dy, texel_off), gamma); }
  3645. /*
  3646. // tex2Dbias:
  3647. inline float4 tex2Dbias_linearize_gamma(const sampler2D tex, const float4 tex_coords, const float3 gamma)
  3648. { return decode_gamma_input(tex2Dbias(tex, tex_coords), gamma); }
  3649. inline float4 tex2Dbias_linearize_gamma(const sampler2D tex, const float4 tex_coords, const int texel_off, const float3 gamma)
  3650. { return decode_gamma_input(tex2Dbias(tex, tex_coords, texel_off), gamma); }
  3651. // tex2Dfetch:
  3652. inline float4 tex2Dfetch_linearize_gamma(const sampler2D tex, const int4 tex_coords, const float3 gamma)
  3653. { return decode_gamma_input(tex2Dfetch(tex, tex_coords), gamma); }
  3654. inline float4 tex2Dfetch_linearize_gamma(const sampler2D tex, const int4 tex_coords, const int texel_off, const float3 gamma)
  3655. { return decode_gamma_input(tex2Dfetch(tex, tex_coords, texel_off), gamma); }
  3656. */
  3657. // tex2Dlod:
  3658. inline float4 tex2Dlod_linearize_gamma(const sampler2D tex, float4 tex_coords, float3 gamma)
  3659. { return decode_gamma_input(textureLod(tex, tex_coords.xy, 0.0), gamma); }
  3660. inline float4 tex2Dlod_linearize_gamma(const sampler2D tex, float4 tex_coords, int texel_off, float3 gamma)
  3661. { return decode_gamma_input(textureLod(tex, tex_coords.xy, texel_off), gamma); }
  3662. #endif // GAMMA_MANAGEMENT_H
  3663. //////////////////////////// END GAMMA-MANAGEMENT //////////////////////////
  3664. //////////////////////////////// END INCLUDES ////////////////////////////////
  3665. ///////////////////////////// SCANLINE FUNCTIONS /////////////////////////////
  3666. inline float3 get_gaussian_sigma(const float3 color, const float sigma_range)
  3667. {
  3668. // Requires: Globals:
  3669. // 1.) beam_min_sigma and beam_max_sigma are global floats
  3670. // containing the desired minimum and maximum beam standard
  3671. // deviations, for dim and bright colors respectively.
  3672. // 2.) beam_max_sigma must be > 0.0
  3673. // 3.) beam_min_sigma must be in (0.0, beam_max_sigma]
  3674. // 4.) beam_spot_power must be defined as a global float.
  3675. // Parameters:
  3676. // 1.) color is the underlying source color along a scanline
  3677. // 2.) sigma_range = beam_max_sigma - beam_min_sigma; we take
  3678. // sigma_range as a parameter to avoid repeated computation
  3679. // when beam_{min, max}_sigma are runtime shader parameters
  3680. // Optional: Users may set beam_spot_shape_function to 1 to define the
  3681. // inner f(color) subfunction (see below) as:
  3682. // f(color) = sqrt(1.0 - (color - 1.0)*(color - 1.0))
  3683. // Otherwise (technically, if beam_spot_shape_function < 0.5):
  3684. // f(color) = pow(color, beam_spot_power)
  3685. // Returns: The standard deviation of the Gaussian beam for "color:"
  3686. // sigma = beam_min_sigma + sigma_range * f(color)
  3687. // Details/Discussion:
  3688. // The beam's spot shape vaguely resembles an aspect-corrected f() in the
  3689. // range [0, 1] (not quite, but it's related). f(color) = color makes
  3690. // spots look like diamonds, and a spherical function or cube balances
  3691. // between variable width and a soft/realistic shape. A beam_spot_power
  3692. // > 1.0 can produce an ugly spot shape and more initial clipping, but the
  3693. // final shape also differs based on the horizontal resampling filter and
  3694. // the phosphor bloom. For instance, resampling horizontally in nonlinear
  3695. // light and/or with a sharp (e.g. Lanczos) filter will sharpen the spot
  3696. // shape, but a sixth root is still quite soft. A power function (default
  3697. // 1.0/3.0 beam_spot_power) is most flexible, but a fixed spherical curve
  3698. // has the highest variability without an awful spot shape.
  3699. //
  3700. // beam_min_sigma affects scanline sharpness/aliasing in dim areas, and its
  3701. // difference from beam_max_sigma affects beam width variability. It only
  3702. // affects clipping [for pure Gaussians] if beam_spot_power > 1.0 (which is
  3703. // a conservative estimate for a more complex constraint).
  3704. //
  3705. // beam_max_sigma affects clipping and increasing scanline width/softness
  3706. // as color increases. The wider this is, the more scanlines need to be
  3707. // evaluated to avoid distortion. For a pure Gaussian, the max_beam_sigma
  3708. // at which the first unused scanline always has a weight < 1.0/255.0 is:
  3709. // num scanlines = 2, max_beam_sigma = 0.2089; distortions begin ~0.34
  3710. // num scanlines = 3, max_beam_sigma = 0.3879; distortions begin ~0.52
  3711. // num scanlines = 4, max_beam_sigma = 0.5723; distortions begin ~0.70
  3712. // num scanlines = 5, max_beam_sigma = 0.7591; distortions begin ~0.89
  3713. // num scanlines = 6, max_beam_sigma = 0.9483; distortions begin ~1.08
  3714. // Generalized Gaussians permit more leeway here as steepness increases.
  3715. if(beam_spot_shape_function < 0.5)
  3716. {
  3717. // Use a power function:
  3718. return float3(beam_min_sigma) + sigma_range *
  3719. pow(color, float3(beam_spot_power));
  3720. }
  3721. else
  3722. {
  3723. // Use a spherical function:
  3724. const float3 color_minus_1 = color - float3(1.0);
  3725. return float3(beam_min_sigma) + sigma_range *
  3726. sqrt(float3(1.0) - color_minus_1*color_minus_1);
  3727. }
  3728. }
  3729. inline float3 get_generalized_gaussian_beta(const float3 color,
  3730. const float shape_range)
  3731. {
  3732. // Requires: Globals:
  3733. // 1.) beam_min_shape and beam_max_shape are global floats
  3734. // containing the desired min/max generalized Gaussian
  3735. // beta parameters, for dim and bright colors respectively.
  3736. // 2.) beam_max_shape must be >= 2.0
  3737. // 3.) beam_min_shape must be in [2.0, beam_max_shape]
  3738. // 4.) beam_shape_power must be defined as a global float.
  3739. // Parameters:
  3740. // 1.) color is the underlying source color along a scanline
  3741. // 2.) shape_range = beam_max_shape - beam_min_shape; we take
  3742. // shape_range as a parameter to avoid repeated computation
  3743. // when beam_{min, max}_shape are runtime shader parameters
  3744. // Returns: The type-I generalized Gaussian "shape" parameter beta for
  3745. // the given color.
  3746. // Details/Discussion:
  3747. // Beta affects the scanline distribution as follows:
  3748. // a.) beta < 2.0 narrows the peak to a spike with a discontinuous slope
  3749. // b.) beta == 2.0 just degenerates to a Gaussian
  3750. // c.) beta > 2.0 flattens and widens the peak, then drops off more steeply
  3751. // than a Gaussian. Whereas high sigmas widen and soften peaks, high
  3752. // beta widen and sharpen peaks at the risk of aliasing.
  3753. // Unlike high beam_spot_powers, high beam_shape_powers actually soften shape
  3754. // transitions, whereas lower ones sharpen them (at the risk of aliasing).
  3755. return beam_min_shape + shape_range * pow(color, float3(beam_shape_power));
  3756. }
  3757. float3 scanline_gaussian_integral_contrib(const float3 dist,
  3758. const float3 color, const float pixel_height, const float sigma_range)
  3759. {
  3760. // Requires: 1.) dist is the distance of the [potentially separate R/G/B]
  3761. // point(s) from a scanline in units of scanlines, where
  3762. // 1.0 means the sample point straddles the next scanline.
  3763. // 2.) color is the underlying source color along a scanline.
  3764. // 3.) pixel_height is the output pixel height in scanlines.
  3765. // 4.) Requirements of get_gaussian_sigma() must be met.
  3766. // Returns: Return a scanline's light output over a given pixel.
  3767. // Details:
  3768. // The CRT beam profile follows a roughly Gaussian distribution which is
  3769. // wider for bright colors than dark ones. The integral over the full
  3770. // range of a Gaussian function is always 1.0, so we can vary the beam
  3771. // with a standard deviation without affecting brightness. 'x' = distance:
  3772. // gaussian sample = 1/(sigma*sqrt(2*pi)) * e**(-(x**2)/(2*sigma**2))
  3773. // gaussian integral = 0.5 (1.0 + erf(x/(sigma * sqrt(2))))
  3774. // Use a numerical approximation of the "error function" (the Gaussian
  3775. // indefinite integral) to find the definite integral of the scanline's
  3776. // average brightness over a given pixel area. Even if curved coords were
  3777. // used in this pass, a flat scalar pixel height works almost as well as a
  3778. // pixel height computed from a full pixel-space to scanline-space matrix.
  3779. const float3 sigma = get_gaussian_sigma(color, sigma_range);
  3780. const float3 ph_offset = float3(pixel_height * 0.5);
  3781. const float3 denom_inv = 1.0/(sigma*sqrt(2.0));
  3782. const float3 integral_high = erf((dist + ph_offset)*denom_inv);
  3783. const float3 integral_low = erf((dist - ph_offset)*denom_inv);
  3784. return color * 0.5*(integral_high - integral_low)/pixel_height;
  3785. }
  3786. float3 scanline_generalized_gaussian_integral_contrib(float3 dist,
  3787. float3 color, float pixel_height, float sigma_range,
  3788. float shape_range)
  3789. {
  3790. // Requires: 1.) Requirements of scanline_gaussian_integral_contrib()
  3791. // must be met.
  3792. // 2.) Requirements of get_gaussian_sigma() must be met.
  3793. // 3.) Requirements of get_generalized_gaussian_beta() must be
  3794. // met.
  3795. // Returns: Return a scanline's light output over a given pixel.
  3796. // A generalized Gaussian distribution allows the shape (beta) to vary
  3797. // as well as the width (alpha). "gamma" refers to the gamma function:
  3798. // generalized sample =
  3799. // beta/(2*alpha*gamma(1/beta)) * e**(-(|x|/alpha)**beta)
  3800. // ligamma(s, z) is the lower incomplete gamma function, for which we only
  3801. // implement two of four branches (because we keep 1/beta <= 0.5):
  3802. // generalized integral = 0.5 + 0.5* sign(x) *
  3803. // ligamma(1/beta, (|x|/alpha)**beta)/gamma(1/beta)
  3804. // See get_generalized_gaussian_beta() for a discussion of beta.
  3805. // We base alpha on the intended Gaussian sigma, but it only strictly
  3806. // models models standard deviation at beta == 2, because the standard
  3807. // deviation depends on both alpha and beta (keeping alpha independent is
  3808. // faster and preserves intuitive behavior and a full spectrum of results).
  3809. const float3 alpha = sqrt(2.0) * get_gaussian_sigma(color, sigma_range);
  3810. const float3 beta = get_generalized_gaussian_beta(color, shape_range);
  3811. const float3 alpha_inv = float3(1.0)/alpha;
  3812. const float3 s = float3(1.0)/beta;
  3813. const float3 ph_offset = float3(pixel_height * 0.5);
  3814. // Pass beta to gamma_impl to avoid repeated divides. Similarly pass
  3815. // beta (i.e. 1/s) and 1/gamma(s) to normalized_ligamma_impl.
  3816. const float3 gamma_s_inv = float3(1.0)/gamma_impl(s, beta);
  3817. const float3 dist1 = dist + ph_offset;
  3818. const float3 dist0 = dist - ph_offset;
  3819. const float3 integral_high = sign(dist1) * normalized_ligamma_impl(
  3820. s, pow(abs(dist1)*alpha_inv, beta), beta, gamma_s_inv);
  3821. const float3 integral_low = sign(dist0) * normalized_ligamma_impl(
  3822. s, pow(abs(dist0)*alpha_inv, beta), beta, gamma_s_inv);
  3823. return color * 0.5*(integral_high - integral_low)/pixel_height;
  3824. }
  3825. float3 scanline_gaussian_sampled_contrib(const float3 dist, const float3 color,
  3826. const float pixel_height, const float sigma_range)
  3827. {
  3828. // See scanline_gaussian integral_contrib() for detailed comments!
  3829. // gaussian sample = 1/(sigma*sqrt(2*pi)) * e**(-(x**2)/(2*sigma**2))
  3830. const float3 sigma = get_gaussian_sigma(color, sigma_range);
  3831. // Avoid repeated divides:
  3832. const float3 sigma_inv = float3(1.0)/sigma;
  3833. const float3 inner_denom_inv = 0.5 * sigma_inv * sigma_inv;
  3834. const float3 outer_denom_inv = sigma_inv/sqrt(2.0*pi);
  3835. if(beam_antialias_level > 0.5)
  3836. {
  3837. // Sample 1/3 pixel away in each direction as well:
  3838. const float3 sample_offset = float3(pixel_height/3.0);
  3839. const float3 dist2 = dist + sample_offset;
  3840. const float3 dist3 = abs(dist - sample_offset);
  3841. // Average three pure Gaussian samples:
  3842. const float3 scale = color/3.0 * outer_denom_inv;
  3843. const float3 weight1 = exp(-(dist*dist)*inner_denom_inv);
  3844. const float3 weight2 = exp(-(dist2*dist2)*inner_denom_inv);
  3845. const float3 weight3 = exp(-(dist3*dist3)*inner_denom_inv);
  3846. return scale * (weight1 + weight2 + weight3);
  3847. }
  3848. else
  3849. {
  3850. return color*exp(-(dist*dist)*inner_denom_inv)*outer_denom_inv;
  3851. }
  3852. }
  3853. float3 scanline_generalized_gaussian_sampled_contrib(float3 dist,
  3854. float3 color, float pixel_height, float sigma_range,
  3855. float shape_range)
  3856. {
  3857. // See scanline_generalized_gaussian_integral_contrib() for details!
  3858. // generalized sample =
  3859. // beta/(2*alpha*gamma(1/beta)) * e**(-(|x|/alpha)**beta)
  3860. const float3 alpha = sqrt(2.0) * get_gaussian_sigma(color, sigma_range);
  3861. const float3 beta = get_generalized_gaussian_beta(color, shape_range);
  3862. // Avoid repeated divides:
  3863. const float3 alpha_inv = float3(1.0)/alpha;
  3864. const float3 beta_inv = float3(1.0)/beta;
  3865. const float3 scale = color * beta * 0.5 * alpha_inv /
  3866. gamma_impl(beta_inv, beta);
  3867. if(beam_antialias_level > 0.5)
  3868. {
  3869. // Sample 1/3 pixel closer to and farther from the scanline too.
  3870. const float3 sample_offset = float3(pixel_height/3.0);
  3871. const float3 dist2 = dist + sample_offset;
  3872. const float3 dist3 = abs(dist - sample_offset);
  3873. // Average three generalized Gaussian samples:
  3874. const float3 weight1 = exp(-pow(abs(dist*alpha_inv), beta));
  3875. const float3 weight2 = exp(-pow(abs(dist2*alpha_inv), beta));
  3876. const float3 weight3 = exp(-pow(abs(dist3*alpha_inv), beta));
  3877. return scale/3.0 * (weight1 + weight2 + weight3);
  3878. }
  3879. else
  3880. {
  3881. return scale * exp(-pow(abs(dist*alpha_inv), beta));
  3882. }
  3883. }
  3884. inline float3 scanline_contrib(float3 dist, float3 color,
  3885. float pixel_height, const float sigma_range, const float shape_range)
  3886. {
  3887. // Requires: 1.) Requirements of scanline_gaussian_integral_contrib()
  3888. // must be met.
  3889. // 2.) Requirements of get_gaussian_sigma() must be met.
  3890. // 3.) Requirements of get_generalized_gaussian_beta() must be
  3891. // met.
  3892. // Returns: Return a scanline's light output over a given pixel, using
  3893. // a generalized or pure Gaussian distribution and sampling or
  3894. // integrals as desired by user codepath choices.
  3895. if(beam_generalized_gaussian)
  3896. {
  3897. if(beam_antialias_level > 1.5)
  3898. {
  3899. return scanline_generalized_gaussian_integral_contrib(
  3900. dist, color, pixel_height, sigma_range, shape_range);
  3901. }
  3902. else
  3903. {
  3904. return scanline_generalized_gaussian_sampled_contrib(
  3905. dist, color, pixel_height, sigma_range, shape_range);
  3906. }
  3907. }
  3908. else
  3909. {
  3910. if(beam_antialias_level > 1.5)
  3911. {
  3912. return scanline_gaussian_integral_contrib(
  3913. dist, color, pixel_height, sigma_range);
  3914. }
  3915. else
  3916. {
  3917. return scanline_gaussian_sampled_contrib(
  3918. dist, color, pixel_height, sigma_range);
  3919. }
  3920. }
  3921. }
  3922. inline float3 get_raw_interpolated_color(const float3 color0,
  3923. const float3 color1, const float3 color2, const float3 color3,
  3924. const float4 weights)
  3925. {
  3926. // Use max to avoid bizarre artifacts from negative colors:
  3927. return max(mul(weights, float4x3(color0, color1, color2, color3)), 0.0);
  3928. }
  3929. float3 get_interpolated_linear_color(const float3 color0, const float3 color1,
  3930. const float3 color2, const float3 color3, const float4 weights)
  3931. {
  3932. // Requires: 1.) Requirements of include/gamma-management.h must be met:
  3933. // intermediate_gamma must be globally defined, and input
  3934. // colors are interpreted as linear RGB unless you #define
  3935. // GAMMA_ENCODE_EVERY_FBO (in which case they are
  3936. // interpreted as gamma-encoded with intermediate_gamma).
  3937. // 2.) color0-3 are colors sampled from a texture with tex2D().
  3938. // They are interpreted as defined in requirement 1.
  3939. // 3.) weights contains weights for each color, summing to 1.0.
  3940. // 4.) beam_horiz_linear_rgb_weight must be defined as a global
  3941. // float in [0.0, 1.0] describing how much blending should
  3942. // be done in linear RGB (rest is gamma-corrected RGB).
  3943. // 5.) RUNTIME_SCANLINES_HORIZ_FILTER_COLORSPACE must be #defined
  3944. // if beam_horiz_linear_rgb_weight is anything other than a
  3945. // static constant, or we may try branching at runtime
  3946. // without dynamic branches allowed (slow).
  3947. // Returns: Return an interpolated color lookup between the four input
  3948. // colors based on the weights in weights. The final color will
  3949. // be a linear RGB value, but the blending will be done as
  3950. // indicated above.
  3951. const float intermediate_gamma = get_intermediate_gamma();
  3952. // Branch if beam_horiz_linear_rgb_weight is static (for free) or if the
  3953. // profile allows dynamic branches (faster than computing extra pows):
  3954. #ifndef RUNTIME_SCANLINES_HORIZ_FILTER_COLORSPACE
  3955. #define SCANLINES_BRANCH_FOR_LINEAR_RGB_WEIGHT
  3956. #else
  3957. #ifdef DRIVERS_ALLOW_DYNAMIC_BRANCHES
  3958. #define SCANLINES_BRANCH_FOR_LINEAR_RGB_WEIGHT
  3959. #endif
  3960. #endif
  3961. #ifdef SCANLINES_BRANCH_FOR_LINEAR_RGB_WEIGHT
  3962. // beam_horiz_linear_rgb_weight is static, so we can branch:
  3963. #ifdef GAMMA_ENCODE_EVERY_FBO
  3964. const float3 gamma_mixed_color = pow(get_raw_interpolated_color(
  3965. color0, color1, color2, color3, weights), float3(intermediate_gamma));
  3966. if(beam_horiz_linear_rgb_weight > 0.0)
  3967. {
  3968. const float3 linear_mixed_color = get_raw_interpolated_color(
  3969. pow(color0, float3(intermediate_gamma)),
  3970. pow(color1, float3(intermediate_gamma)),
  3971. pow(color2, float3(intermediate_gamma)),
  3972. pow(color3, float3(intermediate_gamma)),
  3973. weights);
  3974. return lerp(gamma_mixed_color, linear_mixed_color,
  3975. beam_horiz_linear_rgb_weight);
  3976. }
  3977. else
  3978. {
  3979. return gamma_mixed_color;
  3980. }
  3981. #else
  3982. const float3 linear_mixed_color = get_raw_interpolated_color(
  3983. color0, color1, color2, color3, weights);
  3984. if(beam_horiz_linear_rgb_weight < 1.0)
  3985. {
  3986. const float3 gamma_mixed_color = get_raw_interpolated_color(
  3987. pow(color0, float3(1.0/intermediate_gamma)),
  3988. pow(color1, float3(1.0/intermediate_gamma)),
  3989. pow(color2, float3(1.0/intermediate_gamma)),
  3990. pow(color3, float3(1.0/intermediate_gamma)),
  3991. weights);
  3992. return lerp(gamma_mixed_color, linear_mixed_color,
  3993. beam_horiz_linear_rgb_weight);
  3994. }
  3995. else
  3996. {
  3997. return linear_mixed_color;
  3998. }
  3999. #endif // GAMMA_ENCODE_EVERY_FBO
  4000. #else
  4001. #ifdef GAMMA_ENCODE_EVERY_FBO
  4002. // Inputs: color0-3 are colors in gamma-encoded RGB.
  4003. const float3 gamma_mixed_color = pow(get_raw_interpolated_color(
  4004. color0, color1, color2, color3, weights), intermediate_gamma);
  4005. const float3 linear_mixed_color = get_raw_interpolated_color(
  4006. pow(color0, float3(intermediate_gamma)),
  4007. pow(color1, float3(intermediate_gamma)),
  4008. pow(color2, float3(intermediate_gamma)),
  4009. pow(color3, float3(intermediate_gamma)),
  4010. weights);
  4011. return lerp(gamma_mixed_color, linear_mixed_color,
  4012. beam_horiz_linear_rgb_weight);
  4013. #else
  4014. // Inputs: color0-3 are colors in linear RGB.
  4015. const float3 linear_mixed_color = get_raw_interpolated_color(
  4016. color0, color1, color2, color3, weights);
  4017. const float3 gamma_mixed_color = get_raw_interpolated_color(
  4018. pow(color0, float3(1.0/intermediate_gamma)),
  4019. pow(color1, float3(1.0/intermediate_gamma)),
  4020. pow(color2, float3(1.0/intermediate_gamma)),
  4021. pow(color3, float3(1.0/intermediate_gamma)),
  4022. weights);
  4023. // wtf fixme
  4024. // const float beam_horiz_linear_rgb_weight1 = 1.0;
  4025. return lerp(gamma_mixed_color, linear_mixed_color,
  4026. beam_horiz_linear_rgb_weight);
  4027. #endif // GAMMA_ENCODE_EVERY_FBO
  4028. #endif // SCANLINES_BRANCH_FOR_LINEAR_RGB_WEIGHT
  4029. }
  4030. float3 get_scanline_color(const sampler2D tex, const float2 scanline_uv,
  4031. const float2 uv_step_x, const float4 weights)
  4032. {
  4033. // Requires: 1.) scanline_uv must be vertically snapped to the caller's
  4034. // desired line or scanline and horizontally snapped to the
  4035. // texel just left of the output pixel (color1)
  4036. // 2.) uv_step_x must contain the horizontal uv distance
  4037. // between texels.
  4038. // 3.) weights must contain interpolation filter weights for
  4039. // color0, color1, color2, and color3, where color1 is just
  4040. // left of the output pixel.
  4041. // Returns: Return a horizontally interpolated texture lookup using 2-4
  4042. // nearby texels, according to weights and the conventions of
  4043. // get_interpolated_linear_color().
  4044. // We can ignore the outside texture lookups for Quilez resampling.
  4045. const float3 color1 = COMPAT_TEXTURE(tex, scanline_uv).rgb;
  4046. const float3 color2 = COMPAT_TEXTURE(tex, scanline_uv + uv_step_x).rgb;
  4047. float3 color0 = float3(0.0);
  4048. float3 color3 = float3(0.0);
  4049. if(beam_horiz_filter > 0.5)
  4050. {
  4051. color0 = COMPAT_TEXTURE(tex, scanline_uv - uv_step_x).rgb;
  4052. color3 = COMPAT_TEXTURE(tex, scanline_uv + 2.0 * uv_step_x).rgb;
  4053. }
  4054. // Sample the texture as-is, whether it's linear or gamma-encoded:
  4055. // get_interpolated_linear_color() will handle the difference.
  4056. return get_interpolated_linear_color(color0, color1, color2, color3, weights);
  4057. }
  4058. float3 sample_single_scanline_horizontal(const sampler2D tex,
  4059. const float2 tex_uv, const float2 tex_size,
  4060. const float2 texture_size_inv)
  4061. {
  4062. // TODO: Add function requirements.
  4063. // Snap to the previous texel and get sample dists from 2/4 nearby texels:
  4064. const float2 curr_texel = tex_uv * tex_size;
  4065. // Use under_half to fix a rounding bug right around exact texel locations.
  4066. const float2 prev_texel =
  4067. floor(curr_texel - float2(under_half)) + float2(0.5);
  4068. const float2 prev_texel_hor = float2(prev_texel.x, curr_texel.y);
  4069. const float2 prev_texel_hor_uv = prev_texel_hor * texture_size_inv;
  4070. const float prev_dist = curr_texel.x - prev_texel_hor.x;
  4071. const float4 sample_dists = float4(1.0 + prev_dist, prev_dist,
  4072. 1.0 - prev_dist, 2.0 - prev_dist);
  4073. // Get Quilez, Lanczos2, or Gaussian resize weights for 2/4 nearby texels:
  4074. float4 weights;
  4075. if(beam_horiz_filter < 0.5)
  4076. {
  4077. // Quilez:
  4078. const float x = sample_dists.y;
  4079. const float w2 = x*x*x*(x*(x*6.0 - 15.0) + 10.0);
  4080. weights = float4(0.0, 1.0 - w2, w2, 0.0);
  4081. }
  4082. else if(beam_horiz_filter < 1.5)
  4083. {
  4084. // Gaussian:
  4085. float inner_denom_inv = 1.0/(2.0*beam_horiz_sigma*beam_horiz_sigma);
  4086. weights = exp(-(sample_dists*sample_dists)*inner_denom_inv);
  4087. }
  4088. else
  4089. {
  4090. // Lanczos2:
  4091. const float4 pi_dists = FIX_ZERO(sample_dists * pi);
  4092. weights = 2.0 * sin(pi_dists) * sin(pi_dists * 0.5) /
  4093. (pi_dists * pi_dists);
  4094. }
  4095. // Ensure the weight sum == 1.0:
  4096. const float4 final_weights = weights/dot(weights, float4(1.0));
  4097. // Get the interpolated horizontal scanline color:
  4098. const float2 uv_step_x = float2(texture_size_inv.x, 0.0);
  4099. return get_scanline_color(
  4100. tex, prev_texel_hor_uv, uv_step_x, final_weights);
  4101. }
  4102. float3 sample_rgb_scanline_horizontal(const sampler2D tex,
  4103. const float2 tex_uv, const float2 tex_size,
  4104. const float2 texture_size_inv)
  4105. {
  4106. // TODO: Add function requirements.
  4107. // Rely on a helper to make convergence easier.
  4108. if(beam_misconvergence)
  4109. {
  4110. const float3 convergence_offsets_rgb =
  4111. get_convergence_offsets_x_vector();
  4112. const float3 offset_u_rgb =
  4113. convergence_offsets_rgb * texture_size_inv.xxx;
  4114. const float2 scanline_uv_r = tex_uv - float2(offset_u_rgb.r, 0.0);
  4115. const float2 scanline_uv_g = tex_uv - float2(offset_u_rgb.g, 0.0);
  4116. const float2 scanline_uv_b = tex_uv - float2(offset_u_rgb.b, 0.0);
  4117. const float3 sample_r = sample_single_scanline_horizontal(
  4118. tex, scanline_uv_r, tex_size, texture_size_inv);
  4119. const float3 sample_g = sample_single_scanline_horizontal(
  4120. tex, scanline_uv_g, tex_size, texture_size_inv);
  4121. const float3 sample_b = sample_single_scanline_horizontal(
  4122. tex, scanline_uv_b, tex_size, texture_size_inv);
  4123. return float3(sample_r.r, sample_g.g, sample_b.b);
  4124. }
  4125. else
  4126. {
  4127. return sample_single_scanline_horizontal(tex, tex_uv, tex_size,
  4128. texture_size_inv);
  4129. }
  4130. }
  4131. float2 get_last_scanline_uv(const float2 tex_uv, const float2 tex_size,
  4132. const float2 texture_size_inv, const float2 il_step_multiple,
  4133. const float frame_count, out float dist)
  4134. {
  4135. // Compute texture coords for the last/upper scanline, accounting for
  4136. // interlacing: With interlacing, only consider even/odd scanlines every
  4137. // other frame. Top-field first (TFF) order puts even scanlines on even
  4138. // frames, and BFF order puts them on odd frames. Texels are centered at:
  4139. // frac(tex_uv * tex_size) == x.5
  4140. // Caution: If these coordinates ever seem incorrect, first make sure it's
  4141. // not because anisotropic filtering is blurring across field boundaries.
  4142. // Note: TFF/BFF won't matter for sources that double-weave or similar.
  4143. // wtf fixme
  4144. // const float interlace_bff1 = 1.0;
  4145. const float field_offset = floor(il_step_multiple.y * 0.75) *
  4146. fmod(frame_count + float(interlace_bff), 2.0);
  4147. const float2 curr_texel = tex_uv * tex_size;
  4148. // Use under_half to fix a rounding bug right around exact texel locations.
  4149. const float2 prev_texel_num = floor(curr_texel - float2(under_half));
  4150. const float wrong_field = fmod(
  4151. prev_texel_num.y + field_offset, il_step_multiple.y);
  4152. const float2 scanline_texel_num = prev_texel_num - float2(0.0, wrong_field);
  4153. // Snap to the center of the previous scanline in the current field:
  4154. const float2 scanline_texel = scanline_texel_num + float2(0.5);
  4155. const float2 scanline_uv = scanline_texel * texture_size_inv;
  4156. // Save the sample's distance from the scanline, in units of scanlines:
  4157. dist = (curr_texel.y - scanline_texel.y)/il_step_multiple.y;
  4158. return scanline_uv;
  4159. }
  4160. inline bool is_interlaced(float num_lines)
  4161. {
  4162. // Detect interlacing based on the number of lines in the source.
  4163. if(interlace_detect)
  4164. {
  4165. // NTSC: 525 lines, 262.5/field; 486 active (2 half-lines), 243/field
  4166. // NTSC Emulators: Typically 224 or 240 lines
  4167. // PAL: 625 lines, 312.5/field; 576 active (typical), 288/field
  4168. // PAL Emulators: ?
  4169. // ATSC: 720p, 1080i, 1080p
  4170. // Where do we place our cutoffs? Assumptions:
  4171. // 1.) We only need to care about active lines.
  4172. // 2.) Anything > 288 and <= 576 lines is probably interlaced.
  4173. // 3.) Anything > 576 lines is probably not interlaced...
  4174. // 4.) ...except 1080 lines, which is a crapshoot (user decision).
  4175. // 5.) Just in case the main program uses calculated video sizes,
  4176. // we should nudge the float thresholds a bit.
  4177. const bool sd_interlace = ((num_lines > 288.5) && (num_lines < 576.5));
  4178. const bool hd_interlace = bool(interlace_1080i) ?
  4179. ((num_lines > 1079.5) && (num_lines < 1080.5)) :
  4180. false;
  4181. return (sd_interlace || hd_interlace);
  4182. }
  4183. else
  4184. {
  4185. return false;
  4186. }
  4187. }
  4188. #endif // SCANLINE_FUNCTIONS_H
  4189. ///////////////////////////// END SCANLINE-FUNCTIONS ////////////////////////////
  4190. void main() {
  4191. gl_Position = position;
  4192. vTexCoord = texCoord;
  4193. uv_step = float2(1.0)/texture_size;
  4194. // Detect interlacing: 1.0 = true, 0.0 = false.
  4195. const float2 _video_size = video_size;
  4196. interlaced = float(is_interlaced(_video_size.y));
  4197. }