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