shader_rd.cpp 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  1. /**************************************************************************/
  2. /* shader_rd.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "shader_rd.h"
  31. #include "core/io/dir_access.h"
  32. #include "core/io/file_access.h"
  33. #include "core/object/worker_thread_pool.h"
  34. #include "core/version.h"
  35. #include "servers/rendering/rendering_device.h"
  36. #include "servers/rendering/shader_include_db.h"
  37. #define ENABLE_SHADER_CACHE 1
  38. void ShaderRD::_add_stage(const char *p_code, StageType p_stage_type) {
  39. Vector<String> lines = String(p_code).split("\n");
  40. String text;
  41. int line_count = lines.size();
  42. for (int i = 0; i < line_count; i++) {
  43. const String &l = lines[i];
  44. bool push_chunk = false;
  45. StageTemplate::Chunk chunk;
  46. if (l.begins_with("#VERSION_DEFINES")) {
  47. chunk.type = StageTemplate::Chunk::TYPE_VERSION_DEFINES;
  48. push_chunk = true;
  49. } else if (l.begins_with("#GLOBALS")) {
  50. switch (p_stage_type) {
  51. case STAGE_TYPE_VERTEX:
  52. chunk.type = StageTemplate::Chunk::TYPE_VERTEX_GLOBALS;
  53. break;
  54. case STAGE_TYPE_FRAGMENT:
  55. chunk.type = StageTemplate::Chunk::TYPE_FRAGMENT_GLOBALS;
  56. break;
  57. case STAGE_TYPE_COMPUTE:
  58. chunk.type = StageTemplate::Chunk::TYPE_COMPUTE_GLOBALS;
  59. break;
  60. default: {
  61. }
  62. }
  63. push_chunk = true;
  64. } else if (l.begins_with("#MATERIAL_UNIFORMS")) {
  65. chunk.type = StageTemplate::Chunk::TYPE_MATERIAL_UNIFORMS;
  66. push_chunk = true;
  67. } else if (l.begins_with("#CODE")) {
  68. chunk.type = StageTemplate::Chunk::TYPE_CODE;
  69. push_chunk = true;
  70. chunk.code = l.replace_first("#CODE", String()).remove_char(':').strip_edges().to_upper();
  71. } else if (l.begins_with("#include ")) {
  72. String include_file = l.replace("#include ", "").strip_edges();
  73. if (include_file[0] == '"') {
  74. int end_pos = include_file.find_char('"', 1);
  75. if (end_pos >= 0) {
  76. include_file = include_file.substr(1, end_pos - 1);
  77. String include_code = ShaderIncludeDB::get_built_in_include_file(include_file);
  78. if (!include_code.is_empty()) {
  79. // Add these lines into our parse list so we parse them as well.
  80. Vector<String> include_lines = include_code.split("\n");
  81. for (int j = include_lines.size() - 1; j >= 0; j--) {
  82. lines.insert(i + 1, include_lines[j]);
  83. }
  84. line_count = lines.size();
  85. } else {
  86. // Add it in as is.
  87. text += l + "\n";
  88. }
  89. } else {
  90. // Add it in as is.
  91. text += l + "\n";
  92. }
  93. } else {
  94. // Add it in as is.
  95. text += l + "\n";
  96. }
  97. } else {
  98. text += l + "\n";
  99. }
  100. if (push_chunk) {
  101. if (!text.is_empty()) {
  102. StageTemplate::Chunk text_chunk;
  103. text_chunk.type = StageTemplate::Chunk::TYPE_TEXT;
  104. text_chunk.text = text.utf8();
  105. stage_templates[p_stage_type].chunks.push_back(text_chunk);
  106. text = String();
  107. }
  108. stage_templates[p_stage_type].chunks.push_back(chunk);
  109. }
  110. }
  111. if (!text.is_empty()) {
  112. StageTemplate::Chunk text_chunk;
  113. text_chunk.type = StageTemplate::Chunk::TYPE_TEXT;
  114. text_chunk.text = text.utf8();
  115. stage_templates[p_stage_type].chunks.push_back(text_chunk);
  116. text = String();
  117. }
  118. }
  119. void ShaderRD::setup(const char *p_vertex_code, const char *p_fragment_code, const char *p_compute_code, const char *p_name) {
  120. name = p_name;
  121. if (p_compute_code) {
  122. _add_stage(p_compute_code, STAGE_TYPE_COMPUTE);
  123. is_compute = true;
  124. } else {
  125. is_compute = false;
  126. if (p_vertex_code) {
  127. _add_stage(p_vertex_code, STAGE_TYPE_VERTEX);
  128. }
  129. if (p_fragment_code) {
  130. _add_stage(p_fragment_code, STAGE_TYPE_FRAGMENT);
  131. }
  132. }
  133. StringBuilder tohash;
  134. tohash.append("[GodotVersionNumber]");
  135. tohash.append(GODOT_VERSION_NUMBER);
  136. tohash.append("[GodotVersionHash]");
  137. tohash.append(GODOT_VERSION_HASH);
  138. tohash.append("[Vertex]");
  139. tohash.append(p_vertex_code ? p_vertex_code : "");
  140. tohash.append("[Fragment]");
  141. tohash.append(p_fragment_code ? p_fragment_code : "");
  142. tohash.append("[Compute]");
  143. tohash.append(p_compute_code ? p_compute_code : "");
  144. base_sha256 = tohash.as_string().sha256_text();
  145. }
  146. RID ShaderRD::version_create(bool p_embedded) {
  147. //initialize() was never called
  148. ERR_FAIL_COND_V(group_to_variant_map.is_empty(), RID());
  149. Version version;
  150. version.dirty = true;
  151. version.valid = false;
  152. version.initialize_needed = true;
  153. version.embedded = p_embedded;
  154. version.variants.clear();
  155. version.variant_data.clear();
  156. version.mutex = memnew(Mutex);
  157. RID rid = version_owner.make_rid(version);
  158. {
  159. MutexLock lock(versions_mutex);
  160. version_mutexes.insert(rid, version.mutex);
  161. }
  162. if (p_embedded) {
  163. MutexLock lock(shader_versions_embedded_set_mutex);
  164. shader_versions_embedded_set.insert({ this, rid });
  165. }
  166. return rid;
  167. }
  168. void ShaderRD::_initialize_version(Version *p_version) {
  169. _clear_version(p_version);
  170. p_version->valid = false;
  171. p_version->dirty = false;
  172. p_version->variants.resize_initialized(variant_defines.size());
  173. p_version->variant_data.resize(variant_defines.size());
  174. p_version->group_compilation_tasks.resize_initialized(group_enabled.size());
  175. }
  176. void ShaderRD::_clear_version(Version *p_version) {
  177. _compile_ensure_finished(p_version);
  178. // Clear versions if they exist.
  179. if (!p_version->variants.is_empty()) {
  180. for (int i = 0; i < variant_defines.size(); i++) {
  181. if (p_version->variants[i].is_valid()) {
  182. RD::get_singleton()->free(p_version->variants[i]);
  183. }
  184. }
  185. p_version->variants.clear();
  186. p_version->variant_data.clear();
  187. }
  188. }
  189. void ShaderRD::_build_variant_code(StringBuilder &builder, uint32_t p_variant, const Version *p_version, const StageTemplate &p_template) {
  190. for (const StageTemplate::Chunk &chunk : p_template.chunks) {
  191. switch (chunk.type) {
  192. case StageTemplate::Chunk::TYPE_VERSION_DEFINES: {
  193. builder.append("\n"); //make sure defines begin at newline
  194. builder.append(general_defines.get_data());
  195. builder.append(variant_defines[p_variant].text.get_data());
  196. for (int j = 0; j < p_version->custom_defines.size(); j++) {
  197. builder.append(p_version->custom_defines[j].get_data());
  198. }
  199. builder.append("\n"); //make sure defines begin at newline
  200. if (p_version->uniforms.size()) {
  201. builder.append("#define MATERIAL_UNIFORMS_USED\n");
  202. }
  203. for (const KeyValue<StringName, CharString> &E : p_version->code_sections) {
  204. builder.append(String("#define ") + String(E.key) + "_CODE_USED\n");
  205. }
  206. #if (defined(MACOS_ENABLED) || defined(APPLE_EMBEDDED_ENABLED))
  207. RenderingDevice *rd = RD::get_singleton();
  208. if (rd->get_device_capabilities().device_family == RDD::DEVICE_VULKAN) {
  209. builder.append("#define MOLTENVK_USED\n");
  210. }
  211. if (!rd->has_feature(RD::SUPPORTS_IMAGE_ATOMIC_32_BIT)) {
  212. builder.append("#define NO_IMAGE_ATOMICS\n");
  213. }
  214. #endif
  215. builder.append(String("#define RENDER_DRIVER_") + OS::get_singleton()->get_current_rendering_driver_name().to_upper() + "\n");
  216. builder.append("#define samplerExternalOES sampler2D\n");
  217. builder.append("#define textureExternalOES texture2D\n");
  218. } break;
  219. case StageTemplate::Chunk::TYPE_MATERIAL_UNIFORMS: {
  220. builder.append(p_version->uniforms.get_data()); //uniforms (same for vertex and fragment)
  221. } break;
  222. case StageTemplate::Chunk::TYPE_VERTEX_GLOBALS: {
  223. builder.append(p_version->vertex_globals.get_data()); // vertex globals
  224. } break;
  225. case StageTemplate::Chunk::TYPE_FRAGMENT_GLOBALS: {
  226. builder.append(p_version->fragment_globals.get_data()); // fragment globals
  227. } break;
  228. case StageTemplate::Chunk::TYPE_COMPUTE_GLOBALS: {
  229. builder.append(p_version->compute_globals.get_data()); // compute globals
  230. } break;
  231. case StageTemplate::Chunk::TYPE_CODE: {
  232. if (p_version->code_sections.has(chunk.code)) {
  233. builder.append(p_version->code_sections[chunk.code].get_data());
  234. }
  235. } break;
  236. case StageTemplate::Chunk::TYPE_TEXT: {
  237. builder.append(chunk.text.get_data());
  238. } break;
  239. }
  240. }
  241. }
  242. Vector<String> ShaderRD::_build_variant_stage_sources(uint32_t p_variant, CompileData p_data) {
  243. if (!variants_enabled[p_variant]) {
  244. return Vector<String>(); // Variant is disabled, return.
  245. }
  246. Vector<String> stage_sources;
  247. stage_sources.resize(RD::SHADER_STAGE_MAX);
  248. if (is_compute) {
  249. // Compute stage.
  250. StringBuilder builder;
  251. _build_variant_code(builder, p_variant, p_data.version, stage_templates[STAGE_TYPE_COMPUTE]);
  252. stage_sources.write[RD::SHADER_STAGE_COMPUTE] = builder.as_string();
  253. } else {
  254. {
  255. // Vertex stage.
  256. StringBuilder builder;
  257. _build_variant_code(builder, p_variant, p_data.version, stage_templates[STAGE_TYPE_VERTEX]);
  258. stage_sources.write[RD::SHADER_STAGE_VERTEX] = builder.as_string();
  259. }
  260. {
  261. // Fragment stage.
  262. StringBuilder builder;
  263. _build_variant_code(builder, p_variant, p_data.version, stage_templates[STAGE_TYPE_FRAGMENT]);
  264. stage_sources.write[RD::SHADER_STAGE_FRAGMENT] = builder.as_string();
  265. }
  266. }
  267. return stage_sources;
  268. }
  269. void ShaderRD::_compile_variant(uint32_t p_variant, CompileData p_data) {
  270. uint32_t variant = group_to_variant_map[p_data.group][p_variant];
  271. if (!variants_enabled[variant]) {
  272. return; // Variant is disabled, return.
  273. }
  274. Vector<String> variant_stage_sources = _build_variant_stage_sources(variant, p_data);
  275. Vector<RD::ShaderStageSPIRVData> variant_stages = compile_stages(variant_stage_sources);
  276. ERR_FAIL_COND(variant_stages.is_empty());
  277. Vector<uint8_t> shader_data = RD::get_singleton()->shader_compile_binary_from_spirv(variant_stages, name + ":" + itos(variant));
  278. ERR_FAIL_COND(shader_data.is_empty());
  279. {
  280. p_data.version->variants.write[variant] = RD::get_singleton()->shader_create_from_bytecode_with_samplers(shader_data, p_data.version->variants[variant], immutable_samplers);
  281. p_data.version->variant_data.write[variant] = shader_data;
  282. }
  283. }
  284. Vector<String> ShaderRD::version_build_variant_stage_sources(RID p_version, int p_variant) {
  285. Version *version = version_owner.get_or_null(p_version);
  286. ERR_FAIL_NULL_V(version, Vector<String>());
  287. if (version->dirty) {
  288. _initialize_version(version);
  289. }
  290. CompileData compile_data;
  291. compile_data.version = version;
  292. compile_data.group = variant_to_group[p_variant];
  293. return _build_variant_stage_sources(p_variant, compile_data);
  294. }
  295. RS::ShaderNativeSourceCode ShaderRD::version_get_native_source_code(RID p_version) {
  296. Version *version = version_owner.get_or_null(p_version);
  297. RS::ShaderNativeSourceCode source_code;
  298. ERR_FAIL_NULL_V(version, source_code);
  299. MutexLock lock(*version->mutex);
  300. source_code.versions.resize(variant_defines.size());
  301. for (int i = 0; i < source_code.versions.size(); i++) {
  302. if (!is_compute) {
  303. //vertex stage
  304. StringBuilder builder;
  305. _build_variant_code(builder, i, version, stage_templates[STAGE_TYPE_VERTEX]);
  306. RS::ShaderNativeSourceCode::Version::Stage stage;
  307. stage.name = "vertex";
  308. stage.code = builder.as_string();
  309. source_code.versions.write[i].stages.push_back(stage);
  310. }
  311. if (!is_compute) {
  312. //fragment stage
  313. StringBuilder builder;
  314. _build_variant_code(builder, i, version, stage_templates[STAGE_TYPE_FRAGMENT]);
  315. RS::ShaderNativeSourceCode::Version::Stage stage;
  316. stage.name = "fragment";
  317. stage.code = builder.as_string();
  318. source_code.versions.write[i].stages.push_back(stage);
  319. }
  320. if (is_compute) {
  321. //compute stage
  322. StringBuilder builder;
  323. _build_variant_code(builder, i, version, stage_templates[STAGE_TYPE_COMPUTE]);
  324. RS::ShaderNativeSourceCode::Version::Stage stage;
  325. stage.name = "compute";
  326. stage.code = builder.as_string();
  327. source_code.versions.write[i].stages.push_back(stage);
  328. }
  329. }
  330. return source_code;
  331. }
  332. String ShaderRD::version_get_cache_file_relative_path(RID p_version, int p_group, const String &p_api_name) {
  333. Version *version = version_owner.get_or_null(p_version);
  334. ERR_FAIL_NULL_V(version, String());
  335. return _get_cache_file_relative_path(version, p_group, p_api_name);
  336. }
  337. String ShaderRD::_version_get_sha1(Version *p_version) const {
  338. StringBuilder hash_build;
  339. hash_build.append("[uniforms]");
  340. hash_build.append(p_version->uniforms.get_data());
  341. hash_build.append("[vertex_globals]");
  342. hash_build.append(p_version->vertex_globals.get_data());
  343. hash_build.append("[fragment_globals]");
  344. hash_build.append(p_version->fragment_globals.get_data());
  345. hash_build.append("[compute_globals]");
  346. hash_build.append(p_version->compute_globals.get_data());
  347. Vector<StringName> code_sections;
  348. for (const KeyValue<StringName, CharString> &E : p_version->code_sections) {
  349. code_sections.push_back(E.key);
  350. }
  351. code_sections.sort_custom<StringName::AlphCompare>();
  352. for (int i = 0; i < code_sections.size(); i++) {
  353. hash_build.append(String("[code:") + String(code_sections[i]) + "]");
  354. hash_build.append(p_version->code_sections[code_sections[i]].get_data());
  355. }
  356. for (int i = 0; i < p_version->custom_defines.size(); i++) {
  357. hash_build.append("[custom_defines:" + itos(i) + "]");
  358. hash_build.append(p_version->custom_defines[i].get_data());
  359. }
  360. return hash_build.as_string().sha1_text();
  361. }
  362. static const char *shader_file_header = "GDSC";
  363. static const uint32_t cache_file_version = 4;
  364. String ShaderRD::_get_cache_file_relative_path(Version *p_version, int p_group, const String &p_api_name) {
  365. String sha1 = _version_get_sha1(p_version);
  366. return name.path_join(group_sha256[p_group]).path_join(sha1) + "." + p_api_name + ".cache";
  367. }
  368. String ShaderRD::_get_cache_file_path(Version *p_version, int p_group, const String &p_api_name, bool p_user_dir) {
  369. const String &shader_cache_dir = p_user_dir ? shader_cache_user_dir : shader_cache_res_dir;
  370. String relative_path = _get_cache_file_relative_path(p_version, p_group, p_api_name);
  371. return shader_cache_dir.path_join(relative_path);
  372. }
  373. bool ShaderRD::_load_from_cache(Version *p_version, int p_group) {
  374. String api_safe_name = String(RD::get_singleton()->get_device_api_name()).validate_filename().to_lower();
  375. Ref<FileAccess> f;
  376. if (shader_cache_user_dir_valid) {
  377. f = FileAccess::open(_get_cache_file_path(p_version, p_group, api_safe_name, true), FileAccess::READ);
  378. }
  379. if (f.is_null()) {
  380. f = FileAccess::open(_get_cache_file_path(p_version, p_group, api_safe_name, false), FileAccess::READ);
  381. }
  382. if (f.is_null()) {
  383. const String &sha1 = _version_get_sha1(p_version);
  384. print_verbose(vformat("Shader cache miss for %s", name.path_join(group_sha256[p_group]).path_join(sha1)));
  385. return false;
  386. }
  387. char header[5] = { 0, 0, 0, 0, 0 };
  388. f->get_buffer((uint8_t *)header, 4);
  389. ERR_FAIL_COND_V(header != String(shader_file_header), false);
  390. uint32_t file_version = f->get_32();
  391. if (file_version != cache_file_version) {
  392. return false; // wrong version
  393. }
  394. uint32_t variant_count = f->get_32();
  395. ERR_FAIL_COND_V(variant_count != (uint32_t)group_to_variant_map[p_group].size(), false); //should not happen but check
  396. for (uint32_t i = 0; i < variant_count; i++) {
  397. int variant_id = group_to_variant_map[p_group][i];
  398. uint32_t variant_size = f->get_32();
  399. ERR_FAIL_COND_V(variant_size == 0 && variants_enabled[variant_id], false);
  400. if (!variants_enabled[variant_id]) {
  401. continue;
  402. }
  403. Vector<uint8_t> variant_bytes;
  404. variant_bytes.resize(variant_size);
  405. uint32_t br = f->get_buffer(variant_bytes.ptrw(), variant_size);
  406. ERR_FAIL_COND_V(br != variant_size, false);
  407. p_version->variant_data.write[variant_id] = variant_bytes;
  408. }
  409. for (uint32_t i = 0; i < variant_count; i++) {
  410. int variant_id = group_to_variant_map[p_group][i];
  411. if (!variants_enabled[variant_id]) {
  412. p_version->variants.write[variant_id] = RID();
  413. continue;
  414. }
  415. {
  416. RID shader = RD::get_singleton()->shader_create_from_bytecode_with_samplers(p_version->variant_data[variant_id], p_version->variants[variant_id], immutable_samplers);
  417. if (shader.is_null()) {
  418. for (uint32_t j = 0; j < i; j++) {
  419. int variant_free_id = group_to_variant_map[p_group][j];
  420. RD::get_singleton()->free(p_version->variants[variant_free_id]);
  421. }
  422. ERR_FAIL_COND_V(shader.is_null(), false);
  423. }
  424. p_version->variants.write[variant_id] = shader;
  425. }
  426. }
  427. p_version->valid = true;
  428. return true;
  429. }
  430. void ShaderRD::_save_to_cache(Version *p_version, int p_group) {
  431. ERR_FAIL_COND(!shader_cache_user_dir_valid);
  432. String api_safe_name = String(RD::get_singleton()->get_device_api_name()).validate_filename().to_lower();
  433. const String &path = _get_cache_file_path(p_version, p_group, api_safe_name, true);
  434. Ref<FileAccess> f = FileAccess::open(path, FileAccess::WRITE);
  435. ERR_FAIL_COND(f.is_null());
  436. PackedByteArray shader_cache_bytes = ShaderRD::save_shader_cache_bytes(group_to_variant_map[p_group], p_version->variant_data);
  437. f->store_buffer(shader_cache_bytes);
  438. }
  439. void ShaderRD::_allocate_placeholders(Version *p_version, int p_group) {
  440. ERR_FAIL_COND(p_version->variants.is_empty());
  441. for (uint32_t i = 0; i < group_to_variant_map[p_group].size(); i++) {
  442. int variant_id = group_to_variant_map[p_group][i];
  443. RID shader = RD::get_singleton()->shader_create_placeholder();
  444. {
  445. p_version->variants.write[variant_id] = shader;
  446. }
  447. }
  448. }
  449. // Try to compile all variants for a given group.
  450. // Will skip variants that are disabled.
  451. void ShaderRD::_compile_version_start(Version *p_version, int p_group) {
  452. if (!group_enabled[p_group]) {
  453. return;
  454. }
  455. p_version->dirty = false;
  456. #if ENABLE_SHADER_CACHE
  457. if (_load_from_cache(p_version, p_group)) {
  458. return;
  459. }
  460. #endif
  461. CompileData compile_data;
  462. compile_data.version = p_version;
  463. compile_data.group = p_group;
  464. WorkerThreadPool::GroupID group_task = WorkerThreadPool::get_singleton()->add_template_group_task(this, &ShaderRD::_compile_variant, compile_data, group_to_variant_map[p_group].size(), -1, true, SNAME("ShaderCompilation"));
  465. p_version->group_compilation_tasks.write[p_group] = group_task;
  466. }
  467. void ShaderRD::_compile_version_end(Version *p_version, int p_group) {
  468. if (p_version->group_compilation_tasks.size() <= p_group || p_version->group_compilation_tasks[p_group] == 0) {
  469. return;
  470. }
  471. WorkerThreadPool::GroupID group_task = p_version->group_compilation_tasks[p_group];
  472. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(group_task);
  473. p_version->group_compilation_tasks.write[p_group] = 0;
  474. bool all_valid = true;
  475. for (uint32_t i = 0; i < group_to_variant_map[p_group].size(); i++) {
  476. int variant_id = group_to_variant_map[p_group][i];
  477. if (!variants_enabled[variant_id]) {
  478. continue; // Disabled.
  479. }
  480. if (p_version->variants[variant_id].is_null()) {
  481. all_valid = false;
  482. break;
  483. }
  484. }
  485. if (!all_valid) {
  486. // Clear versions if they exist.
  487. for (int i = 0; i < variant_defines.size(); i++) {
  488. if (!variants_enabled[i] || !group_enabled[variant_defines[i].group]) {
  489. continue; // Disabled.
  490. }
  491. if (!p_version->variants[i].is_null()) {
  492. RD::get_singleton()->free(p_version->variants[i]);
  493. }
  494. }
  495. p_version->variants.clear();
  496. p_version->variant_data.clear();
  497. return;
  498. }
  499. #if ENABLE_SHADER_CACHE
  500. else if (shader_cache_user_dir_valid) {
  501. _save_to_cache(p_version, p_group);
  502. }
  503. #endif
  504. p_version->valid = true;
  505. }
  506. void ShaderRD::_compile_ensure_finished(Version *p_version) {
  507. // Wait for compilation of existing groups if necessary.
  508. for (int i = 0; i < group_enabled.size(); i++) {
  509. _compile_version_end(p_version, i);
  510. }
  511. }
  512. void ShaderRD::version_set_code(RID p_version, const HashMap<String, String> &p_code, const String &p_uniforms, const String &p_vertex_globals, const String &p_fragment_globals, const Vector<String> &p_custom_defines) {
  513. ERR_FAIL_COND(is_compute);
  514. Version *version = version_owner.get_or_null(p_version);
  515. ERR_FAIL_NULL(version);
  516. MutexLock lock(*version->mutex);
  517. _compile_ensure_finished(version);
  518. version->vertex_globals = p_vertex_globals.utf8();
  519. version->fragment_globals = p_fragment_globals.utf8();
  520. version->uniforms = p_uniforms.utf8();
  521. version->code_sections.clear();
  522. for (const KeyValue<String, String> &E : p_code) {
  523. version->code_sections[StringName(E.key.to_upper())] = E.value.utf8();
  524. }
  525. version->custom_defines.clear();
  526. for (int i = 0; i < p_custom_defines.size(); i++) {
  527. version->custom_defines.push_back(p_custom_defines[i].utf8());
  528. }
  529. version->dirty = true;
  530. if (version->initialize_needed) {
  531. _initialize_version(version);
  532. for (int i = 0; i < group_enabled.size(); i++) {
  533. if (!group_enabled[i]) {
  534. _allocate_placeholders(version, i);
  535. continue;
  536. }
  537. _compile_version_start(version, i);
  538. }
  539. version->initialize_needed = false;
  540. }
  541. }
  542. void ShaderRD::version_set_compute_code(RID p_version, const HashMap<String, String> &p_code, const String &p_uniforms, const String &p_compute_globals, const Vector<String> &p_custom_defines) {
  543. ERR_FAIL_COND(!is_compute);
  544. Version *version = version_owner.get_or_null(p_version);
  545. ERR_FAIL_NULL(version);
  546. MutexLock lock(*version->mutex);
  547. _compile_ensure_finished(version);
  548. version->compute_globals = p_compute_globals.utf8();
  549. version->uniforms = p_uniforms.utf8();
  550. version->code_sections.clear();
  551. for (const KeyValue<String, String> &E : p_code) {
  552. version->code_sections[StringName(E.key.to_upper())] = E.value.utf8();
  553. }
  554. version->custom_defines.clear();
  555. for (int i = 0; i < p_custom_defines.size(); i++) {
  556. version->custom_defines.push_back(p_custom_defines[i].utf8());
  557. }
  558. version->dirty = true;
  559. if (version->initialize_needed) {
  560. _initialize_version(version);
  561. for (int i = 0; i < group_enabled.size(); i++) {
  562. if (!group_enabled[i]) {
  563. _allocate_placeholders(version, i);
  564. continue;
  565. }
  566. _compile_version_start(version, i);
  567. }
  568. version->initialize_needed = false;
  569. }
  570. }
  571. bool ShaderRD::version_is_valid(RID p_version) {
  572. Version *version = version_owner.get_or_null(p_version);
  573. ERR_FAIL_NULL_V(version, false);
  574. MutexLock lock(*version->mutex);
  575. if (version->dirty) {
  576. _initialize_version(version);
  577. for (int i = 0; i < group_enabled.size(); i++) {
  578. if (!group_enabled[i]) {
  579. _allocate_placeholders(version, i);
  580. continue;
  581. }
  582. _compile_version_start(version, i);
  583. }
  584. }
  585. _compile_ensure_finished(version);
  586. return version->valid;
  587. }
  588. bool ShaderRD::version_free(RID p_version) {
  589. if (version_owner.owns(p_version)) {
  590. {
  591. MutexLock lock(versions_mutex);
  592. version_mutexes.erase(p_version);
  593. }
  594. Version *version = version_owner.get_or_null(p_version);
  595. if (version->embedded) {
  596. MutexLock lock(shader_versions_embedded_set_mutex);
  597. shader_versions_embedded_set.erase({ this, p_version });
  598. }
  599. version->mutex->lock();
  600. _clear_version(version);
  601. version_owner.free(p_version);
  602. version->mutex->unlock();
  603. memdelete(version->mutex);
  604. } else {
  605. return false;
  606. }
  607. return true;
  608. }
  609. void ShaderRD::set_variant_enabled(int p_variant, bool p_enabled) {
  610. ERR_FAIL_COND(version_owner.get_rid_count() > 0); //versions exist
  611. ERR_FAIL_INDEX(p_variant, variants_enabled.size());
  612. variants_enabled.write[p_variant] = p_enabled;
  613. }
  614. bool ShaderRD::is_variant_enabled(int p_variant) const {
  615. ERR_FAIL_INDEX_V(p_variant, variants_enabled.size(), false);
  616. return variants_enabled[p_variant];
  617. }
  618. int64_t ShaderRD::get_variant_count() const {
  619. return variants_enabled.size();
  620. }
  621. int ShaderRD::get_variant_to_group(int p_variant) const {
  622. return variant_to_group[p_variant];
  623. }
  624. void ShaderRD::enable_group(int p_group) {
  625. ERR_FAIL_INDEX(p_group, group_enabled.size());
  626. if (group_enabled[p_group]) {
  627. // Group already enabled, do nothing.
  628. return;
  629. }
  630. group_enabled.write[p_group] = true;
  631. // Compile all versions again to include the new group.
  632. for (const RID &version_rid : version_owner.get_owned_list()) {
  633. Version *version = version_owner.get_or_null(version_rid);
  634. version->mutex->lock();
  635. _compile_version_start(version, p_group);
  636. version->mutex->unlock();
  637. }
  638. }
  639. bool ShaderRD::is_group_enabled(int p_group) const {
  640. return group_enabled[p_group];
  641. }
  642. int64_t ShaderRD::get_group_count() const {
  643. return group_enabled.size();
  644. }
  645. const LocalVector<int> &ShaderRD::get_group_to_variants(int p_group) const {
  646. return group_to_variant_map[p_group];
  647. }
  648. const String &ShaderRD::get_name() const {
  649. return name;
  650. }
  651. bool ShaderRD::shader_cache_cleanup_on_start = false;
  652. ShaderRD::ShaderRD() {
  653. // Do not feel forced to use this, in most cases it makes little to no difference.
  654. bool use_32_threads = false;
  655. if (RD::get_singleton()->get_device_vendor_name() == "NVIDIA") {
  656. use_32_threads = true;
  657. }
  658. String base_compute_define_text;
  659. if (use_32_threads) {
  660. base_compute_define_text = "\n#define NATIVE_LOCAL_GROUP_SIZE 32\n#define NATIVE_LOCAL_SIZE_2D_X 8\n#define NATIVE_LOCAL_SIZE_2D_Y 4\n";
  661. } else {
  662. base_compute_define_text = "\n#define NATIVE_LOCAL_GROUP_SIZE 64\n#define NATIVE_LOCAL_SIZE_2D_X 8\n#define NATIVE_LOCAL_SIZE_2D_Y 8\n";
  663. }
  664. base_compute_defines = base_compute_define_text.ascii();
  665. }
  666. void ShaderRD::initialize(const Vector<String> &p_variant_defines, const String &p_general_defines, const Vector<RD::PipelineImmutableSampler> &p_immutable_samplers) {
  667. ERR_FAIL_COND(variant_defines.size());
  668. ERR_FAIL_COND(p_variant_defines.is_empty());
  669. general_defines = p_general_defines.utf8();
  670. immutable_samplers = p_immutable_samplers;
  671. // When initialized this way, there is just one group and its always enabled.
  672. group_to_variant_map.insert(0, LocalVector<int>{});
  673. group_enabled.push_back(true);
  674. for (int i = 0; i < p_variant_defines.size(); i++) {
  675. variant_defines.push_back(VariantDefine(0, p_variant_defines[i], true));
  676. variants_enabled.push_back(true);
  677. variant_to_group.push_back(0);
  678. group_to_variant_map[0].push_back(i);
  679. }
  680. if (!shader_cache_user_dir.is_empty() || !shader_cache_res_dir.is_empty()) {
  681. group_sha256.resize(1);
  682. _initialize_cache();
  683. }
  684. }
  685. void ShaderRD::_initialize_cache() {
  686. shader_cache_user_dir_valid = !shader_cache_user_dir.is_empty();
  687. if (!shader_cache_user_dir_valid) {
  688. return;
  689. }
  690. for (const KeyValue<int, LocalVector<int>> &E : group_to_variant_map) {
  691. StringBuilder hash_build;
  692. hash_build.append("[base_hash]");
  693. hash_build.append(base_sha256);
  694. hash_build.append("[general_defines]");
  695. hash_build.append(general_defines.get_data());
  696. hash_build.append("[group_id]");
  697. hash_build.append(itos(E.key));
  698. for (uint32_t i = 0; i < E.value.size(); i++) {
  699. hash_build.append("[variant_defines:" + itos(E.value[i]) + "]");
  700. hash_build.append(variant_defines[E.value[i]].text.get_data());
  701. }
  702. group_sha256[E.key] = hash_build.as_string().sha256_text();
  703. if (!shader_cache_user_dir.is_empty()) {
  704. // Validate if it's possible to write to all the directories required by in the user directory.
  705. Ref<DirAccess> d = DirAccess::open(shader_cache_user_dir);
  706. if (d.is_null()) {
  707. shader_cache_user_dir_valid = false;
  708. ERR_FAIL_MSG(vformat("Unable to open shader cache directory at %s.", shader_cache_user_dir));
  709. }
  710. if (d->change_dir(name) != OK) {
  711. Error err = d->make_dir(name);
  712. if (err != OK) {
  713. shader_cache_user_dir_valid = false;
  714. ERR_FAIL_MSG(vformat("Unable to create shader cache directory %s at %s.", name, shader_cache_user_dir));
  715. }
  716. d->change_dir(name);
  717. }
  718. if (d->change_dir(group_sha256[E.key]) != OK) {
  719. Error err = d->make_dir(group_sha256[E.key]);
  720. if (err != OK) {
  721. shader_cache_user_dir_valid = false;
  722. ERR_FAIL_MSG(vformat("Unable to create shader cache directory %s/%s at %s.", name, group_sha256[E.key], shader_cache_user_dir));
  723. }
  724. }
  725. }
  726. print_verbose("Shader '" + name + "' (group " + itos(E.key) + ") SHA256: " + group_sha256[E.key]);
  727. }
  728. }
  729. // Same as above, but allows specifying shader compilation groups.
  730. void ShaderRD::initialize(const Vector<VariantDefine> &p_variant_defines, const String &p_general_defines, const Vector<RD::PipelineImmutableSampler> &p_immutable_samplers) {
  731. ERR_FAIL_COND(variant_defines.size());
  732. ERR_FAIL_COND(p_variant_defines.is_empty());
  733. general_defines = p_general_defines.utf8();
  734. immutable_samplers = p_immutable_samplers;
  735. int max_group_id = 0;
  736. for (int i = 0; i < p_variant_defines.size(); i++) {
  737. // Fill variant array.
  738. variant_defines.push_back(p_variant_defines[i]);
  739. variants_enabled.push_back(true);
  740. variant_to_group.push_back(p_variant_defines[i].group);
  741. // Map variant array index to group id, so we can iterate over groups later.
  742. if (!group_to_variant_map.has(p_variant_defines[i].group)) {
  743. group_to_variant_map.insert(p_variant_defines[i].group, LocalVector<int>{});
  744. }
  745. group_to_variant_map[p_variant_defines[i].group].push_back(i);
  746. // Track max size.
  747. if (p_variant_defines[i].group > max_group_id) {
  748. max_group_id = p_variant_defines[i].group;
  749. }
  750. }
  751. // Set all to groups to false, then enable those that should be default.
  752. group_enabled.resize_initialized(max_group_id + 1);
  753. bool *enabled_ptr = group_enabled.ptrw();
  754. for (int i = 0; i < p_variant_defines.size(); i++) {
  755. if (p_variant_defines[i].default_enabled) {
  756. enabled_ptr[p_variant_defines[i].group] = true;
  757. }
  758. }
  759. if (!shader_cache_user_dir.is_empty()) {
  760. group_sha256.resize(max_group_id + 1);
  761. _initialize_cache();
  762. }
  763. }
  764. void ShaderRD::shaders_embedded_set_lock() {
  765. shader_versions_embedded_set_mutex.lock();
  766. }
  767. const ShaderRD::ShaderVersionPairSet &ShaderRD::shaders_embedded_set_get() {
  768. return shader_versions_embedded_set;
  769. }
  770. void ShaderRD::shaders_embedded_set_unlock() {
  771. shader_versions_embedded_set_mutex.unlock();
  772. }
  773. void ShaderRD::set_shader_cache_user_dir(const String &p_dir) {
  774. shader_cache_user_dir = p_dir;
  775. }
  776. const String &ShaderRD::get_shader_cache_user_dir() {
  777. return shader_cache_user_dir;
  778. }
  779. void ShaderRD::set_shader_cache_res_dir(const String &p_dir) {
  780. shader_cache_res_dir = p_dir;
  781. }
  782. const String &ShaderRD::get_shader_cache_res_dir() {
  783. return shader_cache_res_dir;
  784. }
  785. void ShaderRD::set_shader_cache_save_compressed(bool p_enable) {
  786. shader_cache_save_compressed = p_enable;
  787. }
  788. void ShaderRD::set_shader_cache_save_compressed_zstd(bool p_enable) {
  789. shader_cache_save_compressed_zstd = p_enable;
  790. }
  791. void ShaderRD::set_shader_cache_save_debug(bool p_enable) {
  792. shader_cache_save_debug = p_enable;
  793. }
  794. Vector<RD::ShaderStageSPIRVData> ShaderRD::compile_stages(const Vector<String> &p_stage_sources) {
  795. RD::ShaderStageSPIRVData stage;
  796. Vector<RD::ShaderStageSPIRVData> stages;
  797. String error;
  798. RD::ShaderStage compilation_failed_stage = RD::SHADER_STAGE_MAX;
  799. bool compilation_failed = false;
  800. for (int64_t i = 0; i < p_stage_sources.size() && !compilation_failed; i++) {
  801. if (p_stage_sources[i].is_empty()) {
  802. continue;
  803. }
  804. stage.spirv = RD::get_singleton()->shader_compile_spirv_from_source(RD::ShaderStage(i), p_stage_sources[i], RD::SHADER_LANGUAGE_GLSL, &error);
  805. stage.shader_stage = RD::ShaderStage(i);
  806. if (!stage.spirv.is_empty()) {
  807. stages.push_back(stage);
  808. } else {
  809. compilation_failed_stage = RD::ShaderStage(i);
  810. compilation_failed = true;
  811. }
  812. }
  813. if (compilation_failed) {
  814. ERR_PRINT("Error compiling " + String(compilation_failed_stage == RD::SHADER_STAGE_COMPUTE ? "Compute " : (compilation_failed_stage == RD::SHADER_STAGE_VERTEX ? "Vertex" : "Fragment")) + " shader.");
  815. ERR_PRINT(error);
  816. #ifdef DEBUG_ENABLED
  817. ERR_PRINT("code:\n" + p_stage_sources[compilation_failed_stage].get_with_code_lines());
  818. #endif
  819. return Vector<RD::ShaderStageSPIRVData>();
  820. } else {
  821. return stages;
  822. }
  823. }
  824. PackedByteArray ShaderRD::save_shader_cache_bytes(const LocalVector<int> &p_variants, const Vector<Vector<uint8_t>> &p_variant_data) {
  825. uint32_t variant_count = p_variants.size();
  826. PackedByteArray bytes;
  827. int64_t total_size = 0;
  828. total_size += 4 + sizeof(uint32_t) * 2;
  829. for (uint32_t i = 0; i < variant_count; i++) {
  830. total_size += sizeof(uint32_t) + p_variant_data[p_variants[i]].size();
  831. }
  832. bytes.resize(total_size);
  833. uint8_t *bytes_ptr = bytes.ptrw();
  834. memcpy(bytes_ptr, shader_file_header, 4);
  835. bytes_ptr += 4;
  836. *(uint32_t *)(bytes_ptr) = cache_file_version;
  837. bytes_ptr += sizeof(uint32_t);
  838. *(uint32_t *)(bytes_ptr) = variant_count;
  839. bytes_ptr += sizeof(uint32_t);
  840. for (uint32_t i = 0; i < variant_count; i++) {
  841. int variant_id = p_variants[i];
  842. *(uint32_t *)(bytes_ptr) = uint32_t(p_variant_data[variant_id].size());
  843. bytes_ptr += sizeof(uint32_t);
  844. memcpy(bytes_ptr, p_variant_data[variant_id].ptr(), p_variant_data[variant_id].size());
  845. bytes_ptr += p_variant_data[variant_id].size();
  846. }
  847. DEV_ASSERT((bytes.ptrw() + bytes.size()) == bytes_ptr);
  848. return bytes;
  849. }
  850. String ShaderRD::shader_cache_user_dir;
  851. String ShaderRD::shader_cache_res_dir;
  852. bool ShaderRD::shader_cache_save_compressed = true;
  853. bool ShaderRD::shader_cache_save_compressed_zstd = true;
  854. bool ShaderRD::shader_cache_save_debug = true;
  855. ShaderRD::~ShaderRD() {
  856. LocalVector<RID> remaining = version_owner.get_owned_list();
  857. if (remaining.size()) {
  858. ERR_PRINT(itos(remaining.size()) + " shaders of type " + name + " were never freed");
  859. for (const RID &version_rid : remaining) {
  860. version_free(version_rid);
  861. }
  862. }
  863. }