shaderGen.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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. #include "shaderGen/HLSL/customFeatureHLSL.h"
  32. #include "shaderGen/GLSL/customFeatureGLSL.h"
  33. MODULE_BEGIN( ShaderGen )
  34. MODULE_INIT_BEFORE( GFX )
  35. MODULE_SHUTDOWN_AFTER( GFX )
  36. MODULE_INIT
  37. {
  38. ManagedSingleton< ShaderGen >::createSingleton();
  39. }
  40. MODULE_SHUTDOWN
  41. {
  42. ManagedSingleton< ShaderGen >::deleteSingleton();
  43. }
  44. MODULE_END;
  45. String ShaderGen::smCommonShaderPath("shaders/common");
  46. ShaderGen::ShaderGen()
  47. {
  48. mInit = false;
  49. GFXDevice::getDeviceEventSignal().notify(this, &ShaderGen::_handleGFXEvent);
  50. mOutput = NULL;
  51. }
  52. ShaderGen::~ShaderGen()
  53. {
  54. GFXDevice::getDeviceEventSignal().remove(this, &ShaderGen::_handleGFXEvent);
  55. _uninit();
  56. }
  57. void ShaderGen::registerInitDelegate(GFXAdapterType adapterType, ShaderGenInitDelegate& initDelegate)
  58. {
  59. mInitDelegates[(U32)adapterType] = initDelegate;
  60. }
  61. bool ShaderGen::_handleGFXEvent(GFXDevice::GFXDeviceEventType event)
  62. {
  63. switch (event)
  64. {
  65. case GFXDevice::deInit :
  66. initShaderGen();
  67. break;
  68. case GFXDevice::deDestroy :
  69. {
  70. flushProceduralShaders();
  71. }
  72. break;
  73. default :
  74. break;
  75. }
  76. return true;
  77. }
  78. void ShaderGen::initShaderGen()
  79. {
  80. if (mInit)
  81. return;
  82. const GFXAdapterType adapterType = GFX->getAdapterType();
  83. if (!mInitDelegates[adapterType])
  84. return;
  85. smCommonShaderPath = String(Con::getVariable("$Core::CommonShaderPath", "shaders/common"));
  86. mInitDelegates[adapterType](this);
  87. mFeatureInitSignal.trigger( adapterType );
  88. mInit = true;
  89. String shaderPath = Con::getVariable( "$shaderGen::cachePath");
  90. if (!shaderPath.equal( "shadergen:" ) && !shaderPath.isEmpty() )
  91. {
  92. // this is necessary, especially under Windows with UAC enabled
  93. if (!Torque::FS::VerifyWriteAccess(shaderPath))
  94. {
  95. // we don't have write access so enable the virtualized memory store
  96. Con::warnf("ShaderGen: Write permission unavailable, switching to virtualized memory storage");
  97. shaderPath.clear();
  98. }
  99. }
  100. if ( shaderPath.equal( "shadergen:" ) || shaderPath.isEmpty() )
  101. {
  102. // If we didn't get a path then we're gonna cache the shaders to
  103. // a virtualized memory file system.
  104. mMemFS = new Torque::Mem::MemFileSystem( "shadergen:/" );
  105. Torque::FS::Mount( "shadergen", mMemFS );
  106. }
  107. else
  108. Torque::FS::Mount( "shadergen", shaderPath + "/" );
  109. // Delete the auto-generated conditioner include file.
  110. Torque::FS::Remove( "shadergen:/" + ConditionerFeature::ConditionerIncludeFileName );
  111. }
  112. void ShaderGen::generateShader( const MaterialFeatureData &featureData,
  113. char *vertFile,
  114. char *pixFile,
  115. F32 *pixVersion,
  116. const GFXVertexFormat *vertexFormat,
  117. const char* cacheName,
  118. Vector<GFXShaderMacro> &macros,
  119. Vector<CustomShaderFeatureData*> &customFeatureData)
  120. {
  121. PROFILE_SCOPE( ShaderGen_GenerateShader );
  122. mFeatureData = featureData;
  123. mVertexFormat = vertexFormat;
  124. mCustomFeaturesData = customFeatureData;
  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, 256 );
  134. dStrcpy( pixFile, pixShaderName, 256 );
  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. //Handle if we have any custom features
  233. if (!mCustomFeaturesData.empty())
  234. {
  235. for (U32 i = 0; i < mCustomFeaturesData.size(); ++i)
  236. {
  237. if (GFX->getAdapterType() == GFXAdapterType::Direct3D11)
  238. {
  239. mCustomFeaturesData[i]->mFeatureHLSL->processVert(mComponents, mFeatureData);
  240. String line = String::ToString(" // %s\r\n", mCustomFeaturesData[i]->mFeatureHLSL->getName().c_str());
  241. mOutput->addStatement(new GenOp(line));
  242. if (mCustomFeaturesData[i]->mFeatureHLSL->getOutput())
  243. mOutput->addStatement(mCustomFeaturesData[i]->mFeatureHLSL->getOutput());
  244. mCustomFeaturesData[i]->mFeatureHLSL->reset();
  245. mOutput->addStatement(new GenOp(" \r\n"));
  246. }
  247. else if (GFX->getAdapterType() == GFXAdapterType::OpenGL)
  248. {
  249. mCustomFeaturesData[i]->mFeatureGLSL->processVert(mComponents, mFeatureData);
  250. String line = String::ToString(" // %s\r\n", mCustomFeaturesData[i]->mFeatureGLSL->getName().c_str());
  251. mOutput->addStatement(new GenOp(line));
  252. if (mCustomFeaturesData[i]->mFeatureGLSL->getOutput())
  253. mOutput->addStatement(mCustomFeaturesData[i]->mFeatureGLSL->getOutput());
  254. mCustomFeaturesData[i]->mFeatureGLSL->reset();
  255. mOutput->addStatement(new GenOp(" \r\n"));
  256. }
  257. }
  258. }
  259. ShaderConnector *connect = dynamic_cast<ShaderConnector *>( mComponents[C_CONNECTOR] );
  260. connect->sortVars();
  261. }
  262. void ShaderGen::_processPixFeatures( Vector<GFXShaderMacro> &macros, bool macrosOnly )
  263. {
  264. const FeatureSet &features = mFeatureData.features;
  265. for( U32 i=0; i < features.getCount(); i++ )
  266. {
  267. S32 index;
  268. const FeatureType &type = features.getAt( i, &index );
  269. ShaderFeature* feature = FEATUREMGR->getByType( type );
  270. if ( feature )
  271. {
  272. feature->setProcessIndex( index );
  273. feature->processPixMacros( macros, mFeatureData );
  274. if ( macrosOnly )
  275. continue;
  276. feature->setInstancingFormat( &mInstancingFormat );
  277. feature->processPix( mComponents, mFeatureData );
  278. String line;
  279. if ( index > -1 )
  280. line = String::ToString( " // %s %d\r\n", feature->getName().c_str(), index );
  281. else
  282. line = String::ToString( " // %s\r\n", feature->getName().c_str() );
  283. mOutput->addStatement( new GenOp( line ) );
  284. if ( feature->getOutput() )
  285. mOutput->addStatement( feature->getOutput() );
  286. feature->reset();
  287. mOutput->addStatement( new GenOp( " \r\n" ) );
  288. }
  289. }
  290. //Handle if we have any custom features
  291. if (!mCustomFeaturesData.empty())
  292. {
  293. for (U32 i = 0; i < mCustomFeaturesData.size(); ++i)
  294. {
  295. if (GFX->getAdapterType() == GFXAdapterType::Direct3D11)
  296. {
  297. mCustomFeaturesData[i]->mFeatureHLSL->processPix(mComponents, mFeatureData);
  298. String line = String::ToString(" // %s\r\n", mCustomFeaturesData[i]->mFeatureHLSL->getName().c_str());
  299. mOutput->addStatement(new GenOp(line));
  300. if (mCustomFeaturesData[i]->mFeatureHLSL->getOutput())
  301. mOutput->addStatement(mCustomFeaturesData[i]->mFeatureHLSL->getOutput());
  302. mCustomFeaturesData[i]->mFeatureHLSL->reset();
  303. mOutput->addStatement(new GenOp(" \r\n"));
  304. }
  305. else if (GFX->getAdapterType() == GFXAdapterType::OpenGL)
  306. {
  307. mCustomFeaturesData[i]->mFeatureGLSL->processPix(mComponents, mFeatureData);
  308. String line = String::ToString(" // %s\r\n", mCustomFeaturesData[i]->mFeatureGLSL->getName().c_str());
  309. mOutput->addStatement(new GenOp(line));
  310. if (mCustomFeaturesData[i]->mFeatureGLSL->getOutput())
  311. mOutput->addStatement(mCustomFeaturesData[i]->mFeatureGLSL->getOutput());
  312. mCustomFeaturesData[i]->mFeatureGLSL->reset();
  313. mOutput->addStatement(new GenOp(" \r\n"));
  314. }
  315. }
  316. }
  317. ShaderConnector *connect = dynamic_cast<ShaderConnector *>( mComponents[C_CONNECTOR] );
  318. connect->sortVars();
  319. }
  320. void ShaderGen::_printFeatureList(Stream &stream)
  321. {
  322. mPrinter->printLine(stream, "// Features:");
  323. const FeatureSet &features = mFeatureData.features;
  324. for( U32 i=0; i < features.getCount(); i++ )
  325. {
  326. S32 index;
  327. const FeatureType &type = features.getAt( i, &index );
  328. ShaderFeature* feature = FEATUREMGR->getByType( type );
  329. if ( feature )
  330. {
  331. String line;
  332. if ( index > -1 )
  333. line = String::ToString( "// %s %d", feature->getName().c_str(), index );
  334. else
  335. line = String::ToString( "// %s", feature->getName().c_str() );
  336. mPrinter->printLine( stream, line );
  337. }
  338. }
  339. mPrinter->printLine(stream, "");
  340. }
  341. void ShaderGen::_printDependencies(Stream &stream)
  342. {
  343. Vector<const ShaderDependency *> dependencies;
  344. for( U32 i=0; i < FEATUREMGR->getFeatureCount(); i++ )
  345. {
  346. const FeatureInfo &info = FEATUREMGR->getAt( i );
  347. if ( mFeatureData.features.hasFeature( *info.type ) )
  348. dependencies.merge( info.feature->getDependencies() );
  349. }
  350. // Do a quick loop removing any duplicate dependancies.
  351. for( U32 i=0; i < dependencies.size(); )
  352. {
  353. bool dup = false;
  354. for( U32 j=0; j < dependencies.size(); j++ )
  355. {
  356. if ( j != i &&
  357. *dependencies[i] == *dependencies[j] )
  358. {
  359. dup = true;
  360. break;
  361. }
  362. }
  363. if ( dup )
  364. dependencies.erase( i );
  365. else
  366. i++;
  367. }
  368. // Print dependencies
  369. if( dependencies.size() > 0 )
  370. {
  371. mPrinter->printLine(stream, "// Dependencies:");
  372. for( S32 i = 0; i < dependencies.size(); i++ )
  373. dependencies[i]->print( stream );
  374. mPrinter->printLine(stream, "");
  375. }
  376. }
  377. void ShaderGen::_printFeatures( Stream &stream )
  378. {
  379. mOutput->print( stream );
  380. }
  381. void ShaderGen::_printVertShader( Stream &stream )
  382. {
  383. mPrinter->printShaderHeader(stream);
  384. _printDependencies(stream); // TODO: Split into vert and pix dependencies?
  385. _printFeatureList(stream);
  386. // print out structures
  387. mComponents[C_VERT_STRUCT]->print( stream, true );
  388. mComponents[C_CONNECTOR]->print( stream, true );
  389. mPrinter->printMainComment(stream);
  390. mComponents[C_VERT_MAIN]->print( stream, true );
  391. mComponents[C_VERT_STRUCT]->printOnMain( stream, true );
  392. // print out the function
  393. _printFeatures( stream );
  394. mPrinter->printVertexShaderCloser(stream);
  395. }
  396. void ShaderGen::_printPixShader( Stream &stream )
  397. {
  398. mPrinter->printShaderHeader(stream);
  399. _printDependencies(stream); // TODO: Split into vert and pix dependencies?
  400. _printFeatureList(stream);
  401. mComponents[C_CONNECTOR]->print( stream, false );
  402. mPrinter->printPixelShaderOutputStruct(stream, mFeatureData);
  403. mPrinter->printMainComment(stream);
  404. mComponents[C_PIX_MAIN]->print( stream, false );
  405. mComponents[C_CONNECTOR]->printOnMain( stream, false );
  406. // print out the function
  407. _printFeatures( stream );
  408. mPrinter->printPixelShaderCloser(stream);
  409. }
  410. GFXShader* ShaderGen::getShader( const MaterialFeatureData &featureData, Vector<CustomShaderFeatureData*> &customFeatureData, const GFXVertexFormat *vertexFormat, const Vector<GFXShaderMacro> *macros, const Vector<String> &samplers )
  411. {
  412. PROFILE_SCOPE( ShaderGen_GetShader );
  413. const FeatureSet &features = featureData.codify();
  414. // Build a description string from the features
  415. // and vertex format combination ( and macros ).
  416. String shaderDescription = vertexFormat->getDescription() + features.getDescription();
  417. if ( macros && !macros->empty() )
  418. {
  419. String macroStr;
  420. GFXShaderMacro::stringize( *macros, &macroStr );
  421. shaderDescription += macroStr;
  422. }
  423. // Generate a single 64bit hash from the description string.
  424. //
  425. // Don't get paranoid! This has 1 in 18446744073709551616
  426. // chance for collision... it won't happen in this lifetime.
  427. //
  428. U64 hash = Torque::hash64( (const U8*)shaderDescription.c_str(), shaderDescription.length(), 0 );
  429. hash = convertHostToLEndian(hash);
  430. U32 high = (U32)( hash >> 32 );
  431. U32 low = (U32)( hash & 0x00000000FFFFFFFF );
  432. String cacheKey = String::ToString( "%x%x", high, low );
  433. // return shader if exists
  434. GFXShader *match = mProcShaders[cacheKey];
  435. if ( match )
  436. return match;
  437. // if not, then create it
  438. char vertFile[256];
  439. char pixFile[256];
  440. F32 pixVersion;
  441. Vector<GFXShaderMacro> shaderMacros;
  442. shaderMacros.push_back( GFXShaderMacro( "TORQUE_SHADERGEN" ) );
  443. if ( macros )
  444. shaderMacros.merge( *macros );
  445. generateShader( featureData, vertFile, pixFile, &pixVersion, vertexFormat, cacheKey, shaderMacros, customFeatureData );
  446. GFXShader *shader = GFX->createShader();
  447. if (!shader->init(vertFile, pixFile, pixVersion, shaderMacros, samplers, &mInstancingFormat))
  448. {
  449. delete shader;
  450. return NULL;
  451. }
  452. mProcShaders[cacheKey] = shader;
  453. return shader;
  454. }
  455. void ShaderGen::flushProceduralShaders()
  456. {
  457. // The shaders are reference counted, so we
  458. // just need to clear the map.
  459. mProcShaders.clear();
  460. }