ShaderCompiler.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  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 deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // 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 FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Context.h"
  23. #include "File.h"
  24. #include "FileSystem.h"
  25. #include "GraphicsDefs.h"
  26. #include "List.h"
  27. #include "Mutex.h"
  28. #include "ProcessUtils.h"
  29. #include "ShaderParser.h"
  30. #include "StringUtils.h"
  31. #include "Thread.h"
  32. #include "XMLFile.h"
  33. #include <cstdio>
  34. #include <cstring>
  35. #include <windows.h>
  36. #include <d3dcompiler.h>
  37. #include <mojoshader.h>
  38. #include "DebugNew.h"
  39. using namespace Urho3D;
  40. struct Parameter
  41. {
  42. Parameter()
  43. {
  44. }
  45. Parameter(const String& name, unsigned reg, unsigned regCount) :
  46. name_(name),
  47. register_(reg),
  48. regCount_(regCount)
  49. {
  50. }
  51. bool operator < (const Parameter& rhs) const
  52. {
  53. if (register_ != rhs.register_)
  54. return register_ < rhs.register_;
  55. else if (name_ != rhs.name_)
  56. return name_ < rhs.name_;
  57. else
  58. return regCount_ < rhs.regCount_;
  59. }
  60. bool operator > (const Parameter& rhs) const
  61. {
  62. if (register_ != rhs.register_)
  63. return register_ > rhs.register_;
  64. else if (name_ != rhs.name_)
  65. return name_ > rhs.name_;
  66. else
  67. return regCount_ > rhs.regCount_;
  68. }
  69. bool operator == (const Parameter& rhs) const { return register_ == rhs.register_ && name_ == rhs.name_ && regCount_ == rhs.regCount_; }
  70. bool operator != (const Parameter& rhs) const { return register_ != rhs.register_ || name_ != rhs.name_ || regCount_ != rhs.regCount_; }
  71. String name_;
  72. unsigned register_;
  73. unsigned regCount_;
  74. };
  75. struct CompiledVariation
  76. {
  77. ShaderType type_;
  78. String name_;
  79. String outFileName_;
  80. Vector<String> defines_;
  81. Vector<String> defineValues_;
  82. PODVector<unsigned char> byteCode_;
  83. Vector<Parameter> constants_;
  84. Vector<Parameter> textureUnits_;
  85. String errorMsg_;
  86. };
  87. SharedPtr<Context> context_(new Context());
  88. SharedPtr<FileSystem> fileSystem_(new FileSystem(context_));
  89. String inDir_;
  90. String outDir_;
  91. Vector<String> defines_;
  92. Vector<String> defineValues_;
  93. String variationName_;
  94. volatile bool compileFailed_ = false;
  95. bool useSM3_ = false;
  96. bool compileVariation_ = false;
  97. bool compileVS_ = true;
  98. bool compilePS_ = true;
  99. List<CompiledVariation> variations_;
  100. List<CompiledVariation*> workList_;
  101. Mutex workMutex_;
  102. String hlslCode_;
  103. int main(int argc, char** argv);
  104. void Run(const Vector<String>& arguments);
  105. void CompileShader(const String& fileName);
  106. void CompileVariation(CompiledVariation* variation);
  107. void CopyStrippedCode(PODVector<unsigned char>& dest, void* src, unsigned srcSize);
  108. class WorkerThread : public RefCounted, public Thread
  109. {
  110. public:
  111. void ThreadFunction()
  112. {
  113. for (;;)
  114. {
  115. CompiledVariation* workItem = 0;
  116. {
  117. MutexLock lock(workMutex_);
  118. if (!workList_.Empty())
  119. {
  120. workItem = workList_.Front();
  121. workList_.Erase(workList_.Begin());
  122. }
  123. }
  124. if (!workItem)
  125. return;
  126. // If compile(s) failed, just empty the list, but do not compile more
  127. if (!compileFailed_)
  128. CompileVariation(workItem);
  129. }
  130. }
  131. };
  132. class IncludeHandler : public ID3DInclude
  133. {
  134. public:
  135. STDMETHOD(Open)(D3D_INCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes)
  136. {
  137. String fileName = inDir_ + String((const char*)pFileName);
  138. File file(context_, fileName);
  139. if (!file.IsOpen())
  140. return E_FAIL;
  141. unsigned fileSize = file.GetSize();
  142. void* fileData = new unsigned char[fileSize];
  143. *pBytes = fileSize;
  144. *ppData = fileData;
  145. file.Read(fileData, fileSize);
  146. return S_OK;
  147. }
  148. STDMETHOD(Close)(LPCVOID pData)
  149. {
  150. delete[] (unsigned char*)pData;
  151. return S_OK;
  152. }
  153. };
  154. int main(int argc, char** argv)
  155. {
  156. Vector<String> arguments;
  157. #ifdef WIN32
  158. arguments = ParseArguments(GetCommandLineW());
  159. #else
  160. arguments = ParseArguments(argc, argv);
  161. #endif
  162. Run(arguments);
  163. return 0;
  164. }
  165. void Run(const Vector<String>& arguments)
  166. {
  167. if (arguments.Size() < 1)
  168. {
  169. ErrorExit(
  170. "Usage: ShaderCompiler <definitionfile> [outputpath] [options]\n\n"
  171. "Options:\n"
  172. "-t<VS|PS> Compile only vertex or pixel shaders, by default compile both\n"
  173. "-v<name> Compile only the shader variation with name\n"
  174. "-d<define> Add a define. Add SM3 to compile for Shader Model 3\n\n"
  175. "If output path is not specified, shader binaries will be output into the same\n"
  176. "directory as the definition file. Specify a wildcard to compile multiple\n"
  177. "shaders."
  178. );
  179. }
  180. String path, file, extension;
  181. SplitPath(arguments[0], path, file, extension);
  182. inDir_ = AddTrailingSlash(path);
  183. if (arguments.Size() > 1 && arguments[1][0] != '-')
  184. outDir_ = AddTrailingSlash(arguments[1]);
  185. else
  186. outDir_ = inDir_;
  187. for (unsigned i = 1; i < arguments.Size(); ++i)
  188. {
  189. if (arguments[i][0] == '-' && arguments[i].Length() > 1)
  190. {
  191. char option = arguments[i][1];
  192. String arg = arguments[i].Substring(2);
  193. switch (option)
  194. {
  195. case 'd':
  196. {
  197. Vector<String> nameAndValue = arg.Split('=');
  198. if (nameAndValue.Size() == 2)
  199. {
  200. defines_.Push(nameAndValue[0]);
  201. defineValues_.Push(nameAndValue[1]);
  202. if (nameAndValue[0] == "SM3" && ToInt(nameAndValue[1]) > 0)
  203. useSM3_ = true;
  204. }
  205. else
  206. {
  207. defines_.Push(arg);
  208. defineValues_.Push("1");
  209. if (arg == "SM3")
  210. useSM3_ = true;
  211. }
  212. }
  213. break;
  214. case 't':
  215. if (arg.ToLower() == "vs")
  216. {
  217. compileVS_ = true;
  218. compilePS_ = false;
  219. }
  220. else if (arg.ToLower() == "ps")
  221. {
  222. compileVS_ = false;
  223. compilePS_ = true;
  224. }
  225. break;
  226. case 'v':
  227. compileVariation_ = true;
  228. variationName_ = arg;
  229. break;
  230. }
  231. }
  232. }
  233. if (!file.StartsWith("*"))
  234. CompileShader(arguments[0]);
  235. else
  236. {
  237. Vector<String> shaderFiles;
  238. fileSystem_->ScanDir(shaderFiles, inDir_, file + extension, SCAN_FILES, false);
  239. for (unsigned i = 0; i < shaderFiles.Size(); ++i)
  240. CompileShader(inDir_ + shaderFiles[i]);
  241. }
  242. }
  243. void CompileShader(const String& fileName)
  244. {
  245. String file = GetFileName(fileName);
  246. XMLFile doc(context_);
  247. File source(context_);
  248. source.Open(fileName);
  249. if (!doc.Load(source))
  250. ErrorExit("Could not open input file " + fileName);
  251. XMLElement shaders = doc.GetRoot("shaders");
  252. if (!shaders)
  253. ErrorExit("No shaders element in " + source.GetName());
  254. if (compileVS_)
  255. {
  256. ShaderParser vsParser;
  257. if (!vsParser.Parse(VS, shaders, defines_, defineValues_))
  258. ErrorExit("VS: " + vsParser.GetErrorMessage());
  259. const HashMap<String, unsigned>& combinations = vsParser.GetAllCombinations();
  260. for (HashMap<String, unsigned>::ConstIterator i = combinations.Begin(); i != combinations.End(); ++i)
  261. {
  262. if (!compileVariation_ || i->first_ == variationName_)
  263. {
  264. ShaderCombination src = vsParser.GetCombination(i->first_);
  265. CompiledVariation compile;
  266. compile.type_ = VS;
  267. compile.name_ = file;
  268. compile.outFileName_ = outDir_ + file;
  269. if (!src.name_.Empty())
  270. {
  271. compile.name_ += "_" + src.name_;
  272. compile.outFileName_ += "_" + src.name_;
  273. }
  274. compile.outFileName_ += useSM3_ ? ".vs3" : ".vs2";
  275. compile.defines_ = src.defines_;
  276. compile.defineValues_ = src.defineValues_;
  277. variations_.Push(compile);
  278. workList_.Push(&variations_.Back());
  279. }
  280. }
  281. }
  282. if (compilePS_)
  283. {
  284. ShaderParser psParser;
  285. if (!psParser.Parse(PS, shaders, defines_, defineValues_))
  286. ErrorExit("PS: " + psParser.GetErrorMessage());
  287. const HashMap<String, unsigned>& combinations = psParser.GetAllCombinations();
  288. for (HashMap<String, unsigned>::ConstIterator i = combinations.Begin(); i != combinations.End(); ++i)
  289. {
  290. if (!compileVariation_ || i->first_ == variationName_)
  291. {
  292. ShaderCombination src = psParser.GetCombination(i->first_);
  293. CompiledVariation compile;
  294. compile.type_ = PS;
  295. compile.name_ = file;
  296. compile.outFileName_ = outDir_ + file;
  297. if (!src.name_.Empty())
  298. {
  299. compile.name_ += "_" + src.name_;
  300. compile.outFileName_ += "_" + src.name_;
  301. }
  302. compile.outFileName_ += useSM3_ ? ".ps3" : ".ps2";
  303. compile.defines_ = src.defines_;
  304. compile.defineValues_ = src.defineValues_;
  305. variations_.Push(compile);
  306. workList_.Push(&variations_.Back());
  307. }
  308. }
  309. }
  310. if (variations_.Empty())
  311. {
  312. PrintLine("No variations to compile");
  313. return;
  314. }
  315. // Load the shader source code
  316. {
  317. String inputFileName = inDir_ + file + ".hlsl";
  318. File hlslFile(context_, inputFileName);
  319. if (!hlslFile.IsOpen())
  320. ErrorExit("Could not open input file " + inputFileName);
  321. hlslCode_.Clear();
  322. while (!hlslFile.IsEof())
  323. hlslCode_ += hlslFile.ReadLine() + "\n";
  324. }
  325. if (!compileVariation_)
  326. {
  327. // Create and start worker threads. Use all logical CPUs except one to not lock up the computer completely
  328. unsigned numWorkerThreads = GetNumLogicalCPUs() - 1;
  329. if (!numWorkerThreads)
  330. numWorkerThreads = 1;
  331. Vector<SharedPtr<WorkerThread> > workerThreads;
  332. workerThreads.Resize(numWorkerThreads);
  333. for (unsigned i = 0; i < workerThreads.Size(); ++i)
  334. {
  335. workerThreads[i] = new WorkerThread();
  336. workerThreads[i]->Run();
  337. }
  338. // This will wait until the thread functions have stopped
  339. for (unsigned i = 0; i < workerThreads.Size(); ++i)
  340. workerThreads[i]->Stop();
  341. }
  342. else
  343. {
  344. WorkerThread dummyThread;
  345. dummyThread.ThreadFunction();
  346. }
  347. // Check that all shaders compiled
  348. for (List<CompiledVariation>::Iterator i = variations_.Begin(); i != variations_.End(); ++i)
  349. {
  350. if (!i->errorMsg_.Empty())
  351. {
  352. if (i->type_ == VS)
  353. ErrorExit("Failed to compile vertex shader " + i->name_ + ": " + i->errorMsg_);
  354. else
  355. ErrorExit("Failed to compile pixel shader " + i->name_ + ": " + i->errorMsg_);
  356. }
  357. }
  358. }
  359. void CompileVariation(CompiledVariation* variation)
  360. {
  361. IncludeHandler includeHandler;
  362. PODVector<D3D_SHADER_MACRO> macros;
  363. // Insert variation-specific and global defines
  364. for (unsigned i = 0; i < variation->defines_.Size(); ++i)
  365. {
  366. D3D_SHADER_MACRO macro;
  367. macro.Name = variation->defines_[i].CString();
  368. macro.Definition = variation->defineValues_[i].CString();
  369. macros.Push(macro);
  370. }
  371. for (unsigned i = 0; i < defines_.Size(); ++i)
  372. {
  373. D3D_SHADER_MACRO macro;
  374. macro.Name = defines_[i].CString();
  375. macro.Definition = defineValues_[i].CString();
  376. macros.Push(macro);
  377. }
  378. D3D_SHADER_MACRO endMacro;
  379. endMacro.Name = 0;
  380. endMacro.Definition = 0;
  381. macros.Push(endMacro);
  382. LPD3DBLOB shaderCode = NULL;
  383. LPD3DBLOB errorMsgs = NULL;
  384. // Set the profile, entrypoint and flags according to the shader being compiled
  385. String profile;
  386. String entryPoint;
  387. unsigned flags = D3DCOMPILE_OPTIMIZATION_LEVEL3;
  388. if (variation->type_ == VS)
  389. {
  390. entryPoint = "VS";
  391. if (!useSM3_)
  392. profile = "vs_2_0";
  393. else
  394. profile = "vs_3_0";
  395. }
  396. else
  397. {
  398. entryPoint = "PS";
  399. if (!useSM3_)
  400. profile = "ps_2_0";
  401. else
  402. {
  403. profile = "ps_3_0";
  404. flags |= D3DCOMPILE_PREFER_FLOW_CONTROL;
  405. }
  406. }
  407. // Compile using D3DCompiler
  408. HRESULT hr = D3DCompile(hlslCode_.CString(), hlslCode_.Length(), NULL, &macros.Front(), &includeHandler,
  409. entryPoint.CString(), profile.CString(), flags, 0, &shaderCode, &errorMsgs);
  410. if (FAILED(hr))
  411. {
  412. variation->errorMsg_ = String((const char*)errorMsgs->GetBufferPointer(), errorMsgs->GetBufferSize());
  413. compileFailed_ = true;
  414. }
  415. else
  416. {
  417. BYTE const *const bufData = static_cast<BYTE *>(shaderCode->GetBufferPointer());
  418. SIZE_T const bufSize = shaderCode->GetBufferSize();
  419. MOJOSHADER_parseData const *parseData = MOJOSHADER_parse("bytecode", bufData, bufSize, NULL, 0, NULL, 0, NULL, NULL, NULL);
  420. CopyStrippedCode(variation->byteCode_, shaderCode->GetBufferPointer(), shaderCode->GetBufferSize());
  421. if (!variation->name_.Empty())
  422. PrintLine("Compiled shader variation " + variation->name_ + ", code size " + String(variation->byteCode_.Size()));
  423. else
  424. PrintLine("Compiled base shader variation, code size " + String(variation->byteCode_.Size()));
  425. // Print warnings if any
  426. if (errorMsgs && errorMsgs->GetBufferSize())
  427. {
  428. String warning((const char*)errorMsgs->GetBufferPointer(), errorMsgs->GetBufferSize());
  429. PrintLine("WARNING: " + warning);
  430. }
  431. for(int i = 0; i < parseData->symbol_count; i++)
  432. {
  433. MOJOSHADER_symbol const& symbol = parseData->symbols[i];
  434. String name(symbol.name);
  435. unsigned const reg = symbol.register_index;
  436. unsigned const regCount = symbol.register_count;
  437. // Check if the parameter is a constant or a texture sampler
  438. bool const isSampler = (name[0] == 's');
  439. name = name.Substring(1);
  440. if (isSampler)
  441. {
  442. // Skip if it's a G-buffer sampler, which are aliases for the standard texture units
  443. if (name != "AlbedoBuffer" && name != "NormalBuffer" && name != "DepthBuffer" && name != "LightBuffer")
  444. {
  445. Parameter newTextureUnit(name, reg, 1);
  446. variation->textureUnits_.Push(newTextureUnit);
  447. }
  448. }
  449. else
  450. {
  451. Parameter newParam(name, reg, regCount);
  452. variation->constants_.Push(newParam);
  453. }
  454. }
  455. MOJOSHADER_freeParseData(parseData);
  456. // Create the last part of the output path (SM2/SM3) if it does not exist
  457. String outPath = GetPath(variation->outFileName_);
  458. if (!fileSystem_->DirExists(outPath))
  459. fileSystem_->CreateDir(outPath);
  460. File outFile(context_);
  461. if (!outFile.Open(variation->outFileName_, FILE_WRITE))
  462. {
  463. variation->errorMsg_ = "Could not open output file " + variation->outFileName_;
  464. compileFailed_ = true;
  465. }
  466. else
  467. {
  468. outFile.WriteFileID("USHD");
  469. outFile.WriteShort((unsigned short)variation->type_);
  470. outFile.WriteShort(useSM3_ ? 3 : 2);
  471. outFile.WriteUInt(variation->constants_.Size());
  472. for (unsigned i = 0; i < variation->constants_.Size(); ++i)
  473. {
  474. outFile.WriteString(variation->constants_[i].name_);
  475. outFile.WriteUByte(variation->constants_[i].register_);
  476. outFile.WriteUByte(variation->constants_[i].regCount_);
  477. }
  478. outFile.WriteUInt(variation->textureUnits_.Size());
  479. for (unsigned i = 0; i < variation->textureUnits_.Size(); ++i)
  480. {
  481. outFile.WriteString(variation->textureUnits_[i].name_);
  482. outFile.WriteUByte(variation->textureUnits_[i].register_);
  483. }
  484. unsigned dataSize = variation->byteCode_.Size();
  485. outFile.WriteUInt(dataSize);
  486. if (dataSize)
  487. outFile.Write(&variation->byteCode_[0], dataSize);
  488. }
  489. }
  490. if (shaderCode)
  491. shaderCode->Release();
  492. if (errorMsgs)
  493. errorMsgs->Release();
  494. }
  495. void CopyStrippedCode(PODVector<unsigned char>& dest, void* src, unsigned srcSize)
  496. {
  497. unsigned const D3DSIO_COMMENT = 0xFFFE;
  498. unsigned* srcWords = (unsigned*)src;
  499. unsigned srcWordSize = srcSize >> 2;
  500. dest.Clear();
  501. for (unsigned i = 0; i < srcWordSize; ++i)
  502. {
  503. unsigned opcode = srcWords[i] & 0xffff;
  504. unsigned paramLength = (srcWords[i] & 0x0f000000) >> 24;
  505. unsigned commentLength = srcWords[i] >> 16;
  506. // For now, skip comment only at fixed position to prevent false positives
  507. if (i == 1 && opcode == D3DSIO_COMMENT)
  508. {
  509. // Skip the comment
  510. i += commentLength;
  511. }
  512. else
  513. {
  514. // Not a comment, copy the data
  515. unsigned char* srcBytes = (unsigned char*)(srcWords + i);
  516. dest.Push(*srcBytes++);
  517. dest.Push(*srcBytes++);
  518. dest.Push(*srcBytes++);
  519. dest.Push(*srcBytes++);
  520. }
  521. }
  522. }