SubpixelMorphologicalAntialiasing.hlsl 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436
  1. // Ported to Unity & tweaked by Thomas Hourdel (thomas@hourdel.com)
  2. #include "../Colors.hlsl"
  3. /**
  4. * Copyright (C) 2013 Jorge Jimenez (jorge@iryoku.com)
  5. * Copyright (C) 2013 Jose I. Echevarria (joseignacioechevarria@gmail.com)
  6. * Copyright (C) 2013 Belen Masia (bmasia@unizar.es)
  7. * Copyright (C) 2013 Fernando Navarro (fernandn@microsoft.com)
  8. * Copyright (C) 2013 Diego Gutierrez (diegog@unizar.es)
  9. *
  10. * Permission is hereby granted, free of charge, to any person obtaining a copy
  11. * this software and associated documentation files (the "Software"), to deal in
  12. * the Software without restriction, including without limitation the rights to
  13. * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  14. * of the Software, and to permit persons to whom the Software is furnished to
  15. * do so, subject to the following conditions:
  16. *
  17. * The above copyright notice and this permission notice shall be included in
  18. * all copies or substantial portions of the Software. As clarification, there
  19. * is no requirement that the copyright notice and permission be included in
  20. * binary distributions of the Software.
  21. *
  22. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  23. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  24. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  25. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  26. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  27. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  28. * SOFTWARE.
  29. */
  30. /**
  31. * _______ ___ ___ ___ ___
  32. * / || \/ | / \ / \
  33. * | (---- | \ / | / ^ \ / ^ \
  34. * \ \ | |\/| | / /_\ \ / /_\ \
  35. * ----) | | | | | / _____ \ / _____ \
  36. * |_______/ |__| |__| /__/ \__\ /__/ \__\
  37. *
  38. * E N H A N C E D
  39. * S U B P I X E L M O R P H O L O G I C A L A N T I A L I A S I N G
  40. *
  41. * http://www.iryoku.com/smaa/
  42. *
  43. * Hi, welcome aboard!
  44. *
  45. * Here you'll find instructions to get the shader up and running as fast as
  46. * possible.
  47. *
  48. * IMPORTANTE NOTICE: when updating, remember to update both this file and the
  49. * precomputed textures! They may change from version to version.
  50. *
  51. * The shader has three passes, chained together as follows:
  52. *
  53. * |input|------------------�
  54. * v |
  55. * [ SMAA*EdgeDetection ] |
  56. * v |
  57. * |edgesTex| |
  58. * v |
  59. * [ SMAABlendingWeightCalculation ] |
  60. * v |
  61. * |blendTex| |
  62. * v |
  63. * [ SMAANeighborhoodBlending ] <------�
  64. * v
  65. * |output|
  66. *
  67. * Note that each [pass] has its own vertex and pixel shader. Remember to use
  68. * oversized triangles instead of quads to avoid overshading along the
  69. * diagonal.
  70. *
  71. * You've three edge detection methods to choose from: luma, color or depth.
  72. * They represent different quality/performance and anti-aliasing/sharpness
  73. * tradeoffs, so our recommendation is for you to choose the one that best
  74. * suits your particular scenario:
  75. *
  76. * - Depth edge detection is usually the fastest but it may miss some edges.
  77. *
  78. * - Luma edge detection is usually more expensive than depth edge detection,
  79. * but catches visible edges that depth edge detection can miss.
  80. *
  81. * - Color edge detection is usually the most expensive one but catches
  82. * chroma-only edges.
  83. *
  84. * For quickstarters: just use luma edge detection.
  85. *
  86. * The general advice is to not rush the integration process and ensure each
  87. * step is done correctly (don't try to integrate SMAA T2x with predicated edge
  88. * detection from the start!). Ok then, let's go!
  89. *
  90. * 1. The first step is to create two RGBA temporal render targets for holding
  91. * |edgesTex| and |blendTex|.
  92. *
  93. * In DX10 or DX11, you can use a RG render target for the edges texture.
  94. * In the case of NVIDIA GPUs, using RG render targets seems to actually be
  95. * slower.
  96. *
  97. * On the Xbox 360, you can use the same render target for resolving both
  98. * |edgesTex| and |blendTex|, as they aren't needed simultaneously.
  99. *
  100. * 2. Both temporal render targets |edgesTex| and |blendTex| must be cleared
  101. * each frame. Do not forget to clear the alpha channel!
  102. *
  103. * 3. The next step is loading the two supporting precalculated textures,
  104. * 'areaTex' and 'searchTex'. You'll find them in the 'Textures' folder as
  105. * C++ headers, and also as regular DDS files. They'll be needed for the
  106. * 'SMAABlendingWeightCalculation' pass.
  107. *
  108. * If you use the C++ headers, be sure to load them in the format specified
  109. * inside of them.
  110. *
  111. * You can also compress 'areaTex' and 'searchTex' using BC5 and BC4
  112. * respectively, if you have that option in your content processor pipeline.
  113. * When compressing then, you get a non-perceptible quality decrease, and a
  114. * marginal performance increase.
  115. *
  116. * 4. All samplers must be set to linear filtering and clamp.
  117. *
  118. * After you get the technique working, remember that 64-bit inputs have
  119. * half-rate linear filtering on GCN.
  120. *
  121. * If SMAA is applied to 64-bit color buffers, switching to point filtering
  122. * when accesing them will increase the performance. Search for
  123. * 'SMAASamplePoint' to see which textures may benefit from point
  124. * filtering, and where (which is basically the color input in the edge
  125. * detection and resolve passes).
  126. *
  127. * 5. All texture reads and buffer writes must be non-sRGB, with the exception
  128. * of the input read and the output write in
  129. * 'SMAANeighborhoodBlending' (and only in this pass!). If sRGB reads in
  130. * this last pass are not possible, the technique will work anyway, but
  131. * will perform antialiasing in gamma space.
  132. *
  133. * IMPORTANT: for best results the input read for the color/luma edge
  134. * detection should *NOT* be sRGB.
  135. *
  136. * 6. Before including SMAA.h you'll have to setup the render target metrics,
  137. * the target and any optional configuration defines. Optionally you can
  138. * use a preset.
  139. *
  140. * You have the following targets available:
  141. * SMAA_HLSL_3
  142. * SMAA_HLSL_4
  143. * SMAA_HLSL_4_1
  144. * SMAA_GLSL_3 *
  145. * SMAA_GLSL_4 *
  146. *
  147. * * (See SMAA_INCLUDE_VS and SMAA_INCLUDE_PS below).
  148. *
  149. * And four presets:
  150. * SMAA_PRESET_LOW (%60 of the quality)
  151. * SMAA_PRESET_MEDIUM (%80 of the quality)
  152. * SMAA_PRESET_HIGH (%95 of the quality)
  153. * SMAA_PRESET_ULTRA (%99 of the quality)
  154. *
  155. * For example:
  156. * #define SMAA_RT_METRICS float4(1.0 / 1280.0, 1.0 / 720.0, 1280.0, 720.0)
  157. * #define SMAA_HLSL_4
  158. * #define SMAA_PRESET_HIGH
  159. * #include "SMAA.h"
  160. *
  161. * Note that SMAA_RT_METRICS doesn't need to be a macro, it can be a
  162. * uniform variable. The code is designed to minimize the impact of not
  163. * using a constant value, but it is still better to hardcode it.
  164. *
  165. * Depending on how you encoded 'areaTex' and 'searchTex', you may have to
  166. * add (and customize) the following defines before including SMAA.h:
  167. * #define SMAA_AREATEX_SELECT(sample) sample.rg
  168. * #define SMAA_SEARCHTEX_SELECT(sample) sample.r
  169. *
  170. * If your engine is already using porting macros, you can define
  171. * SMAA_CUSTOM_SL, and define the porting functions by yourself.
  172. *
  173. * 7. Then, you'll have to setup the passes as indicated in the scheme above.
  174. * You can take a look into SMAA.fx, to see how we did it for our demo.
  175. * Checkout the function wrappers, you may want to copy-paste them!
  176. *
  177. * 8. It's recommended to validate the produced |edgesTex| and |blendTex|.
  178. * You can use a screenshot from your engine to compare the |edgesTex|
  179. * and |blendTex| produced inside of the engine with the results obtained
  180. * with the reference demo.
  181. *
  182. * 9. After you get the last pass to work, it's time to optimize. You'll have
  183. * to initialize a stencil buffer in the first pass (discard is already in
  184. * the code), then mask execution by using it the second pass. The last
  185. * pass should be executed in all pixels.
  186. *
  187. *
  188. * After this point you can choose to enable predicated thresholding,
  189. * temporal supersampling and motion blur integration:
  190. *
  191. * a) If you want to use predicated thresholding, take a look into
  192. * SMAA_PREDICATION; you'll need to pass an extra texture in the edge
  193. * detection pass.
  194. *
  195. * b) If you want to enable temporal supersampling (SMAA T2x):
  196. *
  197. * 1. The first step is to render using subpixel jitters. I won't go into
  198. * detail, but it's as simple as moving each vertex position in the
  199. * vertex shader, you can check how we do it in our DX10 demo.
  200. *
  201. * 2. Then, you must setup the temporal resolve. You may want to take a look
  202. * into SMAAResolve for resolving 2x modes. After you get it working, you'll
  203. * probably see ghosting everywhere. But fear not, you can enable the
  204. * CryENGINE temporal reprojection by setting the SMAA_REPROJECTION macro.
  205. * Check out SMAA_DECODE_VELOCITY if your velocity buffer is encoded.
  206. *
  207. * 3. The next step is to apply SMAA to each subpixel jittered frame, just as
  208. * done for 1x.
  209. *
  210. * 4. At this point you should already have something usable, but for best
  211. * results the proper area textures must be set depending on current jitter.
  212. * For this, the parameter 'subsampleIndices' of
  213. * 'SMAABlendingWeightCalculationPS' must be set as follows, for our T2x
  214. * mode:
  215. *
  216. * @SUBSAMPLE_INDICES
  217. *
  218. * | S# | Camera Jitter | subsampleIndices |
  219. * +----+------------------+---------------------+
  220. * | 0 | ( 0.25, -0.25) | float4(1, 1, 1, 0) |
  221. * | 1 | (-0.25, 0.25) | float4(2, 2, 2, 0) |
  222. *
  223. * These jitter positions assume a bottom-to-top y axis. S# stands for the
  224. * sample number.
  225. *
  226. * More information about temporal supersampling here:
  227. * http://iryoku.com/aacourse/downloads/13-Anti-Aliasing-Methods-in-CryENGINE-3.pdf
  228. *
  229. * c) If you want to enable spatial multisampling (SMAA S2x):
  230. *
  231. * 1. The scene must be rendered using MSAA 2x. The MSAA 2x buffer must be
  232. * created with:
  233. * - DX10: see below (*)
  234. * - DX10.1: D3D10_STANDARD_MULTISAMPLE_PATTERN or
  235. * - DX11: D3D11_STANDARD_MULTISAMPLE_PATTERN
  236. *
  237. * This allows to ensure that the subsample order matches the table in
  238. * @SUBSAMPLE_INDICES.
  239. *
  240. * (*) In the case of DX10, we refer the reader to:
  241. * - SMAA::detectMSAAOrder and
  242. * - SMAA::msaaReorder
  243. *
  244. * These functions allow to match the standard multisample patterns by
  245. * detecting the subsample order for a specific GPU, and reordering
  246. * them appropriately.
  247. *
  248. * 2. A shader must be run to output each subsample into a separate buffer
  249. * (DX10 is required). You can use SMAASeparate for this purpose, or just do
  250. * it in an existing pass (for example, in the tone mapping pass, which has
  251. * the advantage of feeding tone mapped subsamples to SMAA, which will yield
  252. * better results).
  253. *
  254. * 3. The full SMAA 1x pipeline must be run for each separated buffer, storing
  255. * the results in the final buffer. The second run should alpha blend with
  256. * the existing final buffer using a blending factor of 0.5.
  257. * 'subsampleIndices' must be adjusted as in the SMAA T2x case (see point
  258. * b).
  259. *
  260. * d) If you want to enable temporal supersampling on top of SMAA S2x
  261. * (which actually is SMAA 4x):
  262. *
  263. * 1. SMAA 4x consists on temporally jittering SMAA S2x, so the first step is
  264. * to calculate SMAA S2x for current frame. In this case, 'subsampleIndices'
  265. * must be set as follows:
  266. *
  267. * | F# | S# | Camera Jitter | Net Jitter | subsampleIndices |
  268. * +----+----+--------------------+-------------------+----------------------+
  269. * | 0 | 0 | ( 0.125, 0.125) | ( 0.375, -0.125) | float4(5, 3, 1, 3) |
  270. * | 0 | 1 | ( 0.125, 0.125) | (-0.125, 0.375) | float4(4, 6, 2, 3) |
  271. * +----+----+--------------------+-------------------+----------------------+
  272. * | 1 | 2 | (-0.125, -0.125) | ( 0.125, -0.375) | float4(3, 5, 1, 4) |
  273. * | 1 | 3 | (-0.125, -0.125) | (-0.375, 0.125) | float4(6, 4, 2, 4) |
  274. *
  275. * These jitter positions assume a bottom-to-top y axis. F# stands for the
  276. * frame number. S# stands for the sample number.
  277. *
  278. * 2. After calculating SMAA S2x for current frame (with the new subsample
  279. * indices), previous frame must be reprojected as in SMAA T2x mode (see
  280. * point b).
  281. *
  282. * e) If motion blur is used, you may want to do the edge detection pass
  283. * together with motion blur. This has two advantages:
  284. *
  285. * 1. Pixels under heavy motion can be omitted from the edge detection process.
  286. * For these pixels we can just store "no edge", as motion blur will take
  287. * care of them.
  288. * 2. The center pixel tap is reused.
  289. *
  290. * Note that in this case depth testing should be used instead of stenciling,
  291. * as we have to write all the pixels in the motion blur pass.
  292. *
  293. * That's it!
  294. */
  295. //-----------------------------------------------------------------------------
  296. // SMAA Presets
  297. /**
  298. * Note that if you use one of these presets, the following configuration
  299. * macros will be ignored if set in the "Configurable Defines" section.
  300. */
  301. #if defined(SMAA_PRESET_LOW)
  302. #define SMAA_THRESHOLD 0.15
  303. #define SMAA_MAX_SEARCH_STEPS 4
  304. #define SMAA_DISABLE_DIAG_DETECTION
  305. #define SMAA_DISABLE_CORNER_DETECTION
  306. #elif defined(SMAA_PRESET_MEDIUM)
  307. #define SMAA_THRESHOLD 0.1
  308. #define SMAA_MAX_SEARCH_STEPS 8
  309. #define SMAA_DISABLE_DIAG_DETECTION
  310. #define SMAA_DISABLE_CORNER_DETECTION
  311. #elif defined(SMAA_PRESET_HIGH)
  312. #define SMAA_THRESHOLD 0.1
  313. #define SMAA_MAX_SEARCH_STEPS 16
  314. #define SMAA_MAX_SEARCH_STEPS_DIAG 8
  315. #define SMAA_CORNER_ROUNDING 25
  316. #elif defined(SMAA_PRESET_ULTRA)
  317. #define SMAA_THRESHOLD 0.05
  318. #define SMAA_MAX_SEARCH_STEPS 32
  319. #define SMAA_MAX_SEARCH_STEPS_DIAG 16
  320. #define SMAA_CORNER_ROUNDING 25
  321. #endif
  322. //-----------------------------------------------------------------------------
  323. // Configurable Defines
  324. /**
  325. * SMAA_THRESHOLD specifies the threshold or sensitivity to edges.
  326. * Lowering this value you will be able to detect more edges at the expense of
  327. * performance.
  328. *
  329. * Range: [0, 0.5]
  330. * 0.1 is a reasonable value, and allows to catch most visible edges.
  331. * 0.05 is a rather overkill value, that allows to catch 'em all.
  332. *
  333. * If temporal supersampling is used, 0.2 could be a reasonable value, as low
  334. * contrast edges are properly filtered by just 2x.
  335. */
  336. #ifndef SMAA_THRESHOLD
  337. #define SMAA_THRESHOLD 0.1
  338. #endif
  339. /**
  340. * SMAA_DEPTH_THRESHOLD specifies the threshold for depth edge detection.
  341. *
  342. * Range: depends on the depth range of the scene.
  343. */
  344. #ifndef SMAA_DEPTH_THRESHOLD
  345. #define SMAA_DEPTH_THRESHOLD (0.1 * SMAA_THRESHOLD)
  346. #endif
  347. /**
  348. * SMAA_MAX_SEARCH_STEPS specifies the maximum steps performed in the
  349. * horizontal/vertical pattern searches, at each side of the pixel.
  350. *
  351. * In number of pixels, it's actually the double. So the maximum line length
  352. * perfectly handled by, for example 16, is 64 (by perfectly, we meant that
  353. * longer lines won't look as good, but still antialiased).
  354. *
  355. * Range: [0, 112]
  356. */
  357. #ifndef SMAA_MAX_SEARCH_STEPS
  358. #define SMAA_MAX_SEARCH_STEPS 16
  359. #endif
  360. /**
  361. * SMAA_MAX_SEARCH_STEPS_DIAG specifies the maximum steps performed in the
  362. * diagonal pattern searches, at each side of the pixel. In this case we jump
  363. * one pixel at time, instead of two.
  364. *
  365. * Range: [0, 20]
  366. *
  367. * On high-end machines it is cheap (between a 0.8x and 0.9x slower for 16
  368. * steps), but it can have a significant impact on older machines.
  369. *
  370. * Define SMAA_DISABLE_DIAG_DETECTION to disable diagonal processing.
  371. */
  372. #ifndef SMAA_MAX_SEARCH_STEPS_DIAG
  373. #define SMAA_MAX_SEARCH_STEPS_DIAG 8
  374. #endif
  375. /**
  376. * SMAA_CORNER_ROUNDING specifies how much sharp corners will be rounded.
  377. *
  378. * Range: [0, 100]
  379. *
  380. * Define SMAA_DISABLE_CORNER_DETECTION to disable corner processing.
  381. */
  382. #ifndef SMAA_CORNER_ROUNDING
  383. #define SMAA_CORNER_ROUNDING 25
  384. #endif
  385. /**
  386. * If there is an neighbor edge that has SMAA_LOCAL_CONTRAST_FACTOR times
  387. * bigger contrast than current edge, current edge will be discarded.
  388. *
  389. * This allows to eliminate spurious crossing edges, and is based on the fact
  390. * that, if there is too much contrast in a direction, that will hide
  391. * perceptually contrast in the other neighbors.
  392. */
  393. #ifndef SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR
  394. #define SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR 2.0
  395. #endif
  396. /**
  397. * Predicated thresholding allows to better preserve texture details and to
  398. * improve performance, by decreasing the number of detected edges using an
  399. * additional buffer like the light accumulation buffer, object ids or even the
  400. * depth buffer (the depth buffer usage may be limited to indoor or short range
  401. * scenes).
  402. *
  403. * It locally decreases the luma or color threshold if an edge is found in an
  404. * additional buffer (so the global threshold can be higher).
  405. *
  406. * This method was developed by Playstation EDGE MLAA team, and used in
  407. * Killzone 3, by using the light accumulation buffer. More information here:
  408. * http://iryoku.com/aacourse/downloads/06-MLAA-on-PS3.pptx
  409. */
  410. #ifndef SMAA_PREDICATION
  411. #define SMAA_PREDICATION 0
  412. #endif
  413. /**
  414. * Threshold to be used in the additional predication buffer.
  415. *
  416. * Range: depends on the input, so you'll have to find the magic number that
  417. * works for you.
  418. */
  419. #ifndef SMAA_PREDICATION_THRESHOLD
  420. #define SMAA_PREDICATION_THRESHOLD 0.01
  421. #endif
  422. /**
  423. * How much to scale the global threshold used for luma or color edge
  424. * detection when using predication.
  425. *
  426. * Range: [1, 5]
  427. */
  428. #ifndef SMAA_PREDICATION_SCALE
  429. #define SMAA_PREDICATION_SCALE 2.0
  430. #endif
  431. /**
  432. * How much to locally decrease the threshold.
  433. *
  434. * Range: [0, 1]
  435. */
  436. #ifndef SMAA_PREDICATION_STRENGTH
  437. #define SMAA_PREDICATION_STRENGTH 0.4
  438. #endif
  439. /**
  440. * Temporal reprojection allows to remove ghosting artifacts when using
  441. * temporal supersampling. We use the CryEngine 3 method which also introduces
  442. * velocity weighting. This feature is of extreme importance for totally
  443. * removing ghosting. More information here:
  444. * http://iryoku.com/aacourse/downloads/13-Anti-Aliasing-Methods-in-CryENGINE-3.pdf
  445. *
  446. * Note that you'll need to setup a velocity buffer for enabling reprojection.
  447. * For static geometry, saving the previous depth buffer is a viable
  448. * alternative.
  449. */
  450. #ifndef SMAA_REPROJECTION
  451. #define SMAA_REPROJECTION 0
  452. #endif
  453. /**
  454. * Temporal reprojection allows to remove ghosting artifacts when using
  455. * temporal supersampling. However, the default reprojection requires a velocity buffer
  456. * in order to function properly.
  457. *
  458. * A velocity buffer might not always be available (hi Unity 5!). To handle such cases
  459. * we provide a UV-based approximation for calculating motion vectors on the fly.
  460. */
  461. #ifndef SMAA_UV_BASED_REPROJECTION
  462. #define SMAA_UV_BASED_REPROJECTION 0
  463. #endif
  464. /**
  465. * SMAA_REPROJECTION_WEIGHT_SCALE controls the velocity weighting. It allows to
  466. * remove ghosting trails behind the moving object, which are not removed by
  467. * just using reprojection. Using low values will exhibit ghosting, while using
  468. * high values will disable temporal supersampling under motion.
  469. *
  470. * Behind the scenes, velocity weighting removes temporal supersampling when
  471. * the velocity of the subsamples differs (meaning they are different objects).
  472. *
  473. * Range: [0, 80]
  474. */
  475. #ifndef SMAA_REPROJECTION_WEIGHT_SCALE
  476. #define SMAA_REPROJECTION_WEIGHT_SCALE 30.0
  477. #endif
  478. /**
  479. * On some compilers, discard cannot be used in vertex shaders. Thus, they need
  480. * to be compiled separately.
  481. */
  482. #ifndef SMAA_INCLUDE_VS
  483. #define SMAA_INCLUDE_VS 1
  484. #endif
  485. #ifndef SMAA_INCLUDE_PS
  486. #define SMAA_INCLUDE_PS 1
  487. #endif
  488. //-----------------------------------------------------------------------------
  489. // Texture Access Defines
  490. #ifndef SMAA_AREATEX_SELECT
  491. #if defined(SMAA_HLSL_3)
  492. #define SMAA_AREATEX_SELECT(sample) sample.ra
  493. #else
  494. #define SMAA_AREATEX_SELECT(sample) sample.rg
  495. #endif
  496. #endif
  497. #ifndef SMAA_SEARCHTEX_SELECT
  498. #define SMAA_SEARCHTEX_SELECT(sample) sample.r
  499. #endif
  500. #ifndef SMAA_DECODE_VELOCITY
  501. #define SMAA_DECODE_VELOCITY(sample) sample.rg
  502. #endif
  503. //-----------------------------------------------------------------------------
  504. // Non-Configurable Defines
  505. #define SMAA_AREATEX_MAX_DISTANCE 16
  506. #define SMAA_AREATEX_MAX_DISTANCE_DIAG 20
  507. #define SMAA_AREATEX_PIXEL_SIZE (1.0 / float2(160.0, 560.0))
  508. #define SMAA_AREATEX_SUBTEX_SIZE (1.0 / 7.0)
  509. #define SMAA_SEARCHTEX_SIZE float2(66.0, 33.0)
  510. #define SMAA_SEARCHTEX_PACKED_SIZE float2(64.0, 16.0)
  511. #define SMAA_CORNER_ROUNDING_NORM (float(SMAA_CORNER_ROUNDING) / 100.0)
  512. //-----------------------------------------------------------------------------
  513. // Porting Functions
  514. #if defined(SMAA_HLSL_3)
  515. #define SMAATexture2D(tex) sampler2D tex
  516. #define SMAATexturePass2D(tex) tex
  517. #define SMAASampleLevelZero(tex, coord) tex2Dlod(tex, float4(coord, 0.0, 0.0))
  518. #define SMAASampleLevelZeroPoint(tex, coord) tex2Dlod(tex, float4(coord, 0.0, 0.0))
  519. #define SMAASampleLevelZeroOffset(tex, coord, offset) tex2Dlod(tex, float4(coord + offset * SMAA_RT_METRICS.xy, 0.0, 0.0))
  520. #define SMAASample(tex, coord) tex2D(tex, coord)
  521. #define SMAASamplePoint(tex, coord) tex2D(tex, coord)
  522. #define SMAASampleOffset(tex, coord, offset) tex2D(tex, coord + offset * SMAA_RT_METRICS.xy)
  523. //#define SMAA_FLATTEN [flatten]
  524. //#define SMAA_BRANCH [branch]
  525. #define SMAA_FLATTEN
  526. #define SMAA_BRANCH
  527. #endif
  528. #if defined(SMAA_HLSL_4) || defined(SMAA_HLSL_4_1)
  529. //SamplerState LinearSampler { Filter = MIN_MAG_LINEAR_MIP_POINT; AddressU = Clamp; AddressV = Clamp; };
  530. //SamplerState PointSampler { Filter = MIN_MAG_MIP_POINT; AddressU = Clamp; AddressV = Clamp; };
  531. #define SMAATexture2D(tex) Texture2D tex
  532. #define SMAATexturePass2D(tex) tex
  533. #define SMAASampleLevelZero(tex, coord) tex.SampleLevel(LinearSampler, coord, 0)
  534. #define SMAASampleLevelZeroPoint(tex, coord) tex.SampleLevel(PointSampler, coord, 0)
  535. #define SMAASampleLevelZeroOffset(tex, coord, offset) tex.SampleLevel(LinearSampler, coord, 0, offset)
  536. #define SMAASample(tex, coord) tex.Sample(LinearSampler, coord)
  537. #define SMAASamplePoint(tex, coord) tex.Sample(PointSampler, coord)
  538. #define SMAASampleOffset(tex, coord, offset) tex.Sample(LinearSampler, coord, offset)
  539. #define SMAA_FLATTEN [flatten]
  540. #define SMAA_BRANCH [branch]
  541. #define SMAATexture2DMS2(tex) Texture2DMS<float4, 2> tex
  542. #define SMAALoad(tex, pos, sample) tex.Load(pos, sample)
  543. #if defined(SMAA_HLSL_4_1)
  544. #define SMAAGather(tex, coord) tex.Gather(LinearSampler, coord, 0)
  545. #endif
  546. #endif
  547. #if defined(SMAA_GLSL_3) || defined(SMAA_GLSL_4)
  548. #define SMAATexture2D(tex) sampler2D tex
  549. #define SMAATexturePass2D(tex) tex
  550. #define SMAASampleLevelZero(tex, coord) textureLod(tex, coord, 0.0)
  551. #define SMAASampleLevelZeroPoint(tex, coord) textureLod(tex, coord, 0.0)
  552. #define SMAASampleLevelZeroOffset(tex, coord, offset) textureLodOffset(tex, coord, 0.0, offset)
  553. #define SMAASample(tex, coord) texture(tex, coord)
  554. #define SMAASamplePoint(tex, coord) texture(tex, coord)
  555. #define SMAASampleOffset(tex, coord, offset) texture(tex, coord, offset)
  556. #define SMAA_FLATTEN
  557. #define SMAA_BRANCH
  558. #define lerp(a, b, t) mix(a, b, t)
  559. #define saturate(a) clamp(a, 0.0, 1.0)
  560. #if defined(SMAA_GLSL_4)
  561. #define mad(a, b, c) fma(a, b, c)
  562. #define SMAAGather(tex, coord) textureGather(tex, coord)
  563. #else
  564. #define mad(a, b, c) (a * b + c)
  565. #endif
  566. #define float2 vec2
  567. #define float3 vec3
  568. #define float4 vec4
  569. #define int2 ivec2
  570. #define int3 ivec3
  571. #define int4 ivec4
  572. #define bool2 bvec2
  573. #define bool3 bvec3
  574. #define bool4 bvec4
  575. #endif
  576. #if !defined(SMAA_HLSL_3) && !defined(SMAA_HLSL_4) && !defined(SMAA_HLSL_4_1) && !defined(SMAA_GLSL_3) && !defined(SMAA_GLSL_4) && !defined(SMAA_CUSTOM_SL)
  577. #error you must define the shading language: SMAA_HLSL_*, SMAA_GLSL_* or SMAA_CUSTOM_SL
  578. #endif
  579. //-----------------------------------------------------------------------------
  580. // Misc functions
  581. /**
  582. * Gathers current pixel, and the top-left neighbors.
  583. */
  584. float3 SMAAGatherNeighbours(float2 texcoord,
  585. float4 offset[3],
  586. SMAATexture2D(tex)) {
  587. #ifdef SMAAGather
  588. return SMAAGather(tex, texcoord + SMAA_RT_METRICS.xy * float2(-0.5, -0.5)).grb;
  589. #else
  590. float P = SMAASamplePoint(tex, texcoord).r;
  591. float Pleft = SMAASamplePoint(tex, offset[0].xy).r;
  592. float Ptop = SMAASamplePoint(tex, offset[0].zw).r;
  593. return float3(P, Pleft, Ptop);
  594. #endif
  595. }
  596. /**
  597. * Adjusts the threshold by means of predication.
  598. */
  599. float2 SMAACalculatePredicatedThreshold(float2 texcoord,
  600. float4 offset[3],
  601. SMAATexture2D(predicationTex)) {
  602. float3 neighbours = SMAAGatherNeighbours(texcoord, offset, SMAATexturePass2D(predicationTex));
  603. float2 delta = abs(neighbours.xx - neighbours.yz);
  604. float2 edges = step(SMAA_PREDICATION_THRESHOLD, delta);
  605. return SMAA_PREDICATION_SCALE * SMAA_THRESHOLD * (1.0 - SMAA_PREDICATION_STRENGTH * edges);
  606. }
  607. /**
  608. * Conditional move:
  609. */
  610. void SMAAMovc(bool2 cond, inout float2 variable, float2 value) {
  611. SMAA_FLATTEN if (cond.x) variable.x = value.x;
  612. SMAA_FLATTEN if (cond.y) variable.y = value.y;
  613. }
  614. void SMAAMovc(bool4 cond, inout float4 variable, float4 value) {
  615. SMAAMovc(cond.xy, variable.xy, value.xy);
  616. SMAAMovc(cond.zw, variable.zw, value.zw);
  617. }
  618. #if SMAA_INCLUDE_VS
  619. //-----------------------------------------------------------------------------
  620. // Vertex Shaders
  621. /**
  622. * Edge Detection Vertex Shader
  623. */
  624. void SMAAEdgeDetectionVS(float2 texcoord,
  625. out float4 offset[3]) {
  626. offset[0] = mad(SMAA_RT_METRICS.xyxy, float4(-1.0, 0.0, 0.0, -1.0), texcoord.xyxy);
  627. offset[1] = mad(SMAA_RT_METRICS.xyxy, float4( 1.0, 0.0, 0.0, 1.0), texcoord.xyxy);
  628. offset[2] = mad(SMAA_RT_METRICS.xyxy, float4(-2.0, 0.0, 0.0, -2.0), texcoord.xyxy);
  629. }
  630. /**
  631. * Blend Weight Calculation Vertex Shader
  632. */
  633. void SMAABlendingWeightCalculationVS(float2 texcoord,
  634. out float2 pixcoord,
  635. out float4 offset[3]) {
  636. pixcoord = texcoord * SMAA_RT_METRICS.zw;
  637. // We will use these offsets for the searches later on (see @PSEUDO_GATHER4):
  638. offset[0] = mad(SMAA_RT_METRICS.xyxy, float4(-0.25, -0.125, 1.25, -0.125), texcoord.xyxy);
  639. offset[1] = mad(SMAA_RT_METRICS.xyxy, float4(-0.125, -0.25, -0.125, 1.25), texcoord.xyxy);
  640. // And these for the searches, they indicate the ends of the loops:
  641. offset[2] = mad(SMAA_RT_METRICS.xxyy,
  642. float4(-2.0, 2.0, -2.0, 2.0) * float(SMAA_MAX_SEARCH_STEPS),
  643. float4(offset[0].xz, offset[1].yw));
  644. }
  645. /**
  646. * Neighborhood Blending Vertex Shader
  647. */
  648. void SMAANeighborhoodBlendingVS(float2 texcoord,
  649. out float4 offset) {
  650. offset = mad(SMAA_RT_METRICS.xyxy, float4( 1.0, 0.0, 0.0, 1.0), texcoord.xyxy);
  651. }
  652. #endif // SMAA_INCLUDE_VS
  653. #if SMAA_INCLUDE_PS
  654. //-----------------------------------------------------------------------------
  655. // Edge Detection Pixel Shaders (First Pass)
  656. /**
  657. * Luma Edge Detection
  658. *
  659. * IMPORTANT NOTICE: luma edge detection requires gamma-corrected colors, and
  660. * thus 'colorTex' should be a non-sRGB texture.
  661. */
  662. float2 SMAALumaEdgeDetectionPS(float2 texcoord,
  663. float4 offset[3],
  664. SMAATexture2D(colorTex)
  665. #if SMAA_PREDICATION
  666. , SMAATexture2D(predicationTex)
  667. #endif
  668. ) {
  669. // Calculate the threshold:
  670. #if SMAA_PREDICATION
  671. float2 threshold = SMAACalculatePredicatedThreshold(texcoord, offset, SMAATexturePass2D(predicationTex));
  672. #else
  673. float2 threshold = float2(SMAA_THRESHOLD, SMAA_THRESHOLD);
  674. #endif
  675. // Calculate lumas:
  676. float3 weights = float3(0.2126, 0.7152, 0.0722);
  677. float L = dot(SMAASamplePoint(colorTex, texcoord).rgb, weights);
  678. float Lleft = dot(SMAASamplePoint(colorTex, offset[0].xy).rgb, weights);
  679. float Ltop = dot(SMAASamplePoint(colorTex, offset[0].zw).rgb, weights);
  680. // We do the usual threshold:
  681. float4 delta;
  682. delta.xy = abs(L - float2(Lleft, Ltop));
  683. float2 edges = step(threshold, delta.xy);
  684. // Then discard if there is no edge:
  685. if (dot(edges, float2(1.0, 1.0)) == 0.0)
  686. discard;
  687. // Calculate right and bottom deltas:
  688. float Lright = dot(SMAASamplePoint(colorTex, offset[1].xy).rgb, weights);
  689. float Lbottom = dot(SMAASamplePoint(colorTex, offset[1].zw).rgb, weights);
  690. delta.zw = abs(L - float2(Lright, Lbottom));
  691. // Calculate the maximum delta in the direct neighborhood:
  692. float2 maxDelta = max(delta.xy, delta.zw);
  693. // Calculate left-left and top-top deltas:
  694. float Lleftleft = dot(SMAASamplePoint(colorTex, offset[2].xy).rgb, weights);
  695. float Ltoptop = dot(SMAASamplePoint(colorTex, offset[2].zw).rgb, weights);
  696. delta.zw = abs(float2(Lleft, Ltop) - float2(Lleftleft, Ltoptop));
  697. // Calculate the final maximum delta:
  698. maxDelta = max(maxDelta.xy, delta.zw);
  699. float finalDelta = max(maxDelta.x, maxDelta.y);
  700. // Local contrast adaptation:
  701. #if !defined(SHADER_API_OPENGL)
  702. edges.xy *= step(finalDelta, SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR * delta.xy);
  703. #endif
  704. return edges;
  705. }
  706. /**
  707. * Color Edge Detection
  708. *
  709. * IMPORTANT NOTICE: color edge detection requires gamma-corrected colors, and
  710. * thus 'colorTex' should be a non-sRGB texture.
  711. */
  712. float2 SMAAColorEdgeDetectionPS(float2 texcoord,
  713. float4 offset[3],
  714. SMAATexture2D(colorTex)
  715. #if SMAA_PREDICATION
  716. , SMAATexture2D(predicationTex)
  717. #endif
  718. ) {
  719. // Calculate the threshold:
  720. #if SMAA_PREDICATION
  721. float2 threshold = SMAACalculatePredicatedThreshold(texcoord, offset, predicationTex);
  722. #else
  723. float2 threshold = float2(SMAA_THRESHOLD, SMAA_THRESHOLD);
  724. #endif
  725. // Calculate color deltas:
  726. float4 delta;
  727. float3 C = SMAASamplePoint(colorTex, texcoord).rgb;
  728. float3 Cleft = SMAASamplePoint(colorTex, offset[0].xy).rgb;
  729. float3 t = abs(C - Cleft);
  730. delta.x = max(max(t.r, t.g), t.b);
  731. float3 Ctop = SMAASamplePoint(colorTex, offset[0].zw).rgb;
  732. t = abs(C - Ctop);
  733. delta.y = max(max(t.r, t.g), t.b);
  734. // We do the usual threshold:
  735. float2 edges = step(threshold, delta.xy);
  736. // Then discard if there is no edge:
  737. if (dot(edges, float2(1.0, 1.0)) == 0.0)
  738. discard;
  739. // Calculate right and bottom deltas:
  740. float3 Cright = SMAASamplePoint(colorTex, offset[1].xy).rgb;
  741. t = abs(C - Cright);
  742. delta.z = max(max(t.r, t.g), t.b);
  743. float3 Cbottom = SMAASamplePoint(colorTex, offset[1].zw).rgb;
  744. t = abs(C - Cbottom);
  745. delta.w = max(max(t.r, t.g), t.b);
  746. // Calculate the maximum delta in the direct neighborhood:
  747. float2 maxDelta = max(delta.xy, delta.zw);
  748. // Calculate left-left and top-top deltas:
  749. float3 Cleftleft = SMAASamplePoint(colorTex, offset[2].xy).rgb;
  750. t = abs(Cleft - Cleftleft);
  751. delta.z = max(max(t.r, t.g), t.b);
  752. float3 Ctoptop = SMAASamplePoint(colorTex, offset[2].zw).rgb;
  753. t = abs(Ctop - Ctoptop);
  754. delta.w = max(max(t.r, t.g), t.b);
  755. // Calculate the final maximum delta:
  756. maxDelta = max(maxDelta.xy, delta.zw);
  757. float finalDelta = max(maxDelta.x, maxDelta.y);
  758. // Local contrast adaptation:
  759. #if !defined(SHADER_API_OPENGL)
  760. edges.xy *= step(finalDelta, SMAA_LOCAL_CONTRAST_ADAPTATION_FACTOR * delta.xy);
  761. #endif
  762. return edges;
  763. }
  764. /**
  765. * Depth Edge Detection
  766. */
  767. float2 SMAADepthEdgeDetectionPS(float2 texcoord,
  768. float4 offset[3],
  769. SMAATexture2D(depthTex)) {
  770. float3 neighbours = SMAAGatherNeighbours(texcoord, offset, SMAATexturePass2D(depthTex));
  771. float2 delta = abs(neighbours.xx - float2(neighbours.y, neighbours.z));
  772. float2 edges = step(SMAA_DEPTH_THRESHOLD, delta);
  773. if (dot(edges, float2(1.0, 1.0)) == 0.0)
  774. discard;
  775. return edges;
  776. }
  777. //-----------------------------------------------------------------------------
  778. // Diagonal Search Functions
  779. #if !defined(SMAA_DISABLE_DIAG_DETECTION)
  780. /**
  781. * Allows to decode two binary values from a bilinear-filtered access.
  782. */
  783. float2 SMAADecodeDiagBilinearAccess(float2 e) {
  784. // Bilinear access for fetching 'e' have a 0.25 offset, and we are
  785. // interested in the R and G edges:
  786. //
  787. // +---G---+-------+
  788. // | x o R x |
  789. // +-------+-------+
  790. //
  791. // Then, if one of these edge is enabled:
  792. // Red: (0.75 * X + 0.25 * 1) => 0.25 or 1.0
  793. // Green: (0.75 * 1 + 0.25 * X) => 0.75 or 1.0
  794. //
  795. // This function will unpack the values (mad + mul + round):
  796. // wolframalpha.com: round(x * abs(5 * x - 5 * 0.75)) plot 0 to 1
  797. e.r = e.r * abs(5.0 * e.r - 5.0 * 0.75);
  798. return round(e);
  799. }
  800. float4 SMAADecodeDiagBilinearAccess(float4 e) {
  801. e.rb = e.rb * abs(5.0 * e.rb - 5.0 * 0.75);
  802. return round(e);
  803. }
  804. /**
  805. * These functions allows to perform diagonal pattern searches.
  806. */
  807. float2 SMAASearchDiag1(SMAATexture2D(edgesTex), float2 texcoord, float2 dir, out float2 e) {
  808. float4 coord = float4(texcoord, -1.0, 1.0);
  809. float3 t = float3(SMAA_RT_METRICS.xy, 1.0);
  810. while (coord.z < float(SMAA_MAX_SEARCH_STEPS_DIAG - 1) &&
  811. coord.w > 0.9) {
  812. coord.xyz = mad(t, float3(dir, 1.0), coord.xyz);
  813. e = SMAASampleLevelZero(edgesTex, coord.xy).rg;
  814. coord.w = dot(e, float2(0.5, 0.5));
  815. }
  816. return coord.zw;
  817. }
  818. float2 SMAASearchDiag2(SMAATexture2D(edgesTex), float2 texcoord, float2 dir, out float2 e) {
  819. float4 coord = float4(texcoord, -1.0, 1.0);
  820. coord.x += 0.25 * SMAA_RT_METRICS.x; // See @SearchDiag2Optimization
  821. float3 t = float3(SMAA_RT_METRICS.xy, 1.0);
  822. while (coord.z < float(SMAA_MAX_SEARCH_STEPS_DIAG - 1) &&
  823. coord.w > 0.9) {
  824. coord.xyz = mad(t, float3(dir, 1.0), coord.xyz);
  825. // @SearchDiag2Optimization
  826. // Fetch both edges at once using bilinear filtering:
  827. e = SMAASampleLevelZero(edgesTex, coord.xy).rg;
  828. e = SMAADecodeDiagBilinearAccess(e);
  829. // Non-optimized version:
  830. // e.g = SMAASampleLevelZero(edgesTex, coord.xy).g;
  831. // e.r = SMAASampleLevelZeroOffset(edgesTex, coord.xy, int2(1, 0)).r;
  832. coord.w = dot(e, float2(0.5, 0.5));
  833. }
  834. return coord.zw;
  835. }
  836. /**
  837. * Similar to SMAAArea, this calculates the area corresponding to a certain
  838. * diagonal distance and crossing edges 'e'.
  839. */
  840. float2 SMAAAreaDiag(SMAATexture2D(areaTex), float2 dist, float2 e, float offset) {
  841. float2 texcoord = mad(float2(SMAA_AREATEX_MAX_DISTANCE_DIAG, SMAA_AREATEX_MAX_DISTANCE_DIAG), e, dist);
  842. // We do a scale and bias for mapping to texel space:
  843. texcoord = mad(SMAA_AREATEX_PIXEL_SIZE, texcoord, 0.5 * SMAA_AREATEX_PIXEL_SIZE);
  844. // Diagonal areas are on the second half of the texture:
  845. texcoord.x += 0.5;
  846. // Move to proper place, according to the subpixel offset:
  847. texcoord.y += SMAA_AREATEX_SUBTEX_SIZE * offset;
  848. // Do it!
  849. return SMAA_AREATEX_SELECT(SMAASampleLevelZero(areaTex, texcoord));
  850. }
  851. /**
  852. * This searches for diagonal patterns and returns the corresponding weights.
  853. */
  854. float2 SMAACalculateDiagWeights(SMAATexture2D(edgesTex), SMAATexture2D(areaTex), float2 texcoord, float2 e, float4 subsampleIndices) {
  855. float2 weights = float2(0.0, 0.0);
  856. // Search for the line ends:
  857. float4 d;
  858. float2 end;
  859. if (e.r > 0.0) {
  860. d.xz = SMAASearchDiag1(SMAATexturePass2D(edgesTex), texcoord, float2(-1.0, 1.0), end);
  861. d.x += float(end.y > 0.9);
  862. } else
  863. d.xz = float2(0.0, 0.0);
  864. d.yw = SMAASearchDiag1(SMAATexturePass2D(edgesTex), texcoord, float2(1.0, -1.0), end);
  865. SMAA_BRANCH
  866. if (d.x + d.y > 2.0) { // d.x + d.y + 1 > 3
  867. // Fetch the crossing edges:
  868. float4 coords = mad(float4(-d.x + 0.25, d.x, d.y, -d.y - 0.25), SMAA_RT_METRICS.xyxy, texcoord.xyxy);
  869. float4 c;
  870. c.xy = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2(-1, 0)).rg;
  871. c.zw = SMAASampleLevelZeroOffset(edgesTex, coords.zw, int2( 1, 0)).rg;
  872. c.yxwz = SMAADecodeDiagBilinearAccess(c.xyzw);
  873. // Non-optimized version:
  874. // float4 coords = mad(float4(-d.x, d.x, d.y, -d.y), SMAA_RT_METRICS.xyxy, texcoord.xyxy);
  875. // float4 c;
  876. // c.x = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2(-1, 0)).g;
  877. // c.y = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2( 0, 0)).r;
  878. // c.z = SMAASampleLevelZeroOffset(edgesTex, coords.zw, int2( 1, 0)).g;
  879. // c.w = SMAASampleLevelZeroOffset(edgesTex, coords.zw, int2( 1, -1)).r;
  880. // Merge crossing edges at each side into a single value:
  881. float2 cc = mad(float2(2.0, 2.0), c.xz, c.yw);
  882. // Remove the crossing edge if we didn't found the end of the line:
  883. SMAAMovc(bool2(step(float2(0.9, 0.9), d.zw)), cc, float2(0.0, 0.0));
  884. // Fetch the areas for this line:
  885. weights += SMAAAreaDiag(SMAATexturePass2D(areaTex), d.xy, cc, subsampleIndices.z);
  886. }
  887. // Search for the line ends:
  888. d.xz = SMAASearchDiag2(SMAATexturePass2D(edgesTex), texcoord, float2(-1.0, -1.0), end);
  889. if (SMAASampleLevelZeroOffset(edgesTex, texcoord, int2(1, 0)).r > 0.0) {
  890. d.yw = SMAASearchDiag2(SMAATexturePass2D(edgesTex), texcoord, float2(1.0, 1.0), end);
  891. d.y += float(end.y > 0.9);
  892. } else
  893. d.yw = float2(0.0, 0.0);
  894. SMAA_BRANCH
  895. if (d.x + d.y > 2.0) { // d.x + d.y + 1 > 3
  896. // Fetch the crossing edges:
  897. float4 coords = mad(float4(-d.x, -d.x, d.y, d.y), SMAA_RT_METRICS.xyxy, texcoord.xyxy);
  898. float4 c;
  899. c.x = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2(-1, 0)).g;
  900. c.y = SMAASampleLevelZeroOffset(edgesTex, coords.xy, int2( 0, -1)).r;
  901. c.zw = SMAASampleLevelZeroOffset(edgesTex, coords.zw, int2( 1, 0)).gr;
  902. float2 cc = mad(float2(2.0, 2.0), c.xz, c.yw);
  903. // Remove the crossing edge if we didn't found the end of the line:
  904. SMAAMovc(bool2(step(float2(0.9, 0.9), d.zw)), cc, float2(0.0, 0.0));
  905. // Fetch the areas for this line:
  906. weights += SMAAAreaDiag(SMAATexturePass2D(areaTex), d.xy, cc, subsampleIndices.w).gr;
  907. }
  908. return weights;
  909. }
  910. #endif
  911. //-----------------------------------------------------------------------------
  912. // Horizontal/Vertical Search Functions
  913. /**
  914. * This allows to determine how much length should we add in the last step
  915. * of the searches. It takes the bilinearly interpolated edge (see
  916. * @PSEUDO_GATHER4), and adds 0, 1 or 2, depending on which edges and
  917. * crossing edges are active.
  918. */
  919. float SMAASearchLength(SMAATexture2D(searchTex), float2 e, float offset) {
  920. // The texture is flipped vertically, with left and right cases taking half
  921. // of the space horizontally:
  922. float2 scale = SMAA_SEARCHTEX_SIZE * float2(0.5, -1.0);
  923. float2 bias = SMAA_SEARCHTEX_SIZE * float2(offset, 1.0);
  924. // Scale and bias to access texel centers:
  925. scale += float2(-1.0, 1.0);
  926. bias += float2( 0.5, -0.5);
  927. // Convert from pixel coordinates to texcoords:
  928. // (We use SMAA_SEARCHTEX_PACKED_SIZE because the texture is cropped)
  929. scale *= 1.0 / SMAA_SEARCHTEX_PACKED_SIZE;
  930. bias *= 1.0 / SMAA_SEARCHTEX_PACKED_SIZE;
  931. // Lookup the search texture:
  932. return SMAA_SEARCHTEX_SELECT(SMAASampleLevelZero(searchTex, mad(scale, e, bias)));
  933. }
  934. /**
  935. * Horizontal/vertical search functions for the 2nd pass.
  936. */
  937. float SMAASearchXLeft(SMAATexture2D(edgesTex), SMAATexture2D(searchTex), float2 texcoord, float end) {
  938. /**
  939. * @PSEUDO_GATHER4
  940. * This texcoord has been offset by (-0.25, -0.125) in the vertex shader to
  941. * sample between edge, thus fetching four edges in a row.
  942. * Sampling with different offsets in each direction allows to disambiguate
  943. * which edges are active from the four fetched ones.
  944. */
  945. float2 e = float2(0.0, 1.0);
  946. while (texcoord.x > end &&
  947. e.g > 0.8281 && // Is there some edge not activated?
  948. e.r == 0.0) { // Or is there a crossing edge that breaks the line?
  949. e = SMAASampleLevelZero(edgesTex, texcoord).rg;
  950. texcoord = mad(-float2(2.0, 0.0), SMAA_RT_METRICS.xy, texcoord);
  951. }
  952. float offset = mad(-(255.0 / 127.0), SMAASearchLength(SMAATexturePass2D(searchTex), e, 0.0), 3.25);
  953. return mad(SMAA_RT_METRICS.x, offset, texcoord.x);
  954. // Non-optimized version:
  955. // We correct the previous (-0.25, -0.125) offset we applied:
  956. // texcoord.x += 0.25 * SMAA_RT_METRICS.x;
  957. // The searches are bias by 1, so adjust the coords accordingly:
  958. // texcoord.x += SMAA_RT_METRICS.x;
  959. // Disambiguate the length added by the last step:
  960. // texcoord.x += 2.0 * SMAA_RT_METRICS.x; // Undo last step
  961. // texcoord.x -= SMAA_RT_METRICS.x * (255.0 / 127.0) * SMAASearchLength(SMAATexturePass2D(searchTex), e, 0.0);
  962. // return mad(SMAA_RT_METRICS.x, offset, texcoord.x);
  963. }
  964. float SMAASearchXRight(SMAATexture2D(edgesTex), SMAATexture2D(searchTex), float2 texcoord, float end) {
  965. float2 e = float2(0.0, 1.0);
  966. while (texcoord.x < end &&
  967. e.g > 0.8281 && // Is there some edge not activated?
  968. e.r == 0.0) { // Or is there a crossing edge that breaks the line?
  969. e = SMAASampleLevelZero(edgesTex, texcoord).rg;
  970. texcoord = mad(float2(2.0, 0.0), SMAA_RT_METRICS.xy, texcoord);
  971. }
  972. float offset = mad(-(255.0 / 127.0), SMAASearchLength(SMAATexturePass2D(searchTex), e, 0.5), 3.25);
  973. return mad(-SMAA_RT_METRICS.x, offset, texcoord.x);
  974. }
  975. float SMAASearchYUp(SMAATexture2D(edgesTex), SMAATexture2D(searchTex), float2 texcoord, float end) {
  976. float2 e = float2(1.0, 0.0);
  977. while (texcoord.y > end &&
  978. e.r > 0.8281 && // Is there some edge not activated?
  979. e.g == 0.0) { // Or is there a crossing edge that breaks the line?
  980. e = SMAASampleLevelZero(edgesTex, texcoord).rg;
  981. texcoord = mad(-float2(0.0, 2.0), SMAA_RT_METRICS.xy, texcoord);
  982. }
  983. float offset = mad(-(255.0 / 127.0), SMAASearchLength(SMAATexturePass2D(searchTex), e.gr, 0.0), 3.25);
  984. return mad(SMAA_RT_METRICS.y, offset, texcoord.y);
  985. }
  986. float SMAASearchYDown(SMAATexture2D(edgesTex), SMAATexture2D(searchTex), float2 texcoord, float end) {
  987. float2 e = float2(1.0, 0.0);
  988. while (texcoord.y < end &&
  989. e.r > 0.8281 && // Is there some edge not activated?
  990. e.g == 0.0) { // Or is there a crossing edge that breaks the line?
  991. e = SMAASampleLevelZero(edgesTex, texcoord).rg;
  992. texcoord = mad(float2(0.0, 2.0), SMAA_RT_METRICS.xy, texcoord);
  993. }
  994. float offset = mad(-(255.0 / 127.0), SMAASearchLength(SMAATexturePass2D(searchTex), e.gr, 0.5), 3.25);
  995. return mad(-SMAA_RT_METRICS.y, offset, texcoord.y);
  996. }
  997. /**
  998. * Ok, we have the distance and both crossing edges. So, what are the areas
  999. * at each side of current edge?
  1000. */
  1001. float2 SMAAArea(SMAATexture2D(areaTex), float2 dist, float e1, float e2, float offset) {
  1002. // Rounding prevents precision errors of bilinear filtering:
  1003. float2 texcoord = mad(float2(SMAA_AREATEX_MAX_DISTANCE, SMAA_AREATEX_MAX_DISTANCE), round(4.0 * float2(e1, e2)), dist);
  1004. // We do a scale and bias for mapping to texel space:
  1005. texcoord = mad(SMAA_AREATEX_PIXEL_SIZE, texcoord, 0.5 * SMAA_AREATEX_PIXEL_SIZE);
  1006. // Move to proper place, according to the subpixel offset:
  1007. texcoord.y = mad(SMAA_AREATEX_SUBTEX_SIZE, offset, texcoord.y);
  1008. // Do it!
  1009. return SMAA_AREATEX_SELECT(SMAASampleLevelZero(areaTex, texcoord));
  1010. }
  1011. //-----------------------------------------------------------------------------
  1012. // Corner Detection Functions
  1013. void SMAADetectHorizontalCornerPattern(SMAATexture2D(edgesTex), inout float2 weights, float4 texcoord, float2 d) {
  1014. #if !defined(SMAA_DISABLE_CORNER_DETECTION)
  1015. float2 leftRight = step(d.xy, d.yx);
  1016. float2 rounding = (1.0 - SMAA_CORNER_ROUNDING_NORM) * leftRight;
  1017. rounding /= leftRight.x + leftRight.y; // Reduce blending for pixels in the center of a line.
  1018. float2 factor = float2(1.0, 1.0);
  1019. factor.x -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, int2(0, 1)).r;
  1020. factor.x -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, int2(1, 1)).r;
  1021. factor.y -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, int2(0, -2)).r;
  1022. factor.y -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, int2(1, -2)).r;
  1023. weights *= saturate(factor);
  1024. #endif
  1025. }
  1026. void SMAADetectVerticalCornerPattern(SMAATexture2D(edgesTex), inout float2 weights, float4 texcoord, float2 d) {
  1027. #if !defined(SMAA_DISABLE_CORNER_DETECTION)
  1028. float2 leftRight = step(d.xy, d.yx);
  1029. float2 rounding = (1.0 - SMAA_CORNER_ROUNDING_NORM) * leftRight;
  1030. rounding /= leftRight.x + leftRight.y;
  1031. float2 factor = float2(1.0, 1.0);
  1032. factor.x -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, int2( 1, 0)).g;
  1033. factor.x -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, int2( 1, 1)).g;
  1034. factor.y -= rounding.x * SMAASampleLevelZeroOffset(edgesTex, texcoord.xy, int2(-2, 0)).g;
  1035. factor.y -= rounding.y * SMAASampleLevelZeroOffset(edgesTex, texcoord.zw, int2(-2, 1)).g;
  1036. weights *= saturate(factor);
  1037. #endif
  1038. }
  1039. //-----------------------------------------------------------------------------
  1040. // Blending Weight Calculation Pixel Shader (Second Pass)
  1041. float4 SMAABlendingWeightCalculationPS(float2 texcoord,
  1042. float2 pixcoord,
  1043. float4 offset[3],
  1044. SMAATexture2D(edgesTex),
  1045. SMAATexture2D(areaTex),
  1046. SMAATexture2D(searchTex),
  1047. float4 subsampleIndices) { // Just pass zero for SMAA 1x, see @SUBSAMPLE_INDICES.
  1048. float4 weights = float4(0.0, 0.0, 0.0, 0.0);
  1049. float2 e = SMAASample(edgesTex, texcoord).rg;
  1050. SMAA_BRANCH
  1051. if (e.g > 0.0) { // Edge at north
  1052. #if !defined(SMAA_DISABLE_DIAG_DETECTION)
  1053. // Diagonals have both north and west edges, so searching for them in
  1054. // one of the boundaries is enough.
  1055. weights.rg = SMAACalculateDiagWeights(SMAATexturePass2D(edgesTex), SMAATexturePass2D(areaTex), texcoord, e, subsampleIndices);
  1056. // We give priority to diagonals, so if we find a diagonal we skip
  1057. // horizontal/vertical processing.
  1058. SMAA_BRANCH
  1059. if (weights.r == -weights.g) { // weights.r + weights.g == 0.0
  1060. #endif
  1061. float2 d;
  1062. // Find the distance to the left:
  1063. float3 coords;
  1064. coords.x = SMAASearchXLeft(SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[0].xy, offset[2].x);
  1065. coords.y = offset[1].y; // offset[1].y = texcoord.y - 0.25 * SMAA_RT_METRICS.y (@CROSSING_OFFSET)
  1066. d.x = coords.x;
  1067. // Now fetch the left crossing edges, two at a time using bilinear
  1068. // filtering. Sampling at -0.25 (see @CROSSING_OFFSET) enables to
  1069. // discern what value each edge has:
  1070. float e1 = SMAASampleLevelZero(edgesTex, coords.xy).r;
  1071. // Find the distance to the right:
  1072. coords.z = SMAASearchXRight(SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[0].zw, offset[2].y);
  1073. d.y = coords.z;
  1074. // We want the distances to be in pixel units (doing this here allow to
  1075. // better interleave arithmetic and memory accesses):
  1076. d = abs(round(mad(SMAA_RT_METRICS.zz, d, -pixcoord.xx)));
  1077. // SMAAArea below needs a sqrt, as the areas texture is compressed
  1078. // quadratically:
  1079. float2 sqrt_d = sqrt(d);
  1080. // Fetch the right crossing edges:
  1081. float e2 = SMAASampleLevelZeroOffset(edgesTex, coords.zy, int2(1, 0)).r;
  1082. // Ok, we know how this pattern looks like, now it is time for getting
  1083. // the actual area:
  1084. weights.rg = SMAAArea(SMAATexturePass2D(areaTex), sqrt_d, e1, e2, subsampleIndices.y);
  1085. // Fix corners:
  1086. coords.y = texcoord.y;
  1087. SMAADetectHorizontalCornerPattern(SMAATexturePass2D(edgesTex), weights.rg, coords.xyzy, d);
  1088. #if !defined(SMAA_DISABLE_DIAG_DETECTION)
  1089. } else
  1090. e.r = 0.0; // Skip vertical processing.
  1091. #endif
  1092. }
  1093. SMAA_BRANCH
  1094. if (e.r > 0.0) { // Edge at west
  1095. float2 d;
  1096. // Find the distance to the top:
  1097. float3 coords;
  1098. coords.y = SMAASearchYUp(SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[1].xy, offset[2].z);
  1099. coords.x = offset[0].x; // offset[1].x = texcoord.x - 0.25 * SMAA_RT_METRICS.x;
  1100. d.x = coords.y;
  1101. // Fetch the top crossing edges:
  1102. float e1 = SMAASampleLevelZero(edgesTex, coords.xy).g;
  1103. // Find the distance to the bottom:
  1104. coords.z = SMAASearchYDown(SMAATexturePass2D(edgesTex), SMAATexturePass2D(searchTex), offset[1].zw, offset[2].w);
  1105. d.y = coords.z;
  1106. // We want the distances to be in pixel units:
  1107. d = abs(round(mad(SMAA_RT_METRICS.ww, d, -pixcoord.yy)));
  1108. // SMAAArea below needs a sqrt, as the areas texture is compressed
  1109. // quadratically:
  1110. float2 sqrt_d = sqrt(d);
  1111. // Fetch the bottom crossing edges:
  1112. float e2 = SMAASampleLevelZeroOffset(edgesTex, coords.xz, int2(0, 1)).g;
  1113. // Get the area for this direction:
  1114. weights.ba = SMAAArea(SMAATexturePass2D(areaTex), sqrt_d, e1, e2, subsampleIndices.x);
  1115. // Fix corners:
  1116. coords.x = texcoord.x;
  1117. SMAADetectVerticalCornerPattern(SMAATexturePass2D(edgesTex), weights.ba, coords.xyxz, d);
  1118. }
  1119. return weights;
  1120. }
  1121. //-----------------------------------------------------------------------------
  1122. // UV-based reprojection functions
  1123. #if SMAA_UV_BASED_REPROJECTION
  1124. float2 SMAAReproject(float2 texcoord)
  1125. {
  1126. // UV to clip-position:
  1127. // -- This must be sampled at exactly mip 0 due to possible gradient divergence
  1128. // -- as this function is called within a control flow block down below.
  1129. float depth = SMAASampleLevelZero(_CameraDepthTexture, texcoord).r;
  1130. float3 clipPosition = float3(2. * texcoord - 1., depth);
  1131. // Reproject
  1132. float4 previousClipPosition = mul(_ReprojectionMatrix, float4(clipPosition, 1.));
  1133. previousClipPosition.xyz /= previousClipPosition.w;
  1134. // Clip-position to UV
  1135. return (.5 * previousClipPosition.xy + .5);
  1136. }
  1137. #endif
  1138. //-----------------------------------------------------------------------------
  1139. // Neighborhood Blending Pixel Shader (Third Pass)
  1140. float4 SMAANeighborhoodBlendingPS(float2 texcoord,
  1141. float4 offset,
  1142. SMAATexture2D(colorTex),
  1143. SMAATexture2D(blendTex)
  1144. #if SMAA_REPROJECTION
  1145. , SMAATexture2D(velocityTex)
  1146. #endif
  1147. ) {
  1148. // Fetch the blending weights for current pixel:
  1149. float4 a;
  1150. a.x = SMAASample(blendTex, offset.xy).a; // Right
  1151. a.y = SMAASample(blendTex, offset.zw).g; // Top
  1152. a.wz = SMAASample(blendTex, texcoord).xz; // Bottom / Left
  1153. // Is there any blending weight with a value greater than 0.0?
  1154. SMAA_BRANCH
  1155. if (dot(a, float4(1.0, 1.0, 1.0, 1.0)) < 1e-5) {
  1156. float4 color = SMAASampleLevelZero(colorTex, texcoord);
  1157. #if SMAA_REPROJECTION
  1158. float2 velocity = SMAA_DECODE_VELOCITY(SMAASampleLevelZero(velocityTex, texcoord));
  1159. #elif SMAA_UV_BASED_REPROJECTION
  1160. float2 velocity = texcoord - SMAAReproject(texcoord);
  1161. #endif
  1162. #if (SMAA_REPROJECTION || SMAA_UV_BASED_REPROJECTION)
  1163. // Pack velocity into the alpha channel:
  1164. color.a = sqrt(5.0 * length(velocity));
  1165. #endif
  1166. return color;
  1167. } else {
  1168. bool h = max(a.x, a.z) > max(a.y, a.w); // max(horizontal) > max(vertical)
  1169. // Calculate the blending offsets:
  1170. float4 blendingOffset = float4(0.0, a.y, 0.0, a.w);
  1171. float2 blendingWeight = a.yw;
  1172. SMAAMovc(bool4(h, h, h, h), blendingOffset, float4(a.x, 0.0, a.z, 0.0));
  1173. SMAAMovc(bool2(h, h), blendingWeight, a.xz);
  1174. blendingWeight /= dot(blendingWeight, float2(1.0, 1.0));
  1175. // Calculate the texture coordinates:
  1176. float4 blendingCoord = mad(blendingOffset, float4(SMAA_RT_METRICS.xy, -SMAA_RT_METRICS.xy), texcoord.xyxy);
  1177. // We exploit bilinear filtering to mix current pixel with the chosen
  1178. // neighbor:
  1179. float4 color = blendingWeight.x * SMAASampleLevelZero(colorTex, blendingCoord.xy);
  1180. color += blendingWeight.y * SMAASampleLevelZero(colorTex, blendingCoord.zw);
  1181. #if SMAA_REPROJECTION
  1182. // Antialias velocity for proper reprojection in a later stage:
  1183. float2 velocity = blendingWeight.x * SMAA_DECODE_VELOCITY(SMAASampleLevelZero(velocityTex, blendingCoord.xy));
  1184. velocity += blendingWeight.y * SMAA_DECODE_VELOCITY(SMAASampleLevelZero(velocityTex, blendingCoord.zw));
  1185. #elif SMAA_UV_BASED_REPROJECTION
  1186. // Antialias velocity for proper reprojection in a later stage:
  1187. float2 velocity = blendingWeight.x * (blendingCoord.xy - SMAAReproject(blendingCoord.xy));
  1188. velocity += blendingWeight.y * (blendingCoord.zw - SMAAReproject(blendingCoord.zw));
  1189. #endif
  1190. #if (SMAA_REPROJECTION || SMAA_UV_BASED_REPROJECTION)
  1191. // Pack velocity into the alpha channel:
  1192. color.a = sqrt(5.0 * length(velocity));
  1193. #endif
  1194. return color;
  1195. }
  1196. }
  1197. //-----------------------------------------------------------------------------
  1198. // Temporal Resolve Pixel Shader (Optional Pass)
  1199. float4 SMAAResolvePS(float2 texcoord,
  1200. SMAATexture2D(currentColorTex),
  1201. SMAATexture2D(previousColorTex)
  1202. #if SMAA_REPROJECTION
  1203. , SMAATexture2D(velocityTex)
  1204. #endif
  1205. ) {
  1206. #if SMAA_REPROJECTION
  1207. // Velocity is assumed to be calculated for motion blur, so we need to
  1208. // inverse it for reprojection:
  1209. float2 velocity = -SMAA_DECODE_VELOCITY(SMAASamplePoint(velocityTex, texcoord).rg);
  1210. #elif SMAA_UV_BASED_REPROJECTION
  1211. float2 velocity = SMAAReproject(texcoord) - texcoord;
  1212. #endif
  1213. #if (SMAA_REPROJECTION || SMAA_UV_BASED_REPROJECTION)
  1214. // Fetch current pixel:
  1215. float4 current = SMAASamplePoint(currentColorTex, texcoord);
  1216. // Reproject current coordinates and fetch previous pixel:
  1217. float4 previous = SMAASamplePoint(previousColorTex, texcoord + velocity);
  1218. // Attenuate the previous pixel if the velocity is different:
  1219. float delta = abs(current.a * current.a - previous.a * previous.a) / 5.0;
  1220. float weight = 0.5 * saturate(1.0 - sqrt(delta) * SMAA_REPROJECTION_WEIGHT_SCALE);
  1221. // Blend the pixels according to the calculated weight:
  1222. // return lerp(current, previous, weight);
  1223. // Neighbour clamp
  1224. // Contributed by pommak
  1225. float4 n0 = SMAASampleOffset(currentColorTex, texcoord, float2(-1, -1));
  1226. float4 n1 = SMAASampleOffset(currentColorTex, texcoord, float2(+1, -1));
  1227. float4 n2 = SMAASampleOffset(currentColorTex, texcoord, float2(-1, +1));
  1228. float4 n3 = SMAASampleOffset(currentColorTex, texcoord, float2(+1, +1));
  1229. float4 cmax = max(n0, max(n1, max(n2, n3)));
  1230. float4 cmin = min(n0, min(n1, min(n2, n3)));
  1231. float4 avg = 0.25 * (n0+n1+n2+n3);
  1232. float4 wk = abs(avg - current);
  1233. float blend = saturate(lerp(0.35, 0.85, wk));
  1234. // Clamp previous to neighbours colors
  1235. float4 previousClamped = clamp(previous, cmin, cmax);
  1236. float4 color = lerp(lerp(current, previousClamped, 0.5*weight), previousClamped, weight);
  1237. return color;
  1238. #else
  1239. // Just blend the pixels:
  1240. float4 current = SMAASamplePoint(currentColorTex, texcoord);
  1241. float4 previous = SMAASamplePoint(previousColorTex, texcoord);
  1242. return lerp(current, previous, 0.5);
  1243. #endif
  1244. }
  1245. //-----------------------------------------------------------------------------
  1246. // Separate Multisamples Pixel Shader (Optional Pass)
  1247. #ifdef SMAALoad
  1248. void SMAASeparatePS(float4 position,
  1249. float2 texcoord,
  1250. out float4 target0,
  1251. out float4 target1,
  1252. SMAATexture2DMS2(colorTexMS)) {
  1253. int2 pos = int2(position.xy);
  1254. target0 = SMAALoad(colorTexMS, pos, 0);
  1255. target1 = SMAALoad(colorTexMS, pos, 1);
  1256. }
  1257. #endif
  1258. //-----------------------------------------------------------------------------
  1259. #endif // SMAA_INCLUDE_PS