gBufferConditionerGLSL.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. if (!inNormal)
  83. {
  84. inNormal = new Var("normal", "vec3");
  85. meta->addStatement(new GenOp(" @ = vec3( 0.0, 0.0, 1.0 );\r\n", new DecOp(inNormal)));
  86. Con::errorf("ShagerGen: Something went bad with ShaderGen. The normal should be already defined.");
  87. }
  88. AssertFatal( inNormal, "Something went bad with ShaderGen. The normal should be already defined." );
  89. // grab output for gbuffer normal
  90. ShaderConnector *connectComp = dynamic_cast<ShaderConnector *>( componentList[C_CONNECTOR] );
  91. Var *outNormal = connectComp->getElement( RT_TEXCOORD );
  92. outNormal->setName( "gbNormal" );
  93. outNormal->setStructName( "OUT" );
  94. outNormal->setType( "float3" );
  95. if( !fd.features[MFT_ParticleNormal] )
  96. {
  97. // Kick out the view-space normal
  98. // TODO: Total hack because Conditioner is directly derived
  99. // from ShaderFeature and not from ShaderFeatureGLSL.
  100. NamedFeatureGLSL dummy( String::EmptyString );
  101. dummy.setInstancingFormat( mInstancingFormat );
  102. Var *worldViewOnly = dummy.getWorldView( componentList, fd.features[MFT_UseInstancing], meta );
  103. meta->addStatement( new GenOp(" @ = tMul(@, float4( normalize(@), 0.0 ) ).xyz;\r\n",
  104. outNormal, worldViewOnly, inNormal ) );
  105. }
  106. else
  107. {
  108. // Assume the particle normal generator has already put this in view space
  109. // and normalized it
  110. meta->addStatement( new GenOp( " @ = @;\r\n", outNormal, inNormal ) );
  111. }
  112. }
  113. void GBufferConditionerGLSL::processPix( Vector<ShaderComponent*> &componentList,
  114. const MaterialFeatureData &fd )
  115. {
  116. // sanity
  117. AssertFatal( fd.features[MFT_EyeSpaceDepthOut], "No depth-out feature enabled! Bad news!" );
  118. MultiLine *meta = new MultiLine;
  119. // grab connector normal
  120. ShaderConnector *connectComp = dynamic_cast<ShaderConnector *>( componentList[C_CONNECTOR] );
  121. Var *gbNormal = (Var*) LangElement::find( "gbNormal" );
  122. if( !gbNormal )
  123. {
  124. gbNormal = connectComp->getElement( RT_TEXCOORD );
  125. gbNormal->setName( "gbNormal" );
  126. gbNormal->setStructName( "IN" );
  127. gbNormal->setType( "float3" );
  128. gbNormal->mapsToSampler = false;
  129. gbNormal->uniform = false;
  130. }
  131. // find depth
  132. ShaderFeature *depthFeat = FEATUREMGR->getByType( MFT_EyeSpaceDepthOut );
  133. AssertFatal( depthFeat != NULL, "No eye space depth feature found!" );
  134. Var *depth = (Var*) LangElement::find(depthFeat->getOutputVarName());
  135. AssertFatal( depth, "Something went bad with ShaderGen. The depth should be already generated by the EyeSpaceDepthOut feature." );
  136. Var *unconditionedOut = new Var;
  137. unconditionedOut->setType("float4");
  138. unconditionedOut->setName("normal_depth");
  139. LangElement *outputDecl = new DecOp( unconditionedOut );
  140. // If we're doing prepass blending then we need
  141. // to steal away the alpha channel before the
  142. // conditioner stomps on it.
  143. Var *alphaVal = NULL;
  144. if ( fd.features[ MFT_IsTranslucentZWrite ] )
  145. {
  146. alphaVal = new Var( "outAlpha", "float" );
  147. meta->addStatement( new GenOp( " @ = OUT_col1.a; // MFT_IsTranslucentZWrite\r\n", new DecOp( alphaVal ) ) );
  148. }
  149. // If using interlaced normals, invert the normal
  150. if(fd.features[MFT_InterlacedPrePass])
  151. {
  152. // NOTE: Its safe to not call ShaderFeatureGLSL::addOutVpos() in the vertex
  153. // shader as for SM 3.0 nothing is needed there.
  154. Var *Vpos = (Var*) LangElement::find( "gl_Position" ); //Var *Vpos = ShaderFeatureGLSL::getInVpos( meta, componentList );
  155. Var *iGBNormal = new Var( "interlacedGBNormal", "float3" );
  156. 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));
  157. gbNormal = iGBNormal;
  158. }
  159. // NOTE: We renormalize the normal here as they
  160. // will not stay normalized during interpolation.
  161. meta->addStatement( new GenOp(" @ = @;", outputDecl, new GenOp( "float4(normalize(@), @)", gbNormal, depth ) ) );
  162. meta->addStatement( assignOutput( unconditionedOut ) );
  163. // If we have an alpha var then we're doing prepass lerp blending.
  164. if ( alphaVal )
  165. {
  166. Var *outColor = (Var*)LangElement::find( getOutputTargetVarName( DefaultTarget ) );
  167. meta->addStatement( new GenOp( " @.ba = float2( 0, @ ); // MFT_IsTranslucentZWrite\r\n", outColor, alphaVal ) );
  168. }
  169. output = meta;
  170. }
  171. ShaderFeature::Resources GBufferConditionerGLSL::getResources( const MaterialFeatureData &fd )
  172. {
  173. Resources res;
  174. // Passing from VS->PS:
  175. // - world space normal (gbNormal)
  176. res.numTexReg = 1;
  177. return res;
  178. }
  179. Var* GBufferConditionerGLSL::printMethodHeader( MethodType methodType, const String &methodName, Stream &stream, MultiLine *meta )
  180. {
  181. const bool isCondition = ( methodType == ConditionerFeature::ConditionMethod );
  182. Var *retVal = NULL;
  183. // The uncondition method inputs are changed
  184. if( isCondition )
  185. retVal = Parent::printMethodHeader( methodType, methodName, stream, meta );
  186. else
  187. {
  188. Var *methodVar = new Var;
  189. methodVar->setName(methodName);
  190. methodVar->setType("float4");
  191. DecOp *methodDecl = new DecOp(methodVar);
  192. Var *prepassSampler = new Var;
  193. prepassSampler->setName("prepassSamplerVar");
  194. prepassSampler->setType("sampler2D");
  195. DecOp *prepassSamplerDecl = new DecOp(prepassSampler);
  196. Var *screenUV = new Var;
  197. screenUV->setName("screenUVVar");
  198. screenUV->setType("float2");
  199. DecOp *screenUVDecl = new DecOp(screenUV);
  200. Var *bufferSample = new Var;
  201. bufferSample->setName("bufferSample");
  202. bufferSample->setType("float4");
  203. DecOp *bufferSampleDecl = new DecOp(bufferSample);
  204. meta->addStatement( new GenOp( "@(@, @)\r\n", methodDecl, prepassSamplerDecl, screenUVDecl ) );
  205. meta->addStatement( new GenOp( "{\r\n" ) );
  206. meta->addStatement( new GenOp( " // Sampler g-buffer\r\n" ) );
  207. #ifdef TORQUE_OS_XENON
  208. meta->addStatement( new GenOp( " @;\r\n", bufferSampleDecl ) );
  209. meta->addStatement( new GenOp( " asm { tfetch2D @, @, @, MagFilter = point, MinFilter = point, MipFilter = point };\r\n", bufferSample, screenUV, prepassSampler ) );
  210. #else
  211. // The gbuffer has no mipmaps, so use tex2dlod when
  212. // possible so that the shader compiler can optimize.
  213. meta->addStatement( new GenOp( " #if TORQUE_SM >= 30\r\n" ) );
  214. meta->addStatement( new GenOp( " @ = tex2Dlod(@, float4(@,0,0));\r\n", bufferSampleDecl, prepassSampler, screenUV ) );
  215. meta->addStatement( new GenOp( " #else\r\n" ) );
  216. meta->addStatement( new GenOp( " @ = tex2D(@, @);\r\n", bufferSampleDecl, prepassSampler, screenUV ) );
  217. meta->addStatement( new GenOp( " #endif\r\n\r\n" ) );
  218. #endif
  219. // We don't use this way of passing var's around, so this should cause a crash
  220. // if something uses this improperly
  221. retVal = bufferSample;
  222. }
  223. return retVal;
  224. }
  225. GenOp* GBufferConditionerGLSL::_posnegEncode( GenOp *val )
  226. {
  227. if(mNormalStorageType == LambertAzimuthal)
  228. return mCanWriteNegativeValues ? val : new GenOp(avar("(%f * (@ + %f))", 1.0f/(M_SQRT2_F * 2.0f), M_SQRT2_F), val);
  229. else
  230. return mCanWriteNegativeValues ? val : new GenOp("(0.5 * (@ + 1.0))", val);
  231. }
  232. GenOp* GBufferConditionerGLSL::_posnegDecode( GenOp *val )
  233. {
  234. if(mNormalStorageType == LambertAzimuthal)
  235. return mCanWriteNegativeValues ? val : new GenOp(avar("(@ * %f - %f)", M_SQRT2_F * 2.0f, M_SQRT2_F), val);
  236. else
  237. return mCanWriteNegativeValues ? val : new GenOp("(@ * 2.0 - 1.0)", val);
  238. }
  239. Var* GBufferConditionerGLSL::_conditionOutput( Var *unconditionedOutput, MultiLine *meta )
  240. {
  241. Var *retVar = new Var;
  242. retVar->setType("float4");
  243. retVar->setName("_gbConditionedOutput");
  244. LangElement *outputDecl = new DecOp( retVar );
  245. switch(mNormalStorageType)
  246. {
  247. case CartesianXYZ:
  248. meta->addStatement( new GenOp( " // g-buffer conditioner: float4(normal.xyz, depth)\r\n" ) );
  249. meta->addStatement( new GenOp( " @ = float4(@, @.a);\r\n", outputDecl,
  250. _posnegEncode(new GenOp("@.xyz", unconditionedOutput)), unconditionedOutput ) );
  251. break;
  252. case CartesianXY:
  253. meta->addStatement( new GenOp( " // g-buffer conditioner: float4(normal.xy, depth Hi + z-sign, depth Lo)\r\n" ) );
  254. meta->addStatement( new GenOp( " @ = float4(@, @.a);", outputDecl,
  255. _posnegEncode(new GenOp("float3(@.xy, sign(@.z))", unconditionedOutput, unconditionedOutput)), unconditionedOutput ) );
  256. break;
  257. case Spherical:
  258. meta->addStatement( new GenOp( " // g-buffer conditioner: float4(normal.theta, normal.phi, depth Hi, depth Lo)\r\n" ) );
  259. meta->addStatement( new GenOp( " @ = float4(@, 0.0, @.a);\r\n", outputDecl,
  260. _posnegEncode(new GenOp("float2(atan2(@.y, @.x) / 3.14159265358979323846f, @.z)", unconditionedOutput, unconditionedOutput, unconditionedOutput ) ),
  261. unconditionedOutput ) );
  262. // HACK: This fixes the noise present when using a floating point
  263. // gbuffer on Geforce cards and the "flat areas unlit" issues.
  264. //
  265. // We need work around atan2() above to fix this issue correctly
  266. // without the extra overhead of this test.
  267. //
  268. 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",
  269. unconditionedOutput, retVar, unconditionedOutput, unconditionedOutput ) );
  270. break;
  271. case LambertAzimuthal:
  272. //http://en.wikipedia.org/wiki/Lambert_azimuthal_equal-area_projection
  273. //
  274. // Note we're casting to half to use partial precision
  275. // sqrt which is much faster on older Geforces while
  276. // still being acceptable for normals.
  277. //
  278. meta->addStatement( new GenOp( " // g-buffer conditioner: float4(normal.X, normal.Y, depth Hi, depth Lo)\r\n" ) );
  279. meta->addStatement( new GenOp( " @ = float4(@, 0.0, @.a);\r\n", outputDecl,
  280. _posnegEncode(new GenOp("sqrt(half(2.0/(1.0 - @.y))) * half2(@.xz)", unconditionedOutput, unconditionedOutput)),
  281. unconditionedOutput ) );
  282. break;
  283. }
  284. // Encode depth into two channels
  285. if(mNormalStorageType != CartesianXYZ)
  286. {
  287. const U64 maxValPerChannel = (U64)1 << mBitsPerChannel;
  288. meta->addStatement( new GenOp( " \r\n // Encode depth into hi/lo\r\n" ) );
  289. meta->addStatement( new GenOp( avar( " float2 _tempDepth = frac(@.a * float2(1.0, %llu.0));\r\n", maxValPerChannel - 1 ),
  290. unconditionedOutput ) );
  291. meta->addStatement( new GenOp( avar( " @.zw = _tempDepth.xy - _tempDepth.yy * float2(1.0/%llu.0, 0.0);\r\n\r\n", maxValPerChannel - 1 ),
  292. retVar ) );
  293. }
  294. AssertFatal( retVar != NULL, avar( "Cannot condition output to buffer format: %s", GFXStringTextureFormat[getBufferFormat()] ) );
  295. return retVar;
  296. }
  297. Var* GBufferConditionerGLSL::_unconditionInput( Var *conditionedInput, MultiLine *meta )
  298. {
  299. Var *retVar = new Var;
  300. retVar->setType("float4");
  301. retVar->setName("_gbUnconditionedInput");
  302. LangElement *outputDecl = new DecOp( retVar );
  303. switch(mNormalStorageType)
  304. {
  305. case CartesianXYZ:
  306. meta->addStatement( new GenOp( " // g-buffer unconditioner: float4(normal.xyz, depth)\r\n" ) );
  307. meta->addStatement( new GenOp( " @ = float4(@, @.a);\r\n", outputDecl,
  308. _posnegDecode(new GenOp("@.xyz", conditionedInput)), conditionedInput ) );
  309. break;
  310. case CartesianXY:
  311. meta->addStatement( new GenOp( " // g-buffer unconditioner: float4(normal.xy, depth Hi + z-sign, depth Lo)\r\n" ) );
  312. meta->addStatement( new GenOp( " @ = float4(@, @.a);\r\n", outputDecl,
  313. _posnegDecode(new GenOp("@.xyz", conditionedInput)), conditionedInput ) );
  314. meta->addStatement( new GenOp( " @.z *= sqrt(1.0 - dot(@.xy, @.xy));\r\n", retVar, retVar, retVar ) );
  315. break;
  316. case Spherical:
  317. meta->addStatement( new GenOp( " // g-buffer unconditioner: float4(normal.theta, normal.phi, depth Hi, depth Lo)\r\n" ) );
  318. meta->addStatement( new GenOp( " float2 spGPUAngles = @;\r\n", _posnegDecode(new GenOp("@.xy", conditionedInput)) ) );
  319. meta->addStatement( new GenOp( " float2 sincosTheta;\r\n" ) );
  320. meta->addStatement( new GenOp( " sincos(spGPUAngles.x * 3.14159265358979323846f, sincosTheta.x, sincosTheta.y);\r\n" ) );
  321. meta->addStatement( new GenOp( " float2 sincosPhi = float2(sqrt(1.0 - spGPUAngles.y * spGPUAngles.y), spGPUAngles.y);\r\n" ) );
  322. meta->addStatement( new GenOp( " @ = float4(sincosTheta.y * sincosPhi.x, sincosTheta.x * sincosPhi.x, sincosPhi.y, @.a);\r\n", outputDecl, conditionedInput ) );
  323. break;
  324. case LambertAzimuthal:
  325. // Note we're casting to half to use partial precision
  326. // sqrt which is much faster on older Geforces while
  327. // still being acceptable for normals.
  328. //
  329. meta->addStatement( new GenOp( " // g-buffer unconditioner: float4(normal.X, normal.Y, depth Hi, depth Lo)\r\n" ) );
  330. meta->addStatement( new GenOp( " float2 _inpXY = @;\r\n", _posnegDecode(new GenOp("@.xy", conditionedInput)) ) );
  331. meta->addStatement( new GenOp( " float _xySQ = dot(_inpXY, _inpXY);\r\n" ) );
  332. meta->addStatement( new GenOp( " @ = float4( sqrt(half(1.0 - (_xySQ / 4.0))) * _inpXY, -1.0 + (_xySQ / 2.0), @.a).xzyw;\r\n", outputDecl, conditionedInput ) );
  333. break;
  334. }
  335. // Recover depth from encoding
  336. if(mNormalStorageType != CartesianXYZ)
  337. {
  338. const U64 maxValPerChannel = (U64)1 << mBitsPerChannel;
  339. meta->addStatement( new GenOp( " \r\n // Decode depth\r\n" ) );
  340. meta->addStatement( new GenOp( avar( " @.w = dot( @.zw, float2(1.0, 1.0/%llu.0));\r\n", maxValPerChannel - 1 ),
  341. retVar, conditionedInput ) );
  342. }
  343. AssertFatal( retVar != NULL, avar( "Cannot uncondition input from buffer format: %s", GFXStringTextureFormat[getBufferFormat()] ) );
  344. return retVar;
  345. }