smaa.hlsl 53 KB

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