CmD3D9HLSLProgram.cpp 18 KB

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