2
0

gBufferConditionerGLSL.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "lighting/advanced/glsl/gBufferConditionerGLSL.h"
  24. #include "shaderGen/featureMgr.h"
  25. #include "gfx/gfxStringEnumTranslate.h"
  26. #include "materials/materialFeatureTypes.h"
  27. #include "materials/materialFeatureData.h"
  28. #include "shaderGen/GLSL/shaderFeatureGLSL.h"
  29. GBufferConditionerGLSL::GBufferConditionerGLSL( const GFXFormat bufferFormat, const NormalSpace nrmSpace ) :
  30. Parent( bufferFormat )
  31. {
  32. // Figure out how we should store the normal data. These are the defaults.
  33. mCanWriteNegativeValues = false;
  34. mNormalStorageType = CartesianXYZ;
  35. // Note: We clear to a depth 1 (the w component) so
  36. // that the unrendered parts of the scene end up
  37. // farthest to the camera.
  38. const NormalStorage &twoCmpNrmStorageType = ( nrmSpace == WorldSpace ? Spherical : LambertAzimuthal );
  39. switch(bufferFormat)
  40. {
  41. case GFXFormatR8G8B8A8:
  42. mNormalStorageType = twoCmpNrmStorageType;
  43. mBitsPerChannel = 8;
  44. break;
  45. case GFXFormatR16G16B16A16F:
  46. // Floating point buffers don't need to encode negative values
  47. mCanWriteNegativeValues = true;
  48. mNormalStorageType = twoCmpNrmStorageType;
  49. mBitsPerChannel = 16;
  50. break;
  51. // Store a 32bit depth with a sperical normal in the
  52. // integer 16 format. This gives us perfect depth
  53. // precision and high quality normals within a 64bit
  54. // buffer format.
  55. case GFXFormatR16G16B16A16:
  56. mNormalStorageType = twoCmpNrmStorageType;
  57. mBitsPerChannel = 16;
  58. break;
  59. case GFXFormatR32G32B32A32F:
  60. mCanWriteNegativeValues = true;
  61. mNormalStorageType = CartesianXYZ;
  62. mBitsPerChannel = 32;
  63. break;
  64. default:
  65. AssertFatal(false, "Unsupported G-Buffer format");
  66. }
  67. }
  68. GBufferConditionerGLSL::~GBufferConditionerGLSL()
  69. {
  70. }
  71. void GBufferConditionerGLSL::processVert( Vector<ShaderComponent*> &componentList,
  72. const MaterialFeatureData &fd )
  73. {
  74. // If we have a normal map then that feature will
  75. // take care of passing gbNormal to the pixel shader.
  76. if ( fd.features[MFT_NormalMap] )
  77. return;
  78. MultiLine *meta = new MultiLine;
  79. output = meta;
  80. // grab incoming vert normal
  81. Var *inNormal = (Var*) LangElement::find( "normal" );
  82. AssertFatal( inNormal, "Something went bad with ShaderGen. The normal should be already defined." );
  83. // grab output for gbuffer normal
  84. ShaderConnector *connectComp = dynamic_cast<ShaderConnector *>( componentList[C_CONNECTOR] );
  85. Var *outNormal = connectComp->getElement( RT_TEXCOORD );
  86. outNormal->setName( "gbNormal" );
  87. outNormal->setStructName( "OUT" );
  88. outNormal->setType( "float3" );
  89. if( !fd.features[MFT_ParticleNormal] )
  90. {
  91. // Kick out the view-space normal
  92. // TODO: Total hack because Conditioner is directly derived
  93. // from ShaderFeature and not from ShaderFeatureGLSL.
  94. NamedFeatureGLSL dummy( String::EmptyString );
  95. dummy.mInstancingFormat = mInstancingFormat;
  96. Var *worldViewOnly = dummy.getWorldView( componentList, fd.features[MFT_UseInstancing], meta );
  97. meta->addStatement( new GenOp(" @ = tMul(@, float4( normalize(@), 0.0 ) ).xyz;\r\n",
  98. outNormal, worldViewOnly, inNormal ) );
  99. }
  100. else
  101. {
  102. // Assume the particle normal generator has already put this in view space
  103. // and normalized it
  104. meta->addStatement( new GenOp( " @ = @;\r\n", outNormal, inNormal ) );
  105. }
  106. }
  107. void GBufferConditionerGLSL::processPix( Vector<ShaderComponent*> &componentList,
  108. const MaterialFeatureData &fd )
  109. {
  110. // sanity
  111. AssertFatal( fd.features[MFT_EyeSpaceDepthOut], "No depth-out feature enabled! Bad news!" );
  112. MultiLine *meta = new MultiLine;
  113. // grab connector normal
  114. ShaderConnector *connectComp = dynamic_cast<ShaderConnector *>( componentList[C_CONNECTOR] );
  115. Var *gbNormal = (Var*) LangElement::find( "gbNormal" );
  116. if( !gbNormal )
  117. {
  118. gbNormal = connectComp->getElement( RT_TEXCOORD );
  119. gbNormal->setName( "gbNormal" );
  120. gbNormal->setStructName( "IN" );
  121. gbNormal->setType( "float3" );
  122. gbNormal->mapsToSampler = false;
  123. gbNormal->uniform = false;
  124. }
  125. // find depth
  126. ShaderFeature *depthFeat = FEATUREMGR->getByType( MFT_EyeSpaceDepthOut );
  127. AssertFatal( depthFeat != NULL, "No eye space depth feature found!" );
  128. Var *depth = (Var*) LangElement::find(depthFeat->getOutputVarName());
  129. AssertFatal( depth, "Something went bad with ShaderGen. The depth should be already generated by the EyeSpaceDepthOut feature." );
  130. Var *unconditionedOut = new Var;
  131. unconditionedOut->setType("float4");
  132. unconditionedOut->setName("normal_depth");
  133. LangElement *outputDecl = new DecOp( unconditionedOut );
  134. // If we're doing prepass blending then we need
  135. // to steal away the alpha channel before the
  136. // conditioner stomps on it.
  137. Var *alphaVal = NULL;
  138. if ( fd.features[ MFT_IsTranslucentZWrite ] )
  139. {
  140. alphaVal = new Var( "outAlpha", "float" );
  141. meta->addStatement( new GenOp( " @ = col.a; // MFT_IsTranslucentZWrite\r\n", new DecOp( alphaVal ) ) );
  142. }
  143. // If using interlaced normals, invert the normal
  144. if(fd.features[MFT_InterlacedPrePass])
  145. {
  146. // NOTE: Its safe to not call ShaderFeatureGLSL::addOutVpos() in the vertex
  147. // shader as for SM 3.0 nothing is needed there.
  148. Var *Vpos = (Var*) LangElement::find( "gl_Position" ); //Var *Vpos = ShaderFeatureGLSL::getInVpos( meta, componentList );
  149. Var *iGBNormal = new Var( "interlacedGBNormal", "float3" );
  150. meta->addStatement(new GenOp(" @ = (frac(@.y * 0.5) < 0.1 ? reflect(@, float3(0.0, -1.0, 0.0)) : @);\r\n", new DecOp(iGBNormal), Vpos, gbNormal, gbNormal));
  151. gbNormal = iGBNormal;
  152. }
  153. // NOTE: We renormalize the normal here as they
  154. // will not stay normalized during interpolation.
  155. meta->addStatement( new GenOp(" @ = @;", outputDecl, new GenOp( "float4(normalize(@), @)", gbNormal, depth ) ) );
  156. meta->addStatement( assignOutput( unconditionedOut ) );
  157. // If we have an alpha var then we're doing prepass lerp blending.
  158. if ( alphaVal )
  159. {
  160. Var *outColor = (Var*)LangElement::find( getOutputTargetVarName( DefaultTarget ) );
  161. meta->addStatement( new GenOp( " @.ba = float2( 0, @ ); // MFT_IsTranslucentZWrite\r\n", outColor, alphaVal ) );
  162. }
  163. output = meta;
  164. }
  165. ShaderFeature::Resources GBufferConditionerGLSL::getResources( const MaterialFeatureData &fd )
  166. {
  167. Resources res;
  168. // Passing from VS->PS:
  169. // - world space normal (gbNormal)
  170. res.numTexReg = 1;
  171. return res;
  172. }
  173. Var* GBufferConditionerGLSL::printMethodHeader( MethodType methodType, const String &methodName, Stream &stream, MultiLine *meta )
  174. {
  175. const bool isCondition = ( methodType == ConditionerFeature::ConditionMethod );
  176. Var *retVal = NULL;
  177. // The uncondition method inputs are changed
  178. if( isCondition )
  179. retVal = Parent::printMethodHeader( methodType, methodName, stream, meta );
  180. else
  181. {
  182. Var *methodVar = new Var;
  183. methodVar->setName(methodName);
  184. methodVar->setType("float4");
  185. DecOp *methodDecl = new DecOp(methodVar);
  186. Var *prepassSampler = new Var;
  187. prepassSampler->setName("prepassSamplerVar");
  188. prepassSampler->setType("sampler2D");
  189. DecOp *prepassSamplerDecl = new DecOp(prepassSampler);
  190. Var *screenUV = new Var;
  191. screenUV->setName("screenUVVar");
  192. screenUV->setType("float2");
  193. DecOp *screenUVDecl = new DecOp(screenUV);
  194. Var *bufferSample = new Var;
  195. bufferSample->setName("bufferSample");
  196. bufferSample->setType("float4");
  197. DecOp *bufferSampleDecl = new DecOp(bufferSample);
  198. meta->addStatement( new GenOp( "@(@, @)\r\n", methodDecl, prepassSamplerDecl, screenUVDecl ) );
  199. meta->addStatement( new GenOp( "{\r\n" ) );
  200. meta->addStatement( new GenOp( " // Sampler g-buffer\r\n" ) );
  201. #ifdef TORQUE_OS_XENON
  202. meta->addStatement( new GenOp( " @;\r\n", bufferSampleDecl ) );
  203. meta->addStatement( new GenOp( " asm { tfetch2D @, @, @, MagFilter = point, MinFilter = point, MipFilter = point };\r\n", bufferSample, screenUV, prepassSampler ) );
  204. #else
  205. // The gbuffer has no mipmaps, so use tex2dlod when
  206. // possible so that the shader compiler can optimize.
  207. meta->addStatement( new GenOp( " #if TORQUE_SM >= 30\r\n" ) );
  208. meta->addStatement( new GenOp( " @ = tex2Dlod(@, float4(@,0,0));\r\n", bufferSampleDecl, prepassSampler, screenUV ) );
  209. meta->addStatement( new GenOp( " #else\r\n" ) );
  210. meta->addStatement( new GenOp( " @ = tex2D(@, @);\r\n", bufferSampleDecl, prepassSampler, screenUV ) );
  211. meta->addStatement( new GenOp( " #endif\r\n\r\n" ) );
  212. #endif
  213. // We don't use this way of passing var's around, so this should cause a crash
  214. // if something uses this improperly
  215. retVal = bufferSample;
  216. }
  217. return retVal;
  218. }
  219. GenOp* GBufferConditionerGLSL::_posnegEncode( GenOp *val )
  220. {
  221. if(mNormalStorageType == LambertAzimuthal)
  222. return mCanWriteNegativeValues ? val : new GenOp(avar("(%f * (@ + %f))", 1.0f/(M_SQRT2_F * 2.0f), M_SQRT2_F), val);
  223. else
  224. return mCanWriteNegativeValues ? val : new GenOp("(0.5 * (@ + 1.0))", val);
  225. }
  226. GenOp* GBufferConditionerGLSL::_posnegDecode( GenOp *val )
  227. {
  228. if(mNormalStorageType == LambertAzimuthal)
  229. return mCanWriteNegativeValues ? val : new GenOp(avar("(@ * %f - %f)", M_SQRT2_F * 2.0f, M_SQRT2_F), val);
  230. else
  231. return mCanWriteNegativeValues ? val : new GenOp("(@ * 2.0 - 1.0)", val);
  232. }
  233. Var* GBufferConditionerGLSL::_conditionOutput( Var *unconditionedOutput, MultiLine *meta )
  234. {
  235. Var *retVar = new Var;
  236. retVar->setType("float4");
  237. retVar->setName("_gbConditionedOutput");
  238. LangElement *outputDecl = new DecOp( retVar );
  239. switch(mNormalStorageType)
  240. {
  241. case CartesianXYZ:
  242. meta->addStatement( new GenOp( " // g-buffer conditioner: float4(normal.xyz, depth)\r\n" ) );
  243. meta->addStatement( new GenOp( " @ = float4(@, @.a);\r\n", outputDecl,
  244. _posnegEncode(new GenOp("@.xyz", unconditionedOutput)), unconditionedOutput ) );
  245. break;
  246. case CartesianXY:
  247. meta->addStatement( new GenOp( " // g-buffer conditioner: float4(normal.xy, depth Hi + z-sign, depth Lo)\r\n" ) );
  248. meta->addStatement( new GenOp( " @ = float4(@, @.a);", outputDecl,
  249. _posnegEncode(new GenOp("float3(@.xy, sign(@.z))", unconditionedOutput, unconditionedOutput)), unconditionedOutput ) );
  250. break;
  251. case Spherical:
  252. meta->addStatement( new GenOp( " // g-buffer conditioner: float4(normal.theta, normal.phi, depth Hi, depth Lo)\r\n" ) );
  253. meta->addStatement( new GenOp( " @ = float4(@, 0.0, @.a);\r\n", outputDecl,
  254. _posnegEncode(new GenOp("float2(atan2(@.y, @.x) / 3.14159265358979323846f, @.z)", unconditionedOutput, unconditionedOutput, unconditionedOutput ) ),
  255. unconditionedOutput ) );
  256. // HACK: This fixes the noise present when using a floating point
  257. // gbuffer on Geforce cards and the "flat areas unlit" issues.
  258. //
  259. // We need work around atan2() above to fix this issue correctly
  260. // without the extra overhead of this test.
  261. //
  262. meta->addStatement( new GenOp( " if ( abs( dot( @.xyz, float3( 0.0, 0.0, 1.0 ) ) ) > 0.999f ) @ = float4( 0, 1 * sign( @.z ), 0, @.a );\r\n",
  263. unconditionedOutput, retVar, unconditionedOutput, unconditionedOutput ) );
  264. break;
  265. case LambertAzimuthal:
  266. //http://en.wikipedia.org/wiki/Lambert_azimuthal_equal-area_projection
  267. //
  268. // Note we're casting to half to use partial precision
  269. // sqrt which is much faster on older Geforces while
  270. // still being acceptable for normals.
  271. //
  272. meta->addStatement( new GenOp( " // g-buffer conditioner: float4(normal.X, normal.Y, depth Hi, depth Lo)\r\n" ) );
  273. meta->addStatement( new GenOp( " @ = float4(@, 0.0, @.a);\r\n", outputDecl,
  274. _posnegEncode(new GenOp("sqrt(half(2.0/(1.0 - @.y))) * half2(@.xz)", unconditionedOutput, unconditionedOutput)),
  275. unconditionedOutput ) );
  276. break;
  277. }
  278. // Encode depth into two channels
  279. if(mNormalStorageType != CartesianXYZ)
  280. {
  281. const U64 maxValPerChannel = (U64)1 << mBitsPerChannel;
  282. meta->addStatement( new GenOp( " \r\n // Encode depth into hi/lo\r\n" ) );
  283. meta->addStatement( new GenOp( avar( " float2 _tempDepth = frac(@.a * float2(1.0, %llu.0));\r\n", maxValPerChannel - 1 ),
  284. unconditionedOutput ) );
  285. meta->addStatement( new GenOp( avar( " @.zw = _tempDepth.xy - _tempDepth.yy * float2(1.0/%llu.0, 0.0);\r\n\r\n", maxValPerChannel - 1 ),
  286. retVar ) );
  287. }
  288. AssertFatal( retVar != NULL, avar( "Cannot condition output to buffer format: %s", GFXStringTextureFormat[getBufferFormat()] ) );
  289. return retVar;
  290. }
  291. Var* GBufferConditionerGLSL::_unconditionInput( Var *conditionedInput, MultiLine *meta )
  292. {
  293. Var *retVar = new Var;
  294. retVar->setType("float4");
  295. retVar->setName("_gbUnconditionedInput");
  296. LangElement *outputDecl = new DecOp( retVar );
  297. switch(mNormalStorageType)
  298. {
  299. case CartesianXYZ:
  300. meta->addStatement( new GenOp( " // g-buffer unconditioner: float4(normal.xyz, depth)\r\n" ) );
  301. meta->addStatement( new GenOp( " @ = float4(@, @.a);\r\n", outputDecl,
  302. _posnegDecode(new GenOp("@.xyz", conditionedInput)), conditionedInput ) );
  303. break;
  304. case CartesianXY:
  305. meta->addStatement( new GenOp( " // g-buffer unconditioner: float4(normal.xy, depth Hi + z-sign, depth Lo)\r\n" ) );
  306. meta->addStatement( new GenOp( " @ = float4(@, @.a);\r\n", outputDecl,
  307. _posnegDecode(new GenOp("@.xyz", conditionedInput)), conditionedInput ) );
  308. meta->addStatement( new GenOp( " @.z *= sqrt(1.0 - dot(@.xy, @.xy));\r\n", retVar, retVar, retVar ) );
  309. break;
  310. case Spherical:
  311. meta->addStatement( new GenOp( " // g-buffer unconditioner: float4(normal.theta, normal.phi, depth Hi, depth Lo)\r\n" ) );
  312. meta->addStatement( new GenOp( " float2 spGPUAngles = @;\r\n", _posnegDecode(new GenOp("@.xy", conditionedInput)) ) );
  313. meta->addStatement( new GenOp( " float2 sincosTheta;\r\n" ) );
  314. meta->addStatement( new GenOp( " sincos(spGPUAngles.x * 3.14159265358979323846f, sincosTheta.x, sincosTheta.y);\r\n" ) );
  315. meta->addStatement( new GenOp( " float2 sincosPhi = float2(sqrt(1.0 - spGPUAngles.y * spGPUAngles.y), spGPUAngles.y);\r\n" ) );
  316. meta->addStatement( new GenOp( " @ = float4(sincosTheta.y * sincosPhi.x, sincosTheta.x * sincosPhi.x, sincosPhi.y, @.a);\r\n", outputDecl, conditionedInput ) );
  317. break;
  318. case LambertAzimuthal:
  319. // Note we're casting to half to use partial precision
  320. // sqrt which is much faster on older Geforces while
  321. // still being acceptable for normals.
  322. //
  323. meta->addStatement( new GenOp( " // g-buffer unconditioner: float4(normal.X, normal.Y, depth Hi, depth Lo)\r\n" ) );
  324. meta->addStatement( new GenOp( " float2 _inpXY = @;\r\n", _posnegDecode(new GenOp("@.xy", conditionedInput)) ) );
  325. meta->addStatement( new GenOp( " float _xySQ = dot(_inpXY, _inpXY);\r\n" ) );
  326. meta->addStatement( new GenOp( " @ = float4( sqrt(half(1.0 - (_xySQ / 4.0))) * _inpXY, -1.0 + (_xySQ / 2.0), @.a).xzyw;\r\n", outputDecl, conditionedInput ) );
  327. break;
  328. }
  329. // Recover depth from encoding
  330. if(mNormalStorageType != CartesianXYZ)
  331. {
  332. const U64 maxValPerChannel = 1 << mBitsPerChannel;
  333. meta->addStatement( new GenOp( " \r\n // Decode depth\r\n" ) );
  334. meta->addStatement( new GenOp( avar( " @.w = dot( @.zw, float2(1.0, 1.0/%llu.0));\r\n", maxValPerChannel - 1 ),
  335. retVar, conditionedInput ) );
  336. }
  337. AssertFatal( retVar != NULL, avar( "Cannot uncondition input from buffer format: %s", GFXStringTextureFormat[getBufferFormat()] ) );
  338. return retVar;
  339. }