first-pass-linearize-crt-gamma-bob-fields.fs 241 KB

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