shaderGen.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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 "shaderGen/shaderGen.h"
  24. #include "shaderGen/conditionerFeature.h"
  25. #include "core/stream/fileStream.h"
  26. #include "shaderGen/featureMgr.h"
  27. #include "shaderGen/shaderOp.h"
  28. #include "gfx/gfxDevice.h"
  29. #include "core/memVolume.h"
  30. #include "core/module.h"
  31. #ifdef TORQUE_D3D11
  32. #include "shaderGen/HLSL/customFeatureHLSL.h"
  33. #endif
  34. #ifdef TORQUE_OPENGL
  35. #include "shaderGen/GLSL/customFeatureGLSL.h"
  36. #endif
  37. MODULE_BEGIN( ShaderGen )
  38. MODULE_INIT_BEFORE( GFX )
  39. MODULE_SHUTDOWN_AFTER( GFX )
  40. MODULE_INIT
  41. {
  42. ManagedSingleton< ShaderGen >::createSingleton();
  43. }
  44. MODULE_SHUTDOWN
  45. {
  46. ManagedSingleton< ShaderGen >::deleteSingleton();
  47. }
  48. MODULE_END;
  49. String ShaderGen::smCommonShaderPath("shaders/common");
  50. ShaderGen::ShaderGen()
  51. {
  52. mInit = false;
  53. GFXDevice::getDeviceEventSignal().notify(this, &ShaderGen::_handleGFXEvent);
  54. mOutput = NULL;
  55. }
  56. ShaderGen::~ShaderGen()
  57. {
  58. GFXDevice::getDeviceEventSignal().remove(this, &ShaderGen::_handleGFXEvent);
  59. _uninit();
  60. }
  61. void ShaderGen::registerInitDelegate(GFXAdapterType adapterType, ShaderGenInitDelegate& initDelegate)
  62. {
  63. mInitDelegates[(U32)adapterType] = initDelegate;
  64. }
  65. bool ShaderGen::_handleGFXEvent(GFXDevice::GFXDeviceEventType event)
  66. {
  67. switch (event)
  68. {
  69. case GFXDevice::deInit :
  70. initShaderGen();
  71. break;
  72. case GFXDevice::deDestroy :
  73. {
  74. flushProceduralShaders();
  75. }
  76. break;
  77. default :
  78. break;
  79. }
  80. return true;
  81. }
  82. void ShaderGen::initShaderGen()
  83. {
  84. if (mInit)
  85. return;
  86. const GFXAdapterType adapterType = GFX->getAdapterType();
  87. if (!mInitDelegates[adapterType])
  88. return;
  89. smCommonShaderPath = String(Con::getVariable("$Core::CommonShaderPath", "shaders/common"));
  90. mInitDelegates[adapterType](this);
  91. mFeatureInitSignal.trigger( adapterType );
  92. mInit = true;
  93. String shaderPath = Con::getVariable( "$shaderGen::cachePath");
  94. if (!shaderPath.equal( "shadergen:" ) && !shaderPath.isEmpty() )
  95. {
  96. // this is necessary, especially under Windows with UAC enabled
  97. if (!Torque::FS::VerifyWriteAccess(shaderPath))
  98. {
  99. // we don't have write access so enable the virtualized memory store
  100. Con::warnf("ShaderGen: Write permission unavailable, switching to virtualized memory storage");
  101. shaderPath.clear();
  102. }
  103. }
  104. if ( shaderPath.equal( "shadergen:" ) || shaderPath.isEmpty() )
  105. {
  106. // If we didn't get a path then we're gonna cache the shaders to
  107. // a virtualized memory file system.
  108. mMemFS = new Torque::Mem::MemFileSystem( "shadergen:/" );
  109. Torque::FS::Mount( "shadergen", mMemFS );
  110. }
  111. else
  112. Torque::FS::Mount( "shadergen", shaderPath + "/" );
  113. // Delete the auto-generated conditioner include file.
  114. Torque::FS::Remove( "shadergen:/" + ConditionerFeature::ConditionerIncludeFileName );
  115. }
  116. void ShaderGen::generateShader( const MaterialFeatureData &featureData,
  117. char *vertFile,
  118. char *pixFile,
  119. F32 *pixVersion,
  120. const GFXVertexFormat *vertexFormat,
  121. const char* cacheName,
  122. Vector<GFXShaderMacro> &macros)
  123. {
  124. PROFILE_SCOPE( ShaderGen_GenerateShader );
  125. mFeatureData = featureData;
  126. mVertexFormat = vertexFormat;
  127. _uninit();
  128. _init();
  129. char vertShaderName[256];
  130. char pixShaderName[256];
  131. // Note: We use a postfix of _V/_P here so that it sorts the matching
  132. // vert and pixel shaders together when listed alphabetically.
  133. dSprintf( vertShaderName, sizeof(vertShaderName), "shadergen:/%s_V.%s", cacheName, mFileEnding.c_str() );
  134. dSprintf( pixShaderName, sizeof(pixShaderName), "shadergen:/%s_P.%s", cacheName, mFileEnding.c_str() );
  135. dStrcpy( vertFile, vertShaderName, 256 );
  136. dStrcpy( pixFile, pixShaderName, 256 );
  137. // this needs to change - need to optimize down to ps v.1.1
  138. *pixVersion = GFX->getPixelShaderVersion();
  139. if ( !Con::getBoolVariable( "ShaderGen::GenNewShaders", true ) )
  140. {
  141. // If we are not regenerating the shader we will return here.
  142. // But we must fill in the shader macros first!
  143. _processVertFeatures( macros, true );
  144. _processPixFeatures( macros, true );
  145. return;
  146. }
  147. // create vertex shader
  148. //------------------------
  149. FileStream* s = new FileStream();
  150. if(!s->open(vertShaderName, Torque::FS::File::Write ))
  151. {
  152. AssertFatal(false, "Failed to open Shader Stream" );
  153. return;
  154. }
  155. mOutput = new MultiLine;
  156. mInstancingFormat.clear();
  157. _processVertFeatures(macros);
  158. _printVertShader( *s );
  159. delete s;
  160. ((ShaderConnector*)mComponents[C_CONNECTOR])->reset();
  161. LangElement::deleteElements();
  162. // create pixel shader
  163. //------------------------
  164. s = new FileStream();
  165. if(!s->open(pixShaderName, Torque::FS::File::Write ))
  166. {
  167. AssertFatal(false, "Failed to open Shader Stream" );
  168. return;
  169. }
  170. mOutput = new MultiLine;
  171. _processPixFeatures(macros);
  172. _printPixShader( *s );
  173. delete s;
  174. LangElement::deleteElements();
  175. }
  176. void ShaderGen::_init()
  177. {
  178. _createComponents();
  179. }
  180. void ShaderGen::_uninit()
  181. {
  182. for( U32 i=0; i<mComponents.size(); i++ )
  183. {
  184. delete mComponents[i];
  185. mComponents[i] = NULL;
  186. }
  187. mComponents.setSize(0);
  188. LangElement::deleteElements();
  189. Var::reset();
  190. }
  191. void ShaderGen::_createComponents()
  192. {
  193. ShaderComponent* vertComp = mComponentFactory->createVertexInputConnector( *mVertexFormat );
  194. mComponents.push_back(vertComp);
  195. ShaderComponent* vertPixelCon = mComponentFactory->createVertexPixelConnector();
  196. mComponents.push_back(vertPixelCon);
  197. ShaderComponent* vertParamDef = mComponentFactory->createVertexParamsDef();
  198. mComponents.push_back(vertParamDef);
  199. ShaderComponent* pixParamDef = mComponentFactory->createPixelParamsDef();
  200. mComponents.push_back(pixParamDef);
  201. }
  202. //----------------------------------------------------------------------------
  203. // Process features
  204. //----------------------------------------------------------------------------
  205. void ShaderGen::_processVertFeatures( Vector<GFXShaderMacro> &macros, bool macrosOnly )
  206. {
  207. const FeatureSet &features = mFeatureData.features;
  208. for( U32 i=0; i < features.getCount(); i++ )
  209. {
  210. S32 index;
  211. const FeatureType &type = features.getAt( i, &index );
  212. ShaderFeature* feature = FEATUREMGR->getByType( type );
  213. if ( feature )
  214. {
  215. feature->setProcessIndex( index );
  216. feature->processVertMacros( macros, mFeatureData );
  217. if ( macrosOnly )
  218. continue;
  219. feature->setInstancingFormat( &mInstancingFormat );
  220. feature->mVertexFormat = mVertexFormat;
  221. feature->processVert( mComponents, mFeatureData );
  222. String line;
  223. if ( index > -1 )
  224. line = String::ToString( " // %s %d\r\n", feature->getName().c_str(), index );
  225. else
  226. line = String::ToString( " // %s\r\n", feature->getName().c_str() );
  227. mOutput->addStatement( new GenOp( line ) );
  228. if ( feature->getOutput() )
  229. mOutput->addStatement( feature->getOutput() );
  230. feature->reset();
  231. mOutput->addStatement( new GenOp( " \r\n" ) );
  232. }
  233. }
  234. ShaderConnector *connect = dynamic_cast<ShaderConnector *>( mComponents[C_CONNECTOR] );
  235. connect->sortVars();
  236. }
  237. void ShaderGen::_processPixFeatures( Vector<GFXShaderMacro> &macros, bool macrosOnly )
  238. {
  239. const FeatureSet &features = mFeatureData.features;
  240. for( U32 i=0; i < features.getCount(); i++ )
  241. {
  242. S32 index;
  243. const FeatureType &type = features.getAt( i, &index );
  244. ShaderFeature* feature = FEATUREMGR->getByType( type );
  245. if ( feature )
  246. {
  247. feature->setProcessIndex( index );
  248. feature->processPixMacros( macros, mFeatureData );
  249. if ( macrosOnly )
  250. continue;
  251. feature->setInstancingFormat( &mInstancingFormat );
  252. feature->processPix( mComponents, mFeatureData );
  253. String line;
  254. if ( index > -1 )
  255. line = String::ToString( " // %s %d\r\n", feature->getName().c_str(), index );
  256. else
  257. line = String::ToString( " // %s\r\n", feature->getName().c_str() );
  258. mOutput->addStatement( new GenOp( line ) );
  259. if ( feature->getOutput() )
  260. mOutput->addStatement( feature->getOutput() );
  261. feature->reset();
  262. mOutput->addStatement( new GenOp( " \r\n" ) );
  263. }
  264. }
  265. ShaderConnector *connect = dynamic_cast<ShaderConnector *>( mComponents[C_CONNECTOR] );
  266. connect->sortVars();
  267. }
  268. void ShaderGen::_printFeatureList(Stream &stream)
  269. {
  270. mPrinter->printLine(stream, "// Features:");
  271. const FeatureSet &features = mFeatureData.features;
  272. for( U32 i=0; i < features.getCount(); i++ )
  273. {
  274. S32 index;
  275. const FeatureType &type = features.getAt( i, &index );
  276. ShaderFeature* feature = FEATUREMGR->getByType( type );
  277. if ( feature )
  278. {
  279. String line;
  280. if ( index > -1 )
  281. line = String::ToString( "// %s %d", feature->getName().c_str(), index );
  282. else
  283. line = String::ToString( "// %s", feature->getName().c_str() );
  284. mPrinter->printLine( stream, line );
  285. }
  286. }
  287. mPrinter->printLine(stream, "");
  288. }
  289. void ShaderGen::_printDependencies(Stream &stream)
  290. {
  291. Vector<const ShaderDependency *> dependencies;
  292. for( U32 i=0; i < FEATUREMGR->getFeatureCount(); i++ )
  293. {
  294. const FeatureInfo &info = FEATUREMGR->getAt( i );
  295. if ( mFeatureData.features.hasFeature( *info.type ) )
  296. dependencies.merge( info.feature->getDependencies() );
  297. }
  298. // Do a quick loop removing any duplicate dependancies.
  299. for( U32 i=0; i < dependencies.size(); )
  300. {
  301. bool dup = false;
  302. for( U32 j=0; j < dependencies.size(); j++ )
  303. {
  304. if ( j != i &&
  305. *dependencies[i] == *dependencies[j] )
  306. {
  307. dup = true;
  308. break;
  309. }
  310. }
  311. if ( dup )
  312. dependencies.erase( i );
  313. else
  314. i++;
  315. }
  316. // Print dependencies
  317. if( dependencies.size() > 0 )
  318. {
  319. mPrinter->printLine(stream, "// Dependencies:");
  320. for( S32 i = 0; i < dependencies.size(); i++ )
  321. dependencies[i]->print( stream );
  322. mPrinter->printLine(stream, "");
  323. }
  324. }
  325. void ShaderGen::_printFeatures( Stream &stream )
  326. {
  327. mOutput->print( stream );
  328. }
  329. void ShaderGen::_printVertShader( Stream &stream )
  330. {
  331. mPrinter->printShaderHeader(stream);
  332. _printDependencies(stream); // TODO: Split into vert and pix dependencies?
  333. _printFeatureList(stream);
  334. // print out structures
  335. mComponents[C_VERT_STRUCT]->print( stream, true );
  336. mComponents[C_CONNECTOR]->print( stream, true );
  337. mPrinter->printMainComment(stream);
  338. mComponents[C_VERT_MAIN]->print( stream, true );
  339. mComponents[C_VERT_STRUCT]->printOnMain( stream, true );
  340. // print out the function
  341. _printFeatures( stream );
  342. mPrinter->printVertexShaderCloser(stream);
  343. }
  344. void ShaderGen::_printPixShader( Stream &stream )
  345. {
  346. mPrinter->printShaderHeader(stream);
  347. _printDependencies(stream); // TODO: Split into vert and pix dependencies?
  348. _printFeatureList(stream);
  349. mComponents[C_CONNECTOR]->print( stream, false );
  350. mPrinter->printPixelShaderOutputStruct(stream, mFeatureData);
  351. mPrinter->printMainComment(stream);
  352. mComponents[C_PIX_MAIN]->print( stream, false );
  353. mComponents[C_CONNECTOR]->printOnMain( stream, false );
  354. // print out the function
  355. _printFeatures( stream );
  356. mPrinter->printPixelShaderCloser(stream);
  357. }
  358. GFXShader* ShaderGen::getShader( const MaterialFeatureData &featureData, const GFXVertexFormat *vertexFormat, const Vector<GFXShaderMacro> *macros, const Vector<String> &samplers )
  359. {
  360. PROFILE_SCOPE( ShaderGen_GetShader );
  361. const FeatureSet &features = featureData.codify();
  362. // Build a description string from the features
  363. // and vertex format combination ( and macros ).
  364. String shaderDescription = vertexFormat->getDescription() + features.getDescription();
  365. if ( macros && !macros->empty() )
  366. {
  367. String macroStr;
  368. GFXShaderMacro::stringize( *macros, &macroStr );
  369. shaderDescription += macroStr;
  370. }
  371. // Generate a single 64bit hash from the description string.
  372. //
  373. // Don't get paranoid! This has 1 in 18446744073709551616
  374. // chance for collision... it won't happen in this lifetime.
  375. //
  376. U64 hash = Torque::hash64( (const U8*)shaderDescription.c_str(), shaderDescription.length(), 0 );
  377. hash = convertHostToLEndian(hash);
  378. U32 high = (U32)( hash >> 32 );
  379. U32 low = (U32)( hash & 0x00000000FFFFFFFF );
  380. String cacheKey = String::ToString( "%x%x", high, low );
  381. // return shader if exists
  382. GFXShader *match = mProcShaders[cacheKey];
  383. if ( match )
  384. return match;
  385. // if not, then create it
  386. char vertFile[256];
  387. char pixFile[256];
  388. F32 pixVersion;
  389. Vector<GFXShaderMacro> shaderMacros;
  390. shaderMacros.push_back( GFXShaderMacro( "TORQUE_SHADERGEN" ) );
  391. if ( macros )
  392. shaderMacros.merge( *macros );
  393. generateShader( featureData, vertFile, pixFile, &pixVersion, vertexFormat, cacheKey, shaderMacros );
  394. GFXShader *shader = GFX->createShader();
  395. if (!shader->init(vertFile, pixFile, pixVersion, shaderMacros, samplers, &mInstancingFormat))
  396. {
  397. delete shader;
  398. return NULL;
  399. }
  400. mProcShaders[cacheKey] = shader;
  401. return shader;
  402. }
  403. void ShaderGen::flushProceduralShaders()
  404. {
  405. // The shaders are reference counted, so we
  406. // just need to clear the map.
  407. mProcShaders.clear();
  408. }