shaderGen.cpp 15 KB

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