smaa.glslf 48 KB

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