shaderGen.cpp 15 KB

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