shaderGen.cpp 14 KB

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