d3d11-shader.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. /******************************************************************************
  2. Copyright (C) 2013 by Hugh Bailey <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ******************************************************************************/
  14. #include "d3d11-subsystem.hpp"
  15. #include "d3d11-shaderprocessor.hpp"
  16. #include <graphics/vec2.h>
  17. #include <graphics/vec3.h>
  18. #include <graphics/matrix3.h>
  19. #include <graphics/matrix4.h>
  20. void gs_vertex_shader::GetBuffersExpected(
  21. const vector<D3D11_INPUT_ELEMENT_DESC> &inputs)
  22. {
  23. for (size_t i = 0; i < inputs.size(); i++) {
  24. const D3D11_INPUT_ELEMENT_DESC &input = inputs[i];
  25. if (strcmp(input.SemanticName, "NORMAL") == 0)
  26. hasNormals = true;
  27. else if (strcmp(input.SemanticName, "TANGENT") == 0)
  28. hasTangents = true;
  29. else if (strcmp(input.SemanticName, "COLOR") == 0)
  30. hasColors = true;
  31. else if (strcmp(input.SemanticName, "TEXCOORD") == 0)
  32. nTexUnits++;
  33. }
  34. }
  35. gs_vertex_shader::gs_vertex_shader(gs_device_t *device, const char *file,
  36. const char *shaderString)
  37. : gs_shader (device, GS_SHADER_VERTEX),
  38. hasNormals (false),
  39. hasColors (false),
  40. hasTangents (false),
  41. nTexUnits (0)
  42. {
  43. vector<D3D11_INPUT_ELEMENT_DESC> inputs;
  44. ShaderProcessor processor(device);
  45. ComPtr<ID3D10Blob> shaderBlob;
  46. string outputString;
  47. HRESULT hr;
  48. processor.Process(shaderString, file);
  49. processor.BuildString(outputString);
  50. processor.BuildParams(params);
  51. processor.BuildInputLayout(inputs);
  52. GetBuffersExpected(inputs);
  53. BuildConstantBuffer();
  54. Compile(outputString.c_str(), file, "vs_4_0", shaderBlob.Assign());
  55. hr = device->device->CreateVertexShader(shaderBlob->GetBufferPointer(),
  56. shaderBlob->GetBufferSize(), NULL, shader.Assign());
  57. if (FAILED(hr))
  58. throw HRError("Failed to create vertex shader", hr);
  59. hr = device->device->CreateInputLayout(inputs.data(),
  60. (UINT)inputs.size(), shaderBlob->GetBufferPointer(),
  61. shaderBlob->GetBufferSize(), layout.Assign());
  62. if (FAILED(hr))
  63. throw HRError("Failed to create input layout", hr);
  64. viewProj = gs_shader_get_param_by_name(this, "ViewProj");
  65. world = gs_shader_get_param_by_name(this, "World");
  66. }
  67. gs_pixel_shader::gs_pixel_shader(gs_device_t *device, const char *file,
  68. const char *shaderString)
  69. : gs_shader(device, GS_SHADER_PIXEL)
  70. {
  71. ShaderProcessor processor(device);
  72. ComPtr<ID3D10Blob> shaderBlob;
  73. string outputString;
  74. HRESULT hr;
  75. processor.Process(shaderString, file);
  76. processor.BuildString(outputString);
  77. processor.BuildParams(params);
  78. processor.BuildSamplers(samplers);
  79. BuildConstantBuffer();
  80. Compile(outputString.c_str(), file, "ps_4_0", shaderBlob.Assign());
  81. hr = device->device->CreatePixelShader(shaderBlob->GetBufferPointer(),
  82. shaderBlob->GetBufferSize(), NULL, shader.Assign());
  83. if (FAILED(hr))
  84. throw HRError("Failed to create vertex shader", hr);
  85. }
  86. /*
  87. * Shader compilers will pack constants in to single registers when possible.
  88. * For example:
  89. *
  90. * uniform float3 test1;
  91. * uniform float test2;
  92. *
  93. * will inhabit a single constant register (c0.xyz for 'test1', and c0.w for
  94. * 'test2')
  95. *
  96. * However, if two constants cannot inhabit the same register, the second one
  97. * must begin at a new register, for example:
  98. *
  99. * uniform float2 test1;
  100. * uniform float3 test2;
  101. *
  102. * 'test1' will inhabit register constant c0.xy. However, because there's no
  103. * room for 'test2, it must use a new register constant entirely (c1.xyz).
  104. *
  105. * So if we want to calculate the position of the constants in the constant
  106. * buffer, we must take this in to account.
  107. */
  108. void gs_shader::BuildConstantBuffer()
  109. {
  110. for (size_t i = 0; i < params.size(); i++) {
  111. gs_shader_param &param = params[i];
  112. size_t size = 0;
  113. switch (param.type) {
  114. case GS_SHADER_PARAM_BOOL:
  115. case GS_SHADER_PARAM_INT:
  116. case GS_SHADER_PARAM_FLOAT: size = sizeof(float); break;
  117. case GS_SHADER_PARAM_VEC2: size = sizeof(vec2); break;
  118. case GS_SHADER_PARAM_VEC3: size = sizeof(float)*3; break;
  119. case GS_SHADER_PARAM_VEC4: size = sizeof(vec4); break;
  120. case GS_SHADER_PARAM_MATRIX4X4:
  121. size = sizeof(float)*4*4;
  122. break;
  123. case GS_SHADER_PARAM_TEXTURE:
  124. case GS_SHADER_PARAM_STRING:
  125. case GS_SHADER_PARAM_UNKNOWN:
  126. continue;
  127. }
  128. /* checks to see if this constant needs to start at a new
  129. * register */
  130. if (size && (constantSize & 15) != 0) {
  131. size_t alignMax = (constantSize + 15) & ~15;
  132. if ((size + constantSize) > alignMax)
  133. constantSize = alignMax;
  134. }
  135. param.pos = constantSize;
  136. constantSize += size;
  137. }
  138. if (constantSize) {
  139. D3D11_BUFFER_DESC bd;
  140. HRESULT hr;
  141. memset(&bd, 0, sizeof(bd));
  142. bd.ByteWidth = (constantSize+15)&0xFFFFFFF0; /* align */
  143. bd.Usage = D3D11_USAGE_DYNAMIC;
  144. bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
  145. bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  146. hr = device->device->CreateBuffer(&bd, NULL,
  147. constants.Assign());
  148. if (FAILED(hr))
  149. throw HRError("Failed to create constant buffer", hr);
  150. }
  151. for (size_t i = 0; i < params.size(); i++)
  152. gs_shader_set_default(&params[i]);
  153. }
  154. void gs_shader::Compile(const char *shaderString, const char *file,
  155. const char *target, ID3D10Blob **shader)
  156. {
  157. ComPtr<ID3D10Blob> errorsBlob;
  158. HRESULT hr;
  159. if (!shaderString)
  160. throw "No shader string specified";
  161. hr = device->d3dCompile(shaderString, strlen(shaderString), file, NULL,
  162. NULL, "main", target,
  163. D3D10_SHADER_OPTIMIZATION_LEVEL1, 0,
  164. shader, errorsBlob.Assign());
  165. if (FAILED(hr)) {
  166. if (errorsBlob != NULL && errorsBlob->GetBufferSize())
  167. throw ShaderError(errorsBlob, hr);
  168. else
  169. throw HRError("Failed to compile shader", hr);
  170. }
  171. }
  172. inline void gs_shader::UpdateParam(vector<uint8_t> &constData,
  173. gs_shader_param &param, bool &upload)
  174. {
  175. if (param.type != GS_SHADER_PARAM_TEXTURE) {
  176. if (!param.curValue.size())
  177. throw "Not all shader parameters were set";
  178. /* padding in case the constant needs to start at a new
  179. * register */
  180. if (param.pos > constData.size()) {
  181. uint8_t zero = 0;
  182. constData.insert(constData.end(),
  183. param.pos - constData.size(), zero);
  184. }
  185. constData.insert(constData.end(),
  186. param.curValue.begin(),
  187. param.curValue.end());
  188. if (param.changed) {
  189. upload = true;
  190. param.changed = false;
  191. }
  192. } else if (param.curValue.size() == sizeof(gs_texture_t*)) {
  193. gs_texture_t *tex;
  194. memcpy(&tex, param.curValue.data(), sizeof(gs_texture_t*));
  195. device_load_texture(device, tex, param.textureID);
  196. if (param.nextSampler) {
  197. ID3D11SamplerState *state = param.nextSampler->state;
  198. device->context->PSSetSamplers(param.textureID, 1,
  199. &state);
  200. param.nextSampler = nullptr;
  201. }
  202. }
  203. }
  204. void gs_shader::UploadParams()
  205. {
  206. vector<uint8_t> constData;
  207. bool upload = false;
  208. constData.reserve(constantSize);
  209. for (size_t i = 0; i < params.size(); i++)
  210. UpdateParam(constData, params[i], upload);
  211. if (constData.size() != constantSize)
  212. throw "Invalid constant data size given to shader";
  213. if (upload) {
  214. D3D11_MAPPED_SUBRESOURCE map;
  215. HRESULT hr;
  216. hr = device->context->Map(constants, 0, D3D11_MAP_WRITE_DISCARD,
  217. 0, &map);
  218. if (FAILED(hr))
  219. throw HRError("Could not lock constant buffer", hr);
  220. memcpy(map.pData, constData.data(), constData.size());
  221. device->context->Unmap(constants, 0);
  222. }
  223. }
  224. void gs_shader_destroy(gs_shader_t *shader)
  225. {
  226. delete shader;
  227. }
  228. int gs_shader_get_num_params(const gs_shader_t *shader)
  229. {
  230. return (int)shader->params.size();
  231. }
  232. gs_sparam_t *gs_shader_get_param_by_idx(gs_shader_t *shader, uint32_t param)
  233. {
  234. return &shader->params[param];
  235. }
  236. gs_sparam_t *gs_shader_get_param_by_name(gs_shader_t *shader, const char *name)
  237. {
  238. for (size_t i = 0; i < shader->params.size(); i++) {
  239. gs_shader_param &param = shader->params[i];
  240. if (strcmp(param.name.c_str(), name) == 0)
  241. return &param;
  242. }
  243. return NULL;
  244. }
  245. gs_sparam_t *gs_shader_get_viewproj_matrix(const gs_shader_t *shader)
  246. {
  247. if (shader->type != GS_SHADER_VERTEX)
  248. return NULL;
  249. return static_cast<const gs_vertex_shader*>(shader)->viewProj;
  250. }
  251. gs_sparam_t *gs_shader_get_world_matrix(const gs_shader_t *shader)
  252. {
  253. if (shader->type != GS_SHADER_VERTEX)
  254. return NULL;
  255. return static_cast<const gs_vertex_shader*>(shader)->world;
  256. }
  257. void gs_shader_get_param_info(const gs_sparam_t *param,
  258. struct gs_shader_param_info *info)
  259. {
  260. if (!param)
  261. return;
  262. info->name = param->name.c_str();
  263. info->type = param->type;
  264. }
  265. static inline void shader_setval_inline(gs_shader_param *param,
  266. const void *data, size_t size)
  267. {
  268. assert(param);
  269. if (!param)
  270. return;
  271. bool size_changed = param->curValue.size() != size;
  272. if (size_changed)
  273. param->curValue.resize(size);
  274. if (size_changed || memcmp(param->curValue.data(), data, size) != 0) {
  275. memcpy(param->curValue.data(), data, size);
  276. param->changed = true;
  277. }
  278. }
  279. void gs_shader_set_bool(gs_sparam_t *param, bool val)
  280. {
  281. int b_val = (int)val;
  282. shader_setval_inline(param, &b_val, sizeof(int));
  283. }
  284. void gs_shader_set_float(gs_sparam_t *param, float val)
  285. {
  286. shader_setval_inline(param, &val, sizeof(float));
  287. }
  288. void gs_shader_set_int(gs_sparam_t *param, int val)
  289. {
  290. shader_setval_inline(param, &val, sizeof(int));
  291. }
  292. void gs_shader_set_matrix3(gs_sparam_t *param, const struct matrix3 *val)
  293. {
  294. struct matrix4 mat;
  295. matrix4_from_matrix3(&mat, val);
  296. shader_setval_inline(param, &mat, sizeof(matrix4));
  297. }
  298. void gs_shader_set_matrix4(gs_sparam_t *param, const struct matrix4 *val)
  299. {
  300. shader_setval_inline(param, val, sizeof(matrix4));
  301. }
  302. void gs_shader_set_vec2(gs_sparam_t *param, const struct vec2 *val)
  303. {
  304. shader_setval_inline(param, val, sizeof(vec2));
  305. }
  306. void gs_shader_set_vec3(gs_sparam_t *param, const struct vec3 *val)
  307. {
  308. shader_setval_inline(param, val, sizeof(float) * 3);
  309. }
  310. void gs_shader_set_vec4(gs_sparam_t *param, const struct vec4 *val)
  311. {
  312. shader_setval_inline(param, val, sizeof(vec4));
  313. }
  314. void gs_shader_set_texture(gs_sparam_t *param, gs_texture_t *val)
  315. {
  316. shader_setval_inline(param, &val, sizeof(gs_texture_t*));
  317. }
  318. void gs_shader_set_val(gs_sparam_t *param, const void *val, size_t size)
  319. {
  320. shader_setval_inline(param, val, size);
  321. }
  322. void gs_shader_set_default(gs_sparam_t *param)
  323. {
  324. if (param->defaultValue.size())
  325. shader_setval_inline(param, param->defaultValue.data(),
  326. param->defaultValue.size());
  327. }
  328. void gs_shader_set_next_sampler(gs_sparam_t *param, gs_samplerstate_t *sampler)
  329. {
  330. param->nextSampler = sampler;
  331. }