CmD3D9HLSLProgram.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. /*
  2. -----------------------------------------------------------------------------
  3. This source file is part of OGRE
  4. (Object-oriented Graphics Rendering Engine)
  5. For the latest info, see http://www.ogre3d.org/
  6. Copyright (c) 2000-2011 Torus Knot Software Ltd
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  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. */
  24. #include "CmD3D9HLSLProgram.h"
  25. #include "CmGpuProgramManager.h"
  26. #include "CmD3D9GpuProgram.h"
  27. #include "CmException.h"
  28. #include "CmRenderSystem.h"
  29. #include "CmRenderSystemManager.h"
  30. #include "CmAsyncOp.h"
  31. #include "CmD3D9HLSLProgramRTTI.h"
  32. namespace CamelotEngine {
  33. class CM_D3D9_EXPORT HLSLIncludeHandler : public ID3DXInclude
  34. {
  35. public:
  36. HLSLIncludeHandler(HighLevelGpuProgram* sourceProgram)
  37. : mProgram(sourceProgram) {}
  38. ~HLSLIncludeHandler() {}
  39. STDMETHOD(Open)(D3DXINCLUDE_TYPE IncludeType,
  40. LPCSTR pFileName,
  41. LPCVOID pParentData,
  42. LPCVOID *ppData,
  43. UINT *pByteLen
  44. )
  45. {
  46. // TODO PORT - I'm not sure what to do with this. It will probably break something in its current state.
  47. //// find & load source code
  48. //DataStreamPtr stream =
  49. // ResourceGroupManager::getSingleton().openResource(
  50. // String(pFileName), mProgram->getGroup(), true, mProgram);
  51. //String source = stream->getAsString();
  52. //// copy into separate c-string
  53. //// Note - must NOT copy the null terminator, otherwise this will terminate
  54. //// the entire program string!
  55. //*pByteLen = static_cast<UINT>(source.length());
  56. //char* pChar = new char[*pByteLen];
  57. //memcpy(pChar, source.c_str(), *pByteLen);
  58. //*ppData = pChar;
  59. assert(false); // TODO - Include files not supported until I can figure out how to handle them
  60. return S_OK;
  61. }
  62. STDMETHOD(Close)(LPCVOID pData)
  63. {
  64. char* pChar = (char*)pData;
  65. delete [] pChar;
  66. return S_OK;
  67. }
  68. protected:
  69. HighLevelGpuProgram* mProgram;
  70. };
  71. //-----------------------------------------------------------------------
  72. //-----------------------------------------------------------------------
  73. void D3D9HLSLProgram::loadFromSource(void)
  74. {
  75. // Populate preprocessor defines
  76. String stringBuffer;
  77. vector<D3DXMACRO>::type defines;
  78. const D3DXMACRO* pDefines = 0;
  79. if (!mPreprocessorDefines.empty())
  80. {
  81. stringBuffer = mPreprocessorDefines;
  82. // Split preprocessor defines and build up macro array
  83. D3DXMACRO macro;
  84. String::size_type pos = 0;
  85. while (pos != String::npos)
  86. {
  87. macro.Name = &stringBuffer[pos];
  88. macro.Definition = 0;
  89. String::size_type start_pos=pos;
  90. // Find delims
  91. pos = stringBuffer.find_first_of(";,=", pos);
  92. if(start_pos==pos)
  93. {
  94. if(pos==stringBuffer.length())
  95. {
  96. break;
  97. }
  98. pos++;
  99. continue;
  100. }
  101. if (pos != String::npos)
  102. {
  103. // Check definition part
  104. if (stringBuffer[pos] == '=')
  105. {
  106. // Setup null character for macro name
  107. stringBuffer[pos++] = '\0';
  108. macro.Definition = &stringBuffer[pos];
  109. pos = stringBuffer.find_first_of(";,", pos);
  110. }
  111. else
  112. {
  113. // No definition part, define as "1"
  114. macro.Definition = "1";
  115. }
  116. if (pos != String::npos)
  117. {
  118. // Setup null character for macro name or definition
  119. stringBuffer[pos++] = '\0';
  120. }
  121. }
  122. else
  123. {
  124. macro.Definition = "1";
  125. }
  126. if(strlen(macro.Name)>0)
  127. {
  128. defines.push_back(macro);
  129. }
  130. else
  131. {
  132. break;
  133. }
  134. }
  135. // Add NULL terminator
  136. macro.Name = 0;
  137. macro.Definition = 0;
  138. defines.push_back(macro);
  139. pDefines = &defines[0];
  140. }
  141. // Populate compile flags
  142. DWORD compileFlags = 0;
  143. if (mColumnMajorMatrices)
  144. compileFlags |= D3DXSHADER_PACKMATRIX_COLUMNMAJOR;
  145. else
  146. compileFlags |= D3DXSHADER_PACKMATRIX_ROWMAJOR;
  147. #if CM_DEBUG_MODE
  148. compileFlags |= D3DXSHADER_DEBUG;
  149. #endif
  150. switch (mOptimisationLevel)
  151. {
  152. case OPT_DEFAULT:
  153. compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL1;
  154. break;
  155. case OPT_NONE:
  156. compileFlags |= D3DXSHADER_SKIPOPTIMIZATION;
  157. break;
  158. case OPT_0:
  159. compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL0;
  160. break;
  161. case OPT_1:
  162. compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL1;
  163. break;
  164. case OPT_2:
  165. compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL2;
  166. break;
  167. case OPT_3:
  168. compileFlags |= D3DXSHADER_OPTIMIZATION_LEVEL3;
  169. break;
  170. }
  171. LPD3DXBUFFER errors = 0;
  172. // include handler
  173. HLSLIncludeHandler includeHandler(this);
  174. String hlslProfile = GpuProgramManager::instance().gpuProgProfileToRSSpecificProfile(mProfile);
  175. // Compile & assemble into microcode
  176. HRESULT hr = D3DXCompileShader(
  177. mSource.c_str(),
  178. static_cast<UINT>(mSource.length()),
  179. pDefines,
  180. &includeHandler,
  181. mEntryPoint.c_str(),
  182. hlslProfile.c_str(),
  183. compileFlags,
  184. &mpMicroCode,
  185. &errors,
  186. &mpConstTable);
  187. if (FAILED(hr))
  188. {
  189. String message = "Cannot assemble D3D9 high-level shader ";
  190. if( errors )
  191. {
  192. message += String(" Errors:\n") + static_cast<const char*>(errors->GetBufferPointer());
  193. errors->Release();
  194. }
  195. CM_EXCEPT(RenderingAPIException, message);
  196. }
  197. }
  198. //-----------------------------------------------------------------------
  199. void D3D9HLSLProgram::createLowLevelImpl(void)
  200. {
  201. if (!mCompileError)
  202. {
  203. String hlslProfile = GpuProgramManager::instance().gpuProgProfileToRSSpecificProfile(mProfile);
  204. // Create a low-level program, give it the same name as us
  205. mAssemblerProgram =
  206. GpuProgramManager::instance().createProgram(
  207. "",// dummy source, since we'll be using microcode
  208. "",
  209. hlslProfile,
  210. mType,
  211. GPP_NONE);
  212. static_cast<D3D9GpuProgram*>(mAssemblerProgram.get())->setExternalMicrocode(mpMicroCode);
  213. }
  214. }
  215. //-----------------------------------------------------------------------
  216. void D3D9HLSLProgram::unloadHighLevelImpl(void)
  217. {
  218. SAFE_RELEASE(mpMicroCode);
  219. SAFE_RELEASE(mpConstTable);
  220. }
  221. //-----------------------------------------------------------------------
  222. void D3D9HLSLProgram::buildConstantDefinitions() const
  223. {
  224. // Derive parameter names from const table
  225. assert(mpConstTable && "Program not loaded!");
  226. // Get contents of the constant table
  227. D3DXCONSTANTTABLE_DESC desc;
  228. HRESULT hr = mpConstTable->GetDesc(&desc);
  229. createParameterMappingStructures(true);
  230. if (FAILED(hr))
  231. {
  232. CM_EXCEPT(InternalErrorException, "Cannot retrieve constant descriptions from HLSL program.");
  233. }
  234. // Iterate over the constants
  235. for (unsigned int i = 0; i < desc.Constants; ++i)
  236. {
  237. // Recursively descend through the structure levels
  238. processParamElement(NULL, "", i);
  239. }
  240. }
  241. //-----------------------------------------------------------------------
  242. void D3D9HLSLProgram::processParamElement(D3DXHANDLE parent, String prefix,
  243. unsigned int index) const
  244. {
  245. D3DXHANDLE hConstant = mpConstTable->GetConstant(parent, index);
  246. // Since D3D HLSL doesn't deal with naming of array and struct parameters
  247. // automatically, we have to do it by hand
  248. D3DXCONSTANT_DESC desc;
  249. unsigned int numParams = 1;
  250. HRESULT hr = mpConstTable->GetConstantDesc(hConstant, &desc, &numParams);
  251. if (FAILED(hr))
  252. {
  253. CM_EXCEPT(InternalErrorException, "Cannot retrieve constant description from HLSL program.");
  254. }
  255. String paramName = desc.Name;
  256. // trim the odd '$' which appears at the start of the names in HLSL
  257. if (paramName.at(0) == '$')
  258. paramName.erase(paramName.begin());
  259. // Also trim the '[0]' suffix if it exists, we will add our own indexing later
  260. if (StringUtil::endsWith(paramName, "[0]", false))
  261. {
  262. paramName.erase(paramName.size() - 3);
  263. }
  264. if (desc.Class == D3DXPC_STRUCT)
  265. {
  266. // work out a new prefix for nested members, if it's an array, we need an index
  267. prefix = prefix + paramName + ".";
  268. // Cascade into struct
  269. for (unsigned int i = 0; i < desc.StructMembers; ++i)
  270. {
  271. processParamElement(hConstant, prefix, i);
  272. }
  273. }
  274. else
  275. {
  276. // Process params
  277. if (desc.Type == D3DXPT_FLOAT || desc.Type == D3DXPT_INT || desc.Type == D3DXPT_BOOL ||
  278. desc.Type == D3DXPT_SAMPLER1D || desc.Type == D3DXPT_SAMPLER2D || desc.Type == D3DXPT_SAMPLER3D || desc.Type == D3DXPT_SAMPLERCUBE)
  279. {
  280. UINT32 paramIndex = desc.RegisterIndex;
  281. String name = prefix + paramName;
  282. GpuConstantDefinition def;
  283. def.logicalIndex = paramIndex;
  284. // populate type, array size & element size
  285. populateDef(desc, def);
  286. if(def.isSampler())
  287. {
  288. def.physicalIndex = mSamplerLogicalToPhysical->bufferSize;
  289. CM_LOCK_MUTEX(mSamplerLogicalToPhysical->mutex)
  290. mSamplerLogicalToPhysical->map.insert(
  291. GpuLogicalIndexUseMap::value_type(paramIndex,
  292. GpuLogicalIndexUse(def.physicalIndex, def.arraySize, GPV_GLOBAL)));
  293. mSamplerLogicalToPhysical->bufferSize += def.arraySize;
  294. mConstantDefs->samplerCount = mSamplerLogicalToPhysical->bufferSize;
  295. }
  296. else
  297. {
  298. if (def.isFloat())
  299. {
  300. def.physicalIndex = mFloatLogicalToPhysical->bufferSize;
  301. CM_LOCK_MUTEX(mFloatLogicalToPhysical->mutex)
  302. mFloatLogicalToPhysical->map.insert(
  303. GpuLogicalIndexUseMap::value_type(paramIndex,
  304. GpuLogicalIndexUse(def.physicalIndex, def.arraySize * def.elementSize, GPV_GLOBAL)));
  305. mFloatLogicalToPhysical->bufferSize += def.arraySize * def.elementSize;
  306. mConstantDefs->floatBufferSize = mFloatLogicalToPhysical->bufferSize;
  307. }
  308. else
  309. {
  310. def.physicalIndex = mIntLogicalToPhysical->bufferSize;
  311. CM_LOCK_MUTEX(mIntLogicalToPhysical->mutex)
  312. mIntLogicalToPhysical->map.insert(
  313. GpuLogicalIndexUseMap::value_type(paramIndex,
  314. GpuLogicalIndexUse(def.physicalIndex, def.arraySize * def.elementSize, GPV_GLOBAL)));
  315. mIntLogicalToPhysical->bufferSize += def.arraySize * def.elementSize;
  316. mConstantDefs->intBufferSize = mIntLogicalToPhysical->bufferSize;
  317. }
  318. }
  319. mConstantDefs->map.insert(GpuConstantDefinitionMap::value_type(name, def));
  320. // Now deal with arrays
  321. mConstantDefs->generateConstantDefinitionArrayEntries(name, def);
  322. }
  323. }
  324. }
  325. //-----------------------------------------------------------------------
  326. void D3D9HLSLProgram::populateDef(D3DXCONSTANT_DESC& d3dDesc, GpuConstantDefinition& def) const
  327. {
  328. def.arraySize = d3dDesc.Elements;
  329. switch(d3dDesc.Type)
  330. {
  331. case D3DXPT_SAMPLER1D:
  332. def.constType = GCT_SAMPLER1D;
  333. break;
  334. case D3DXPT_SAMPLER2D:
  335. def.constType = GCT_SAMPLER2D;
  336. break;
  337. case D3DXPT_SAMPLER3D:
  338. def.constType = GCT_SAMPLER3D;
  339. break;
  340. case D3DXPT_SAMPLERCUBE:
  341. def.constType = GCT_SAMPLERCUBE;
  342. break;
  343. case D3DXPT_INT:
  344. switch(d3dDesc.Columns)
  345. {
  346. case 1:
  347. def.constType = GCT_INT1;
  348. break;
  349. case 2:
  350. def.constType = GCT_INT2;
  351. break;
  352. case 3:
  353. def.constType = GCT_INT3;
  354. break;
  355. case 4:
  356. def.constType = GCT_INT4;
  357. break;
  358. } // columns
  359. break;
  360. case D3DXPT_FLOAT:
  361. switch(d3dDesc.Class)
  362. {
  363. case D3DXPC_MATRIX_COLUMNS:
  364. case D3DXPC_MATRIX_ROWS:
  365. {
  366. int firstDim, secondDim;
  367. firstDim = d3dDesc.RegisterCount / d3dDesc.Elements;
  368. if (d3dDesc.Class == D3DXPC_MATRIX_ROWS)
  369. {
  370. secondDim = d3dDesc.Columns;
  371. }
  372. else
  373. {
  374. secondDim = d3dDesc.Rows;
  375. }
  376. switch(firstDim)
  377. {
  378. case 2:
  379. switch(secondDim)
  380. {
  381. case 2:
  382. def.constType = GCT_MATRIX_2X2;
  383. def.elementSize = 8; // HLSL always packs
  384. break;
  385. case 3:
  386. def.constType = GCT_MATRIX_2X3;
  387. def.elementSize = 8; // HLSL always packs
  388. break;
  389. case 4:
  390. def.constType = GCT_MATRIX_2X4;
  391. def.elementSize = 8;
  392. break;
  393. } // columns
  394. break;
  395. case 3:
  396. switch(secondDim)
  397. {
  398. case 2:
  399. def.constType = GCT_MATRIX_3X2;
  400. def.elementSize = 12; // HLSL always packs
  401. break;
  402. case 3:
  403. def.constType = GCT_MATRIX_3X3;
  404. def.elementSize = 12; // HLSL always packs
  405. break;
  406. case 4:
  407. def.constType = GCT_MATRIX_3X4;
  408. def.elementSize = 12;
  409. break;
  410. } // columns
  411. break;
  412. case 4:
  413. switch(secondDim)
  414. {
  415. case 2:
  416. def.constType = GCT_MATRIX_4X2;
  417. def.elementSize = 16; // HLSL always packs
  418. break;
  419. case 3:
  420. def.constType = GCT_MATRIX_4X3;
  421. def.elementSize = 16; // HLSL always packs
  422. break;
  423. case 4:
  424. def.constType = GCT_MATRIX_4X4;
  425. def.elementSize = 16;
  426. break;
  427. } // secondDim
  428. break;
  429. } // firstDim
  430. }
  431. break;
  432. case D3DXPC_SCALAR:
  433. case D3DXPC_VECTOR:
  434. switch(d3dDesc.Columns)
  435. {
  436. case 1:
  437. def.constType = GCT_FLOAT1;
  438. break;
  439. case 2:
  440. def.constType = GCT_FLOAT2;
  441. break;
  442. case 3:
  443. def.constType = GCT_FLOAT3;
  444. break;
  445. case 4:
  446. def.constType = GCT_FLOAT4;
  447. break;
  448. } // columns
  449. break;
  450. }
  451. default:
  452. // not mapping samplers, don't need to take the space
  453. break;
  454. };
  455. // D3D9 pads to 4 elements
  456. def.elementSize = GpuConstantDefinition::getElementSize(def.constType, true);
  457. }
  458. LPD3DXBUFFER D3D9HLSLProgram::getMicroCode()
  459. {
  460. return mpMicroCode;
  461. }
  462. //-----------------------------------------------------------------------
  463. D3D9HLSLProgram::D3D9HLSLProgram(const String& source, const String& entryPoint, const String& language,
  464. GpuProgramType gptype, GpuProgramProfile profile, bool isAdjacencyInfoRequired)
  465. : HighLevelGpuProgram(source, entryPoint, language, gptype, profile, isAdjacencyInfoRequired)
  466. , mPreprocessorDefines()
  467. , mColumnMajorMatrices(true)
  468. , mpMicroCode(NULL), mpConstTable(NULL)
  469. , mOptimisationLevel(OPT_DEFAULT)
  470. {
  471. }
  472. //-----------------------------------------------------------------------
  473. D3D9HLSLProgram::~D3D9HLSLProgram()
  474. {
  475. unloadHighLevel();
  476. }
  477. //-----------------------------------------------------------------------
  478. bool D3D9HLSLProgram::isSupported(void) const
  479. {
  480. if (mCompileError || !isRequiredCapabilitiesSupported())
  481. return false;
  482. String hlslProfile = GpuProgramManager::instance().gpuProgProfileToRSSpecificProfile(mProfile);
  483. RenderSystem* rs = CamelotEngine::RenderSystemManager::getActive();
  484. return rs->getCapabilities_internal()->isShaderProfileSupported(hlslProfile);
  485. }
  486. //-----------------------------------------------------------------------
  487. void D3D9HLSLProgram::createParameters_internal(AsyncOp& op)
  488. {
  489. // Call superclass
  490. HighLevelGpuProgram::createParameters_internal(op);
  491. GpuProgramParametersSharedPtr params = op.getReturnValue<GpuProgramParametersSharedPtr>();
  492. // Need to transpose matrices if compiled with column-major matrices
  493. params->setTransposeMatrices(mColumnMajorMatrices);
  494. }
  495. //-----------------------------------------------------------------------
  496. const String& D3D9HLSLProgram::getLanguage(void) const
  497. {
  498. static const String language = "hlsl";
  499. return language;
  500. }
  501. /************************************************************************/
  502. /* SERIALIZATION */
  503. /************************************************************************/
  504. RTTITypeBase* D3D9HLSLProgram::getRTTIStatic()
  505. {
  506. return D3D9HLSLProgramRTTI::instance();
  507. }
  508. RTTITypeBase* D3D9HLSLProgram::getRTTI() const
  509. {
  510. return D3D9HLSLProgram::getRTTIStatic();
  511. }
  512. }