scanlines-vertical-interlacing.fs 310 KB

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