shaderGen.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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->setInstancingFormat( &mInstancingFormat );
  218. feature->mVertexFormat = mVertexFormat;
  219. feature->processVert( mComponents, mFeatureData );
  220. String line;
  221. if ( index > -1 )
  222. line = String::ToString( " // %s %d\r\n", feature->getName().c_str(), index );
  223. else
  224. line = String::ToString( " // %s\r\n", feature->getName().c_str() );
  225. mOutput->addStatement( new GenOp( line ) );
  226. if ( feature->getOutput() )
  227. mOutput->addStatement( feature->getOutput() );
  228. feature->reset();
  229. mOutput->addStatement( new GenOp( " \r\n" ) );
  230. }
  231. }
  232. ShaderConnector *connect = dynamic_cast<ShaderConnector *>( mComponents[C_CONNECTOR] );
  233. connect->sortVars();
  234. }
  235. void ShaderGen::_processPixFeatures( Vector<GFXShaderMacro> &macros, bool macrosOnly )
  236. {
  237. const FeatureSet &features = mFeatureData.features;
  238. for( U32 i=0; i < features.getCount(); i++ )
  239. {
  240. S32 index;
  241. const FeatureType &type = features.getAt( i, &index );
  242. ShaderFeature* feature = FEATUREMGR->getByType( type );
  243. if ( feature )
  244. {
  245. feature->setProcessIndex( index );
  246. feature->processPixMacros( macros, mFeatureData );
  247. if ( macrosOnly )
  248. continue;
  249. feature->setInstancingFormat( &mInstancingFormat );
  250. feature->processPix( mComponents, mFeatureData );
  251. String line;
  252. if ( index > -1 )
  253. line = String::ToString( " // %s %d\r\n", feature->getName().c_str(), index );
  254. else
  255. line = String::ToString( " // %s\r\n", feature->getName().c_str() );
  256. mOutput->addStatement( new GenOp( line ) );
  257. if ( feature->getOutput() )
  258. mOutput->addStatement( feature->getOutput() );
  259. feature->reset();
  260. mOutput->addStatement( new GenOp( " \r\n" ) );
  261. }
  262. }
  263. ShaderConnector *connect = dynamic_cast<ShaderConnector *>( mComponents[C_CONNECTOR] );
  264. connect->sortVars();
  265. }
  266. void ShaderGen::_printFeatureList(Stream &stream)
  267. {
  268. mPrinter->printLine(stream, "// Features:");
  269. const FeatureSet &features = mFeatureData.features;
  270. for( U32 i=0; i < features.getCount(); i++ )
  271. {
  272. S32 index;
  273. const FeatureType &type = features.getAt( i, &index );
  274. ShaderFeature* feature = FEATUREMGR->getByType( type );
  275. if ( feature )
  276. {
  277. String line;
  278. if ( index > -1 )
  279. line = String::ToString( "// %s %d", feature->getName().c_str(), index );
  280. else
  281. line = String::ToString( "// %s", feature->getName().c_str() );
  282. mPrinter->printLine( stream, line );
  283. }
  284. }
  285. mPrinter->printLine(stream, "");
  286. }
  287. void ShaderGen::_printDependencies(Stream &stream)
  288. {
  289. Vector<const ShaderDependency *> dependencies;
  290. for( U32 i=0; i < FEATUREMGR->getFeatureCount(); i++ )
  291. {
  292. const FeatureInfo &info = FEATUREMGR->getAt( i );
  293. if ( mFeatureData.features.hasFeature( *info.type ) )
  294. dependencies.merge( info.feature->getDependencies() );
  295. }
  296. // Do a quick loop removing any duplicate dependancies.
  297. for( U32 i=0; i < dependencies.size(); )
  298. {
  299. bool dup = false;
  300. for( U32 j=0; j < dependencies.size(); j++ )
  301. {
  302. if ( j != i &&
  303. *dependencies[i] == *dependencies[j] )
  304. {
  305. dup = true;
  306. break;
  307. }
  308. }
  309. if ( dup )
  310. dependencies.erase( i );
  311. else
  312. i++;
  313. }
  314. // Print dependencies
  315. if( dependencies.size() > 0 )
  316. {
  317. mPrinter->printLine(stream, "// Dependencies:");
  318. for( S32 i = 0; i < dependencies.size(); i++ )
  319. dependencies[i]->print( stream );
  320. mPrinter->printLine(stream, "");
  321. }
  322. }
  323. void ShaderGen::_printFeatures( Stream &stream )
  324. {
  325. mOutput->print( stream );
  326. }
  327. void ShaderGen::_printVertShader( Stream &stream )
  328. {
  329. mPrinter->printShaderHeader(stream);
  330. _printDependencies(stream); // TODO: Split into vert and pix dependencies?
  331. _printFeatureList(stream);
  332. // print out structures
  333. mComponents[C_VERT_STRUCT]->print( stream, true );
  334. mComponents[C_CONNECTOR]->print( stream, true );
  335. mPrinter->printMainComment(stream);
  336. mComponents[C_VERT_MAIN]->print( stream, true );
  337. mComponents[C_VERT_STRUCT]->printOnMain( stream, true );
  338. // print out the function
  339. _printFeatures( stream );
  340. mPrinter->printVertexShaderCloser(stream);
  341. }
  342. void ShaderGen::_printPixShader( Stream &stream )
  343. {
  344. mPrinter->printShaderHeader(stream);
  345. _printDependencies(stream); // TODO: Split into vert and pix dependencies?
  346. _printFeatureList(stream);
  347. mComponents[C_CONNECTOR]->print( stream, false );
  348. mPrinter->printPixelShaderOutputStruct(stream, mFeatureData);
  349. mPrinter->printMainComment(stream);
  350. mComponents[C_PIX_MAIN]->print( stream, false );
  351. mComponents[C_CONNECTOR]->printOnMain( stream, false );
  352. // print out the function
  353. _printFeatures( stream );
  354. mPrinter->printPixelShaderCloser(stream);
  355. }
  356. GFXShader* ShaderGen::getShader( const MaterialFeatureData &featureData, const GFXVertexFormat *vertexFormat, const Vector<GFXShaderMacro> *macros, const Vector<String> &samplers )
  357. {
  358. PROFILE_SCOPE( ShaderGen_GetShader );
  359. const FeatureSet &features = featureData.codify();
  360. // Build a description string from the features
  361. // and vertex format combination ( and macros ).
  362. String shaderDescription = vertexFormat->getDescription() + features.getDescription();
  363. if ( macros && !macros->empty() )
  364. {
  365. String macroStr;
  366. GFXShaderMacro::stringize( *macros, &macroStr );
  367. shaderDescription += macroStr;
  368. }
  369. // Generate a single 64bit hash from the description string.
  370. //
  371. // Don't get paranoid! This has 1 in 18446744073709551616
  372. // chance for collision... it won't happen in this lifetime.
  373. //
  374. U64 hash = Torque::hash64( (const U8*)shaderDescription.c_str(), shaderDescription.length(), 0 );
  375. hash = convertHostToLEndian(hash);
  376. U32 high = (U32)( hash >> 32 );
  377. U32 low = (U32)( hash & 0x00000000FFFFFFFF );
  378. String cacheKey = String::ToString( "%x%x", high, low );
  379. // return shader if exists
  380. GFXShader *match = mProcShaders[cacheKey];
  381. if ( match )
  382. return match;
  383. // if not, then create it
  384. char vertFile[256];
  385. char pixFile[256];
  386. F32 pixVersion;
  387. Vector<GFXShaderMacro> shaderMacros;
  388. shaderMacros.push_back( GFXShaderMacro( "TORQUE_SHADERGEN" ) );
  389. if ( macros )
  390. shaderMacros.merge( *macros );
  391. generateShader( featureData, vertFile, pixFile, &pixVersion, vertexFormat, cacheKey, shaderMacros );
  392. GFXShader *shader = GFX->createShader();
  393. if (!shader->init(vertFile, pixFile, pixVersion, shaderMacros, samplers, &mInstancingFormat))
  394. {
  395. delete shader;
  396. return NULL;
  397. }
  398. mProcShaders[cacheKey] = shader;
  399. return shader;
  400. }
  401. void ShaderGen::flushProceduralShaders()
  402. {
  403. // The shaders are reference counted, so we
  404. // just need to clear the map.
  405. mProcShaders.clear();
  406. }