ShaderCompiler.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Context.h"
  24. #include "File.h"
  25. #include "FileSystem.h"
  26. #include "List.h"
  27. #include "Map.h"
  28. #include "Mutex.h"
  29. #include "ProcessUtils.h"
  30. #include "Set.h"
  31. #include "StringUtils.h"
  32. #include "Thread.h"
  33. #include "XMLFile.h"
  34. #include <cstdio>
  35. #include <cstring>
  36. #include <windows.h>
  37. #include <d3d9.h>
  38. #include <d3dx9shader.h>
  39. #include "DebugNew.h"
  40. enum ShaderType
  41. {
  42. VS = 0,
  43. PS,
  44. Both
  45. };
  46. struct Parameter
  47. {
  48. Parameter()
  49. {
  50. }
  51. Parameter(const String& name, unsigned reg, unsigned regCount) :
  52. name_(name),
  53. register_(reg),
  54. regCount_(regCount)
  55. {
  56. }
  57. bool operator < (const Parameter& rhs) const
  58. {
  59. if (register_ != rhs.register_)
  60. return register_ < rhs.register_;
  61. else if (name_ != rhs.name_)
  62. return name_ < rhs.name_;
  63. else
  64. return regCount_ < rhs.regCount_;
  65. }
  66. bool operator > (const Parameter& rhs) const
  67. {
  68. if (register_ != rhs.register_)
  69. return register_ > rhs.register_;
  70. else if (name_ != rhs.name_)
  71. return name_ > rhs.name_;
  72. else
  73. return regCount_ > rhs.regCount_;
  74. }
  75. bool operator == (const Parameter& rhs) const { return register_ == rhs.register_ && name_ == rhs.name_ && regCount_ == rhs.regCount_; }
  76. bool operator != (const Parameter& rhs) const { return register_ != rhs.register_ || name_ != rhs.name_ || regCount_ != rhs.regCount_; }
  77. String name_;
  78. unsigned register_;
  79. unsigned regCount_;
  80. };
  81. struct Variation
  82. {
  83. Variation()
  84. {
  85. }
  86. Variation(const String& name, bool isOption) :
  87. name_(name),
  88. option_(isOption)
  89. {
  90. }
  91. String name_;
  92. Vector<String> defines_;
  93. Vector<String> defineValues_;
  94. Vector<String> excludes_;
  95. Vector<String> includes_;
  96. Vector<String> requires_;
  97. bool option_;
  98. };
  99. struct CompiledVariation
  100. {
  101. ShaderType type_;
  102. String name_;
  103. Vector<String> defines_;
  104. Vector<String> defineValues_;
  105. PODVector<unsigned char> byteCode_;
  106. unsigned byteCodeOffset_;
  107. Set<Parameter> constants_;
  108. Set<Parameter> textureUnits_;
  109. String errorMsg_;
  110. };
  111. struct Shader
  112. {
  113. Shader(const String& name, ShaderType type) :
  114. name_(name),
  115. type_(type)
  116. {
  117. }
  118. String name_;
  119. ShaderType type_;
  120. Vector<Variation> variations_;
  121. };
  122. SharedPtr<Context> context_(new Context());
  123. SharedPtr<FileSystem> fileSystem_(new FileSystem(context_));
  124. String inDir_;
  125. String inFile_;
  126. String outDir_;
  127. Vector<String> defines_;
  128. Vector<String> defineValues_;
  129. bool useSM3_ = false;
  130. volatile bool compileFailed_ = false;
  131. List<CompiledVariation*> workList_;
  132. Mutex globalParamMutex_;
  133. Mutex workMutex_;
  134. String hlslCode_;
  135. Set<String> constants_;
  136. Set<String> textureUnits_;
  137. int main(int argc, char** argv);
  138. void Run(const Vector<String>& arguments);
  139. void CompileVariations(const Shader& baseShader, XMLElement& shaders);
  140. void Compile(CompiledVariation* variation);
  141. void CopyStrippedCode(PODVector<unsigned char>& dest, void* src, unsigned srcSize);
  142. class WorkerThread : public RefCounted, public Thread
  143. {
  144. public:
  145. void ThreadFunction()
  146. {
  147. for (;;)
  148. {
  149. CompiledVariation* workItem = 0;
  150. {
  151. MutexLock lock(workMutex_);
  152. if (!workList_.Empty())
  153. {
  154. workItem = workList_.Front();
  155. workList_.Erase(workList_.Begin());
  156. }
  157. }
  158. if (!workItem)
  159. return;
  160. // If compile(s) failed, just empty the list, but do not compile more
  161. if (!compileFailed_)
  162. Compile(workItem);
  163. }
  164. }
  165. };
  166. class IncludeHandler : public ID3DXInclude
  167. {
  168. public:
  169. STDMETHOD(Open)(D3DXINCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes)
  170. {
  171. String fileName = inDir_ + String((const char*)pFileName);
  172. File file(context_, fileName);
  173. if (!file.IsOpen())
  174. return E_FAIL;
  175. unsigned fileSize = file.GetSize();
  176. void* fileData = new unsigned char[fileSize];
  177. *pBytes = fileSize;
  178. *ppData = fileData;
  179. file.Read(fileData, fileSize);
  180. return S_OK;
  181. }
  182. STDMETHOD(Close)(LPCVOID pData)
  183. {
  184. delete[] (unsigned char*)pData;
  185. return S_OK;
  186. }
  187. };
  188. int main(int argc, char** argv)
  189. {
  190. Vector<String> arguments;
  191. #ifdef WIN32
  192. arguments = ParseArguments(GetCommandLineW());
  193. #else
  194. arguments = ParseArguments(argc, argv);
  195. #endif
  196. Run(arguments);
  197. return 0;
  198. }
  199. void Run(const Vector<String>& arguments)
  200. {
  201. if (arguments.Size() < 2)
  202. {
  203. ErrorExit(
  204. "Usage: ShaderCompiler <definitionfile> <outputpath> [SM3] [define1] [define2]\n\n"
  205. "HLSL files will be loaded from definition file directory, and binary files will\n"
  206. "be output to the output path, preserving the subdirectory structure.\n"
  207. );
  208. }
  209. unsigned pos = arguments[0].FindLast('/');
  210. if (pos != String::NPOS)
  211. {
  212. inDir_ = arguments[0].Substring(0, pos);
  213. inFile_ = arguments[0].Substring(pos + 1);
  214. }
  215. else
  216. {
  217. inFile_ = arguments[0];
  218. }
  219. outDir_ = arguments[1];
  220. inDir_ = AddTrailingSlash(inDir_);
  221. outDir_ = AddTrailingSlash(outDir_);
  222. for (unsigned i = 2; i < arguments.Size(); ++i)
  223. {
  224. String arg = arguments[i].ToUpper();
  225. if (arg == "SM3")
  226. useSM3_ = true;
  227. else if (arg == "SM2")
  228. useSM3_ = false;
  229. Vector<String> nameAndValue = arg.Split('=');
  230. if (nameAndValue.Size() == 2)
  231. {
  232. defines_.Push(nameAndValue[0]);
  233. defineValues_.Push(nameAndValue[1]);
  234. }
  235. else
  236. {
  237. defines_.Push(arg);
  238. defineValues_.Push("1");
  239. }
  240. }
  241. XMLFile doc(context_);
  242. File source(context_);
  243. source.Open(arguments[0]);
  244. if (!doc.Load(source))
  245. ErrorExit("Could not open input file " + arguments[0]);
  246. XMLElement shaders = doc.GetRoot("shaders");
  247. if (!shaders)
  248. ErrorExit("No shaders element in " + source.GetName());
  249. XMLFile outDoc(context_);
  250. XMLElement outShaders = outDoc.CreateRoot("shaders");
  251. XMLElement shader = shaders.GetChild("shader");
  252. while (shader)
  253. {
  254. String source = shader.GetAttribute("name");
  255. ShaderType compileType = Both;
  256. String type = shader.GetAttribute("type");
  257. if (type == "VS" || type == "vs")
  258. compileType = VS;
  259. if (type == "PS" || type == "ps")
  260. compileType = PS;
  261. Shader baseShader(source, compileType);
  262. XMLElement variation = shader.GetChild();
  263. while (variation)
  264. {
  265. String value = variation.GetName();
  266. if (value == "variation" || value == "option")
  267. {
  268. String name = variation.GetAttribute("name");
  269. Variation newVar(name, value == "option");
  270. String simpleDefine = variation.GetAttribute("define");
  271. if (!simpleDefine.Empty())
  272. {
  273. Vector<String> nameAndValue = simpleDefine.Split('=');
  274. if (nameAndValue.Size() == 2)
  275. {
  276. newVar.defines_.Push(nameAndValue[0]);
  277. newVar.defineValues_.Push(nameAndValue[1]);
  278. }
  279. else
  280. {
  281. newVar.defines_.Push(simpleDefine);
  282. newVar.defineValues_.Push("1");
  283. }
  284. }
  285. String simpleExclude = variation.GetAttribute("exclude");
  286. if (!simpleExclude.Empty())
  287. newVar.excludes_.Push(simpleExclude);
  288. String simpleInclude = variation.GetAttribute("include");
  289. if (!simpleInclude.Empty())
  290. newVar.includes_.Push(simpleInclude);
  291. String simpleRequire = variation.GetAttribute("require");
  292. if (!simpleRequire.Empty())
  293. newVar.requires_.Push(simpleRequire);
  294. XMLElement define = variation.GetChild("define");
  295. while (define)
  296. {
  297. String defineName = define.GetAttribute("name");
  298. Vector<String> nameAndValue = defineName.Split('=');
  299. if (nameAndValue.Size() == 2)
  300. {
  301. newVar.defines_.Push(nameAndValue[0]);
  302. newVar.defineValues_.Push(nameAndValue[1]);
  303. }
  304. else
  305. {
  306. newVar.defines_.Push(defineName);
  307. newVar.defineValues_.Push("1");
  308. }
  309. define = define.GetNext("define");
  310. }
  311. XMLElement exclude = variation.GetChild("exclude");
  312. while (exclude)
  313. {
  314. newVar.excludes_.Push(exclude.GetAttribute("name"));
  315. exclude = exclude.GetNext("exclude");
  316. }
  317. XMLElement include = variation.GetChild("include");
  318. while (include)
  319. {
  320. newVar.includes_.Push(include.GetAttribute("name"));
  321. include = include.GetNext("include");
  322. }
  323. XMLElement require = variation.GetChild("require");
  324. while (require)
  325. {
  326. newVar.requires_.Push(require.GetAttribute("name"));
  327. require = require.GetNext("require");
  328. }
  329. baseShader.variations_.Push(newVar);
  330. }
  331. variation = variation.GetNext();
  332. }
  333. if (baseShader.type_ != Both)
  334. CompileVariations(baseShader, outShaders);
  335. else
  336. {
  337. baseShader.type_ = VS;
  338. CompileVariations(baseShader, outShaders);
  339. baseShader.type_ = PS;
  340. CompileVariations(baseShader, outShaders);
  341. }
  342. shader = shader.GetNext("shader");
  343. }
  344. }
  345. void CompileVariations(const Shader& baseShader, XMLElement& shaders)
  346. {
  347. unsigned combinations = 1;
  348. Set<unsigned> usedCombinations;
  349. Map<String, unsigned> nameToIndex;
  350. Vector<CompiledVariation> compiledVariations;
  351. unsigned numVariationGroups = 0;
  352. const Vector<Variation>& variations = baseShader.variations_;
  353. if (variations.Size() > 32)
  354. ErrorExit("Maximum amount of variations exceeded");
  355. // Load the shader source code
  356. {
  357. String inputFileName = inDir_ + baseShader.name_ + ".hlsl";
  358. File hlslFile(context_, inputFileName);
  359. if (!hlslFile.IsOpen())
  360. ErrorExit("Could not open input file " + inputFileName);
  361. hlslCode_.Clear();
  362. while (!hlslFile.IsEof())
  363. hlslCode_ += hlslFile.ReadLine() + "\n";
  364. }
  365. for (unsigned i = 0; i < variations.Size(); ++i)
  366. {
  367. combinations *= 2;
  368. nameToIndex[variations[i].name_] = i;
  369. if (!variations[i].option_ && (i == 0 || variations[i - 1].option_))
  370. ++numVariationGroups;
  371. }
  372. for (unsigned i = 0; i < combinations; ++i)
  373. {
  374. unsigned active = i; // Variations/options active on this particular combination
  375. unsigned variationsActive = 0;
  376. bool skipThis = false;
  377. // Check for excludes/includes/requires
  378. for (unsigned j = 0; j < variations.Size(); ++j)
  379. {
  380. if ((active >> j) & 1)
  381. {
  382. for (unsigned k = 0; k < variations[j].includes_.Size(); ++k)
  383. {
  384. if (nameToIndex.Contains(variations[j].includes_[k]))
  385. active |= (1 << nameToIndex[variations[j].includes_[k]]);
  386. }
  387. for (unsigned k = 0; k < variations[j].excludes_.Size(); ++k)
  388. {
  389. if (nameToIndex.Contains(variations[j].excludes_[k]))
  390. active &= ~(1 << nameToIndex[variations[j].excludes_[k]]);
  391. }
  392. // Skip dummy separators (options without name and defines)
  393. if (variations[j].name_.Empty() && variations[j].option_ && variations[j].defines_.Empty())
  394. active &= ~(1 << j);
  395. // If it's a variation, exclude all other variations in the same group
  396. if (!variations[j].option_)
  397. {
  398. for (unsigned k = j - 1; k < variations.Size(); --k)
  399. {
  400. if (!variations[k].option_)
  401. active &= ~(1 << k);
  402. else
  403. break;
  404. }
  405. for (unsigned k = j + 1; k < variations.Size(); ++k)
  406. {
  407. if (!variations[k].option_)
  408. active &= ~(1 << k);
  409. else
  410. break;
  411. }
  412. ++variationsActive;
  413. }
  414. for (unsigned k = 0; k < variations[j].requires_.Size(); ++k)
  415. {
  416. bool requireFound = false;
  417. for (unsigned l = 0; l < defines_.Size(); ++l)
  418. {
  419. if (defines_[l] == variations[j].requires_[k])
  420. {
  421. requireFound = true;
  422. break;
  423. }
  424. }
  425. for (unsigned l = 0; l < variations.Size(); ++l)
  426. {
  427. if ((active >> l) & 1 && l != j)
  428. {
  429. if (variations[l].name_ == variations[j].requires_[k])
  430. {
  431. requireFound = true;
  432. break;
  433. }
  434. for (unsigned m = 0; m < variations[l].defines_.Size(); ++m)
  435. {
  436. if (variations[l].defines_[m] == variations[j].requires_[k])
  437. {
  438. requireFound = true;
  439. break;
  440. }
  441. }
  442. }
  443. if (requireFound)
  444. break;
  445. }
  446. if (!requireFound)
  447. skipThis = true;
  448. }
  449. }
  450. }
  451. // If variations are included, check that one from each group is active
  452. if (variationsActive < numVariationGroups)
  453. continue;
  454. if (skipThis)
  455. continue;
  456. // Check that this combination is unique
  457. if (usedCombinations.Contains(active))
  458. continue;
  459. // Build shader variation name & defines for active variations
  460. String outName;
  461. Vector<String> defines;
  462. Vector<String> defineValues;
  463. for (unsigned j = 0; j < variations.Size(); ++j)
  464. {
  465. if (active & (1 << j))
  466. {
  467. if (variations[j].name_.Length())
  468. outName += variations[j].name_;
  469. for (unsigned k = 0; k < variations[j].defines_.Size(); ++k)
  470. {
  471. defines.Push(variations[j].defines_[k]);
  472. defineValues.Push(variations[j].defineValues_[k]);
  473. }
  474. }
  475. }
  476. CompiledVariation compile;
  477. compile.type_ = baseShader.type_;
  478. compile.name_ = outName;
  479. compile.defines_ = defines;
  480. compile.defineValues_ = defineValues;
  481. compiledVariations.Push(compile);
  482. usedCombinations.Insert(active);
  483. }
  484. // Prepare the work list
  485. // (all variations must be created first, so that vector resize does not change pointers)
  486. for (unsigned i = 0; i < compiledVariations.Size(); ++i)
  487. workList_.Push(&compiledVariations[i]);
  488. // Create and start worker threads. Use all logical CPUs except one to not lock up the computer completely
  489. unsigned numWorkerThreads = GetNumLogicalCPUs() - 1;
  490. if (!numWorkerThreads)
  491. numWorkerThreads = 1;
  492. Vector<SharedPtr<WorkerThread> > workerThreads;
  493. workerThreads.Resize(numWorkerThreads);
  494. for (unsigned i = 0; i < workerThreads.Size(); ++i)
  495. {
  496. workerThreads[i] = new WorkerThread();
  497. workerThreads[i]->Start();
  498. }
  499. // This will wait until the thread functions have stopped
  500. for (unsigned i = 0; i < workerThreads.Size(); ++i)
  501. workerThreads[i]->Stop();
  502. // Check that all shaders compiled
  503. for (unsigned i = 0; i < compiledVariations.Size(); ++i)
  504. {
  505. if (!compiledVariations[i].errorMsg_.Empty())
  506. ErrorExit("Failed to compile shader " + baseShader.name_ + "_" + compiledVariations[i].name_ + ": " + compiledVariations[i].errorMsg_);
  507. }
  508. // Build the output file
  509. String outFileName = outDir_ + inDir_ + baseShader.name_;
  510. outFileName += (baseShader.type_ == VS) ? ".vs" : ".ps";
  511. outFileName += (useSM3_) ? "3" : "2";
  512. File outFile(context_, outFileName, FILE_WRITE);
  513. if (!outFile.IsOpen())
  514. ErrorExit("Could not open output file " + outFileName);
  515. outFile.WriteFileID("USHD");
  516. outFile.WriteShort(baseShader.type_);
  517. outFile.WriteShort(useSM3_ ? 3 : 2);
  518. outFile.WriteUInt(constants_.Size());
  519. for (Set<String>::ConstIterator i = constants_.Begin(); i != constants_.End(); ++i)
  520. outFile.WriteString(*i);
  521. outFile.WriteUInt(textureUnits_.Size());
  522. for (Set<String>::ConstIterator i = textureUnits_.Begin(); i != textureUnits_.End(); ++i)
  523. outFile.WriteString(*i);
  524. outFile.WriteUInt(compiledVariations.Size());
  525. for (unsigned i = 0; i < compiledVariations.Size(); ++i)
  526. {
  527. CompiledVariation& variation = compiledVariations[i];
  528. outFile.WriteString(variation.name_);
  529. outFile.WriteUInt(variation.constants_.Size());
  530. for (Set<Parameter>::ConstIterator i = variation.constants_.Begin(); i != variation.constants_.End(); ++i)
  531. {
  532. outFile.WriteStringHash(StringHash(i->name_));
  533. outFile.WriteUByte(i->register_);
  534. outFile.WriteUByte(i->regCount_);
  535. }
  536. outFile.WriteUInt(variation.textureUnits_.Size());
  537. for (Set<Parameter>::ConstIterator i = variation.textureUnits_.Begin(); i != variation.textureUnits_.End(); ++i)
  538. {
  539. outFile.WriteStringHash(StringHash(i->name_));
  540. outFile.WriteUByte(i->register_);
  541. }
  542. unsigned dataSize = variation.byteCode_.Size();
  543. outFile.WriteUInt(dataSize);
  544. if (dataSize)
  545. outFile.Write(&variation.byteCode_[0], dataSize);
  546. }
  547. }
  548. void Compile(CompiledVariation* variation)
  549. {
  550. IncludeHandler includeHandler;
  551. PODVector<D3DXMACRO> macros;
  552. // Insert variation-specific and global defines
  553. for (unsigned i = 0; i < variation->defines_.Size(); ++i)
  554. {
  555. D3DXMACRO macro;
  556. macro.Name = variation->defines_[i].CString();
  557. macro.Definition = variation->defineValues_[i].CString();
  558. macros.Push(macro);
  559. }
  560. for (unsigned i = 0; i < defines_.Size(); ++i)
  561. {
  562. D3DXMACRO macro;
  563. macro.Name = defines_[i].CString();
  564. macro.Definition = defineValues_[i].CString();
  565. macros.Push(macro);
  566. }
  567. D3DXMACRO endMacro;
  568. endMacro.Name = 0;
  569. endMacro.Definition = 0;
  570. macros.Push(endMacro);
  571. LPD3DXBUFFER shaderCode = 0;
  572. LPD3DXBUFFER errorMsgs = 0;
  573. LPD3DXCONSTANTTABLE constantTable = 0;
  574. // Set the profile, entrypoint and flags according to the shader being compiled
  575. String profile;
  576. String entryPoint;
  577. unsigned flags = D3DXSHADER_OPTIMIZATION_LEVEL3;
  578. if (variation->type_ == VS)
  579. {
  580. entryPoint = "VS";
  581. if (!useSM3_)
  582. profile = "vs_2_0";
  583. else
  584. profile = "vs_3_0";
  585. }
  586. else
  587. {
  588. entryPoint = "PS";
  589. if (!useSM3_)
  590. profile = "ps_2_0";
  591. else
  592. {
  593. profile = "ps_3_0";
  594. flags |= D3DXSHADER_PREFER_FLOW_CONTROL;
  595. }
  596. }
  597. // Compile using D3DX
  598. HRESULT hr = D3DXCompileShader(hlslCode_.CString(), hlslCode_.Length(), &macros.Front(), &includeHandler,
  599. entryPoint.CString(), profile.CString(), flags, &shaderCode, &errorMsgs, &constantTable);
  600. if (FAILED(hr))
  601. {
  602. variation->errorMsg_ = String((const char*)errorMsgs->GetBufferPointer(), errorMsgs->GetBufferSize());
  603. compileFailed_ = true;
  604. }
  605. else
  606. {
  607. CopyStrippedCode(variation->byteCode_, shaderCode->GetBufferPointer(), shaderCode->GetBufferSize());
  608. if (!variation->name_.Empty())
  609. PrintLine("Compiled shader variation " + variation->name_ + ", code size " + String(variation->byteCode_.Size()));
  610. else
  611. PrintLine("Compiled base shader variation, code size " + String(variation->byteCode_.Size()));
  612. // Print warnings if any
  613. if (errorMsgs && errorMsgs->GetBufferSize())
  614. {
  615. String warning((const char*)errorMsgs->GetBufferPointer(), errorMsgs->GetBufferSize());
  616. PrintLine("WARNING: " + warning);
  617. }
  618. // Parse the constant table for constants and texture units
  619. D3DXCONSTANTTABLE_DESC desc;
  620. constantTable->GetDesc(&desc);
  621. for (unsigned i = 0; i < desc.Constants; ++i)
  622. {
  623. D3DXHANDLE handle = constantTable->GetConstant(NULL, i);
  624. D3DXCONSTANT_DESC constantDesc;
  625. unsigned numElements = 1;
  626. constantTable->GetConstantDesc(handle, &constantDesc, &numElements);
  627. String name(constantDesc.Name);
  628. unsigned reg = constantDesc.RegisterIndex;
  629. unsigned regCount = constantDesc.RegisterCount;
  630. // Check if the parameter is a constant or a texture sampler
  631. bool isSampler = (name[0] == 's');
  632. name = name.Substring(1);
  633. MutexLock lock(globalParamMutex_);
  634. if (isSampler)
  635. {
  636. // Skip if it's a G-buffer sampler
  637. if (name.Find("Buffer") == String::NPOS)
  638. {
  639. Parameter newTextureUnit(name, reg, 1);
  640. variation->textureUnits_.Insert(newTextureUnit);
  641. textureUnits_.Insert(name);
  642. }
  643. }
  644. else
  645. {
  646. Parameter newParam(name, reg, regCount);
  647. variation->constants_.Insert(newParam);
  648. constants_.Insert(name);
  649. }
  650. }
  651. }
  652. if (shaderCode)
  653. shaderCode->Release();
  654. if (constantTable)
  655. constantTable->Release();
  656. if (errorMsgs)
  657. errorMsgs->Release();
  658. }
  659. void CopyStrippedCode(PODVector<unsigned char>& dest, void* src, unsigned srcSize)
  660. {
  661. unsigned* srcWords = (unsigned*)src;
  662. unsigned srcWordSize = srcSize >> 2;
  663. dest.Clear();
  664. for (unsigned i = 0; i < srcWordSize; ++i)
  665. {
  666. unsigned opcode = srcWords[i] & 0xffff;
  667. unsigned paramLength = (srcWords[i] & 0x0f000000) >> 24;
  668. unsigned commentLength = srcWords[i] >> 16;
  669. // For now, skip comment only at fixed position to prevent false positives
  670. if (i == 1 && opcode == D3DSIO_COMMENT)
  671. {
  672. // Skip the comment
  673. i += commentLength;
  674. }
  675. else
  676. {
  677. // Not a comment, copy the data
  678. unsigned char* srcBytes = (unsigned char*)(srcWords + i);
  679. dest.Push(*srcBytes++);
  680. dest.Push(*srcBytes++);
  681. dest.Push(*srcBytes++);
  682. dest.Push(*srcBytes++);
  683. }
  684. }
  685. }