CmD3D9HLSLProgram.cpp 18 KB

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