shaderGen.cpp 15 KB

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