CmD3D9HLSLProgram.cpp 17 KB

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