shaderGen.cpp 18 KB

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