shader_baker_export_plugin.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. /**************************************************************************/
  2. /* shader_baker_export_plugin.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_baker_export_plugin.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/io/dir_access.h"
  33. #include "core/version.h"
  34. #include "editor/editor_node.h"
  35. #include "scene/3d/label_3d.h"
  36. #include "scene/3d/sprite_3d.h"
  37. #include "servers/rendering/renderer_rd/renderer_scene_render_rd.h"
  38. #include "servers/rendering/renderer_rd/storage_rd/material_storage.h"
  39. #include "servers/rendering/rendering_shader_container.h"
  40. // Ensure that AlphaCut is the same between the two classes so we can share the code to detect transparency.
  41. static_assert(ENUM_MEMBERS_EQUAL(SpriteBase3D::ALPHA_CUT_DISABLED, Label3D::ALPHA_CUT_DISABLED));
  42. static_assert(ENUM_MEMBERS_EQUAL(SpriteBase3D::ALPHA_CUT_DISCARD, Label3D::ALPHA_CUT_DISCARD));
  43. static_assert(ENUM_MEMBERS_EQUAL(SpriteBase3D::ALPHA_CUT_OPAQUE_PREPASS, Label3D::ALPHA_CUT_OPAQUE_PREPASS));
  44. static_assert(ENUM_MEMBERS_EQUAL(SpriteBase3D::ALPHA_CUT_HASH, Label3D::ALPHA_CUT_HASH));
  45. static_assert(ENUM_MEMBERS_EQUAL(SpriteBase3D::ALPHA_CUT_MAX, Label3D::ALPHA_CUT_MAX));
  46. String ShaderBakerExportPlugin::get_name() const {
  47. return "ShaderBaker";
  48. }
  49. bool ShaderBakerExportPlugin::_is_active(const Vector<String> &p_features) const {
  50. // Shader baker should only work when a RendererRD driver is active, as the embedded shaders won't be found otherwise.
  51. return RendererSceneRenderRD::get_singleton() != nullptr && RendererRD::MaterialStorage::get_singleton() != nullptr && p_features.has("shader_baker");
  52. }
  53. bool ShaderBakerExportPlugin::_initialize_container_format(const Ref<EditorExportPlatform> &p_platform, const Ref<EditorExportPreset> &p_preset) {
  54. shader_container_driver = p_preset->get_project_setting("rendering/rendering_device/driver");
  55. ERR_FAIL_COND_V_MSG(shader_container_driver.is_empty(), false, "Invalid `rendering/rendering_device/driver` setting, disabling shader baking.");
  56. for (Ref<ShaderBakerExportPluginPlatform> platform : platforms) {
  57. if (platform->matches_driver(shader_container_driver)) {
  58. shader_container_format = platform->create_shader_container_format(p_platform, p_preset);
  59. ERR_FAIL_NULL_V_MSG(shader_container_format, false, "Unable to create shader container format for the export platform.");
  60. return true;
  61. }
  62. }
  63. return false;
  64. }
  65. void ShaderBakerExportPlugin::_cleanup_container_format() {
  66. if (shader_container_format != nullptr) {
  67. memdelete(shader_container_format);
  68. shader_container_format = nullptr;
  69. }
  70. }
  71. bool ShaderBakerExportPlugin::_initialize_cache_directory() {
  72. shader_cache_export_path = get_export_base_path().path_join("shader_baker").path_join(shader_cache_platform_name).path_join(shader_container_driver);
  73. if (!DirAccess::dir_exists_absolute(shader_cache_export_path)) {
  74. Error err = DirAccess::make_dir_recursive_absolute(shader_cache_export_path);
  75. ERR_FAIL_COND_V_MSG(err != OK, false, "Can't create shader cache folder for exporting.");
  76. }
  77. return true;
  78. }
  79. bool ShaderBakerExportPlugin::_begin_customize_resources(const Ref<EditorExportPlatform> &p_platform, const Vector<String> &p_features) {
  80. if (!_is_active(p_features)) {
  81. return false;
  82. }
  83. if (!_initialize_container_format(p_platform, get_export_preset())) {
  84. return false;
  85. }
  86. if (Engine::get_singleton()->is_generate_spirv_debug_info_enabled()) {
  87. WARN_PRINT("Shader baker can't generate a compatible shader when run with --generate-spirv-debug-info. Restart the editor without this argument if you want to bake shaders.");
  88. return false;
  89. }
  90. shader_cache_platform_name = p_platform->get_os_name();
  91. shader_cache_renderer_name = RendererSceneRenderRD::get_singleton()->get_name();
  92. tasks_processed = 0;
  93. tasks_total = 0;
  94. tasks_cancelled = false;
  95. StringBuilder to_hash;
  96. to_hash.append("[GodotVersionNumber]");
  97. to_hash.append(GODOT_VERSION_NUMBER);
  98. to_hash.append("[GodotVersionHash]");
  99. to_hash.append(GODOT_VERSION_HASH);
  100. to_hash.append("[Renderer]");
  101. to_hash.append(shader_cache_renderer_name);
  102. customization_configuration_hash = to_hash.as_string().hash64();
  103. BitField<RenderingShaderLibrary::FeatureBits> renderer_features = {};
  104. #ifndef XR_DISABLED
  105. bool xr_enabled = GLOBAL_GET("xr/shaders/enabled");
  106. renderer_features.set_flag(RenderingShaderLibrary::FEATURE_ADVANCED_BIT);
  107. if (xr_enabled) {
  108. renderer_features.set_flag(RenderingShaderLibrary::FEATURE_MULTIVIEW_BIT);
  109. }
  110. #endif // XR_DISABLED
  111. int vrs_mode = GLOBAL_GET("rendering/vrs/mode");
  112. if (vrs_mode != 0) {
  113. renderer_features.set_flag(RenderingShaderLibrary::FEATURE_VRS_BIT);
  114. }
  115. // Both FP16 and FP32 variants should be included.
  116. renderer_features.set_flag(RenderingShaderLibrary::FEATURE_FP16_BIT);
  117. renderer_features.set_flag(RenderingShaderLibrary::FEATURE_FP32_BIT);
  118. RendererSceneRenderRD::get_singleton()->enable_features(renderer_features);
  119. // Included all shaders created by renderers and effects.
  120. ShaderRD::shaders_embedded_set_lock();
  121. const ShaderRD::ShaderVersionPairSet &pair_set = ShaderRD::shaders_embedded_set_get();
  122. for (Pair<ShaderRD *, RID> pair : pair_set) {
  123. _customize_shader_version(pair.first, pair.second);
  124. }
  125. ShaderRD::shaders_embedded_set_unlock();
  126. // Include all shaders created by embedded materials.
  127. RendererRD::MaterialStorage *material_storage = RendererRD::MaterialStorage::get_singleton();
  128. material_storage->shader_embedded_set_lock();
  129. const HashSet<RID> &rid_set = material_storage->shader_embedded_set_get();
  130. for (RID rid : rid_set) {
  131. RendererRD::MaterialStorage::ShaderData *shader_data = material_storage->shader_get_data(rid);
  132. if (shader_data != nullptr) {
  133. Pair<ShaderRD *, RID> shader_version_pair = shader_data->get_native_shader_and_version();
  134. if (shader_version_pair.first != nullptr) {
  135. _customize_shader_version(shader_version_pair.first, shader_version_pair.second);
  136. }
  137. }
  138. }
  139. material_storage->shader_embedded_set_unlock();
  140. return true;
  141. }
  142. bool ShaderBakerExportPlugin::_begin_customize_scenes(const Ref<EditorExportPlatform> &p_platform, const Vector<String> &p_features) {
  143. if (!_is_active(p_features)) {
  144. return false;
  145. }
  146. if (shader_container_format == nullptr) {
  147. // Resource customization failed to initialize.
  148. return false;
  149. }
  150. return true;
  151. }
  152. void ShaderBakerExportPlugin::_end_customize_resources() {
  153. if (!_initialize_cache_directory()) {
  154. return;
  155. }
  156. // Run a progress bar that waits for all shader baking tasks to finish.
  157. bool progress_active = true;
  158. EditorProgress editor_progress("baking_shaders", TTR("Baking shaders"), tasks_total);
  159. editor_progress.step("Baking...", 0);
  160. while (progress_active) {
  161. uint32_t tasks_for_progress = 0;
  162. {
  163. MutexLock lock(tasks_mutex);
  164. if (tasks_processed >= tasks_total) {
  165. progress_active = false;
  166. } else {
  167. tasks_condition.wait(lock);
  168. tasks_for_progress = tasks_processed;
  169. }
  170. }
  171. if (progress_active && editor_progress.step("Baking...", tasks_for_progress)) {
  172. // User skipped the shader baker, we just don't pack the shaders in the project.
  173. tasks_cancelled = true;
  174. progress_active = false;
  175. }
  176. }
  177. String shader_cache_user_dir = ShaderRD::get_shader_cache_user_dir();
  178. for (const ShaderGroupItem &group_item : shader_group_items) {
  179. // Wait for all shader compilation tasks of the group to be finished.
  180. for (WorkerThreadPool::TaskID task_id : group_item.variant_tasks) {
  181. WorkerThreadPool::get_singleton()->wait_for_task_completion(task_id);
  182. }
  183. if (!tasks_cancelled) {
  184. WorkResult work_result;
  185. {
  186. MutexLock lock(shader_work_results_mutex);
  187. work_result = shader_work_results[group_item.cache_path];
  188. }
  189. PackedByteArray cache_file_bytes = ShaderRD::save_shader_cache_bytes(group_item.variants, work_result.variant_data);
  190. add_file(shader_cache_user_dir.path_join(group_item.cache_path), cache_file_bytes, false);
  191. String cache_file_path = shader_cache_export_path.path_join(group_item.cache_path);
  192. if (!DirAccess::exists(cache_file_path)) {
  193. DirAccess::make_dir_recursive_absolute(cache_file_path.get_base_dir());
  194. }
  195. Ref<FileAccess> cache_file_access = FileAccess::open(cache_file_path, FileAccess::WRITE);
  196. if (cache_file_access.is_valid()) {
  197. cache_file_access->store_buffer(cache_file_bytes);
  198. }
  199. }
  200. }
  201. if (!tasks_cancelled) {
  202. String file_cache_path = shader_cache_export_path.path_join("file_cache");
  203. Ref<FileAccess> cache_list_access = FileAccess::open(file_cache_path, FileAccess::READ_WRITE);
  204. if (cache_list_access.is_null()) {
  205. cache_list_access = FileAccess::open(file_cache_path, FileAccess::WRITE);
  206. }
  207. if (cache_list_access.is_valid()) {
  208. String cache_list_line;
  209. while (cache_list_line = cache_list_access->get_line(), !cache_list_line.is_empty()) {
  210. // Only add if it wasn't already added.
  211. if (!shader_paths_processed.has(cache_list_line)) {
  212. PackedByteArray cache_file_bytes = FileAccess::get_file_as_bytes(shader_cache_export_path.path_join(cache_list_line));
  213. if (!cache_file_bytes.is_empty()) {
  214. add_file(shader_cache_user_dir.path_join(cache_list_line), cache_file_bytes, false);
  215. }
  216. }
  217. shader_paths_processed.erase(cache_list_line);
  218. }
  219. for (const String &shader_path : shader_paths_processed) {
  220. cache_list_access->store_line(shader_path);
  221. }
  222. cache_list_access->close();
  223. }
  224. }
  225. shader_paths_processed.clear();
  226. shader_work_results.clear();
  227. shader_group_items.clear();
  228. _cleanup_container_format();
  229. }
  230. Ref<Resource> ShaderBakerExportPlugin::_customize_resource(const Ref<Resource> &p_resource, const String &p_path) {
  231. RendererRD::MaterialStorage *singleton = RendererRD::MaterialStorage::get_singleton();
  232. DEV_ASSERT(singleton != nullptr);
  233. Ref<Material> material = p_resource;
  234. if (material.is_valid()) {
  235. RID material_rid = material->get_rid();
  236. if (material_rid.is_valid()) {
  237. RendererRD::MaterialStorage::ShaderData *shader_data = singleton->material_get_shader_data(material_rid);
  238. if (shader_data != nullptr) {
  239. Pair<ShaderRD *, RID> shader_version_pair = shader_data->get_native_shader_and_version();
  240. if (shader_version_pair.first != nullptr) {
  241. _customize_shader_version(shader_version_pair.first, shader_version_pair.second);
  242. }
  243. }
  244. }
  245. }
  246. return Ref<Resource>();
  247. }
  248. Node *ShaderBakerExportPlugin::_customize_scene(Node *p_root, const String &p_path) {
  249. LocalVector<Node *> nodes_to_visit;
  250. nodes_to_visit.push_back(p_root);
  251. while (!nodes_to_visit.is_empty()) {
  252. // Visit all nodes recursively in the scene to find the Label3Ds and Sprite3Ds.
  253. Node *node = nodes_to_visit[nodes_to_visit.size() - 1];
  254. nodes_to_visit.remove_at(nodes_to_visit.size() - 1);
  255. Label3D *label_3d = Object::cast_to<Label3D>(node);
  256. Sprite3D *sprite_3d = Object::cast_to<Sprite3D>(node);
  257. if (label_3d != nullptr || sprite_3d != nullptr) {
  258. // Create materials for Label3D and Sprite3D, which are normally generated at runtime on demand.
  259. HashMap<StringName, Variant> properties;
  260. // These must match the defaults set by Sprite3D/Label3D.
  261. properties["transparent"] = true; // Label3D doesn't have this property, but it is always true anyway.
  262. properties["shaded"] = false;
  263. properties["double_sided"] = true;
  264. properties["no_depth_test"] = false;
  265. properties["fixed_size"] = false;
  266. properties["billboard"] = StandardMaterial3D::BILLBOARD_DISABLED;
  267. properties["texture_filter"] = StandardMaterial3D::TEXTURE_FILTER_LINEAR_WITH_MIPMAPS;
  268. properties["alpha_antialiasing_mode"] = StandardMaterial3D::ALPHA_ANTIALIASING_OFF;
  269. properties["alpha_cut"] = SpriteBase3D::ALPHA_CUT_DISABLED;
  270. List<PropertyInfo> property_list;
  271. node->get_property_list(&property_list);
  272. for (const PropertyInfo &info : property_list) {
  273. bool valid = false;
  274. Variant property = node->get(info.name, &valid);
  275. if (valid) {
  276. properties[info.name] = property;
  277. }
  278. }
  279. // This must follow the logic in Sprite3D::draw_texture_rect().
  280. BaseMaterial3D::Transparency mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_DISABLED;
  281. if (properties["transparent"]) {
  282. SpriteBase3D::AlphaCutMode acm = SpriteBase3D::AlphaCutMode(int(properties["alpha_cut"]));
  283. if (acm == SpriteBase3D::ALPHA_CUT_DISCARD) {
  284. mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA_SCISSOR;
  285. } else if (acm == SpriteBase3D::ALPHA_CUT_OPAQUE_PREPASS) {
  286. mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA_DEPTH_PRE_PASS;
  287. } else if (acm == SpriteBase3D::ALPHA_CUT_HASH) {
  288. mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA_HASH;
  289. } else {
  290. mat_transparency = BaseMaterial3D::Transparency::TRANSPARENCY_ALPHA;
  291. }
  292. }
  293. StandardMaterial3D::BillboardMode billboard_mode = StandardMaterial3D::BillboardMode(int(properties["billboard"]));
  294. Ref<Material> sprite_3d_material = StandardMaterial3D::get_material_for_2d(bool(properties["shaded"]), mat_transparency, bool(properties["double_sided"]), billboard_mode == StandardMaterial3D::BILLBOARD_ENABLED, billboard_mode == StandardMaterial3D::BILLBOARD_FIXED_Y, false, bool(properties["no_depth_test"]), bool(properties["fixed_size"]), BaseMaterial3D::TextureFilter(int(properties["texture_filter"])), BaseMaterial3D::AlphaAntiAliasing(int(properties["alpha_antialiasing_mode"])));
  295. _customize_resource(sprite_3d_material, String());
  296. if (label_3d != nullptr) {
  297. // Generate variants with and without MSDF support since we don't have access to the font here.
  298. Ref<Material> label_3d_material = StandardMaterial3D::get_material_for_2d(bool(properties["shaded"]), mat_transparency, bool(properties["double_sided"]), billboard_mode == StandardMaterial3D::BILLBOARD_ENABLED, billboard_mode == StandardMaterial3D::BILLBOARD_FIXED_Y, true, bool(properties["no_depth_test"]), bool(properties["fixed_size"]), BaseMaterial3D::TextureFilter(int(properties["texture_filter"])), BaseMaterial3D::AlphaAntiAliasing(int(properties["alpha_antialiasing_mode"])));
  299. _customize_resource(label_3d_material, String());
  300. }
  301. }
  302. // Visit children.
  303. int child_count = node->get_child_count();
  304. for (int i = 0; i < child_count; i++) {
  305. nodes_to_visit.push_back(node->get_child(i));
  306. }
  307. }
  308. return nullptr;
  309. }
  310. uint64_t ShaderBakerExportPlugin::_get_customization_configuration_hash() const {
  311. return customization_configuration_hash;
  312. }
  313. void ShaderBakerExportPlugin::_customize_shader_version(ShaderRD *p_shader, RID p_version) {
  314. const int64_t variant_count = p_shader->get_variant_count();
  315. const int64_t group_count = p_shader->get_group_count();
  316. LocalVector<ShaderGroupItem> group_items;
  317. group_items.resize(group_count);
  318. RBSet<uint32_t> groups_to_compile;
  319. for (int64_t i = 0; i < group_count; i++) {
  320. if (!p_shader->is_group_enabled(i)) {
  321. continue;
  322. }
  323. String cache_path = p_shader->version_get_cache_file_relative_path(p_version, i, shader_container_driver);
  324. if (shader_paths_processed.has(cache_path)) {
  325. continue;
  326. }
  327. shader_paths_processed.insert(cache_path);
  328. groups_to_compile.insert(i);
  329. group_items[i].cache_path = cache_path;
  330. group_items[i].variants = p_shader->get_group_to_variants(i);
  331. {
  332. MutexLock lock(shader_work_results_mutex);
  333. shader_work_results[cache_path].variant_data.resize(variant_count);
  334. }
  335. }
  336. for (int64_t i = 0; i < variant_count; i++) {
  337. int group = p_shader->get_variant_to_group(i);
  338. if (!p_shader->is_variant_enabled(i) || !groups_to_compile.has(group)) {
  339. continue;
  340. }
  341. WorkItem work_item;
  342. work_item.cache_path = group_items[group].cache_path;
  343. work_item.shader_name = p_shader->get_name();
  344. work_item.stage_sources = p_shader->version_build_variant_stage_sources(p_version, i);
  345. work_item.dynamic_buffers = p_shader->get_dynamic_buffers();
  346. work_item.variant = i;
  347. WorkerThreadPool::TaskID task_id = WorkerThreadPool::get_singleton()->add_template_task(this, &ShaderBakerExportPlugin::_process_work_item, work_item);
  348. group_items[group].variant_tasks.push_back(task_id);
  349. tasks_total++;
  350. }
  351. for (uint32_t i : groups_to_compile) {
  352. shader_group_items.push_back(group_items[i]);
  353. }
  354. }
  355. void ShaderBakerExportPlugin::_process_work_item(WorkItem p_work_item) {
  356. if (!tasks_cancelled) {
  357. // Only process the item if the tasks haven't been cancelled by the user yet.
  358. Vector<RD::ShaderStageSPIRVData> spirv_data = ShaderRD::compile_stages(p_work_item.stage_sources, p_work_item.dynamic_buffers);
  359. if (unlikely(spirv_data.is_empty())) {
  360. ERR_PRINT("Unable to retrieve SPIR-V data for shader.");
  361. } else {
  362. Ref<RenderingShaderContainer> shader_container = shader_container_format->create_container();
  363. // Compile shader binary from SPIR-V.
  364. bool code_compiled = shader_container->set_code_from_spirv(p_work_item.shader_name, spirv_data);
  365. if (unlikely(!code_compiled)) {
  366. ERR_PRINT("Failed to compile code to native for SPIR-V.");
  367. } else {
  368. PackedByteArray shader_bytes = shader_container->to_bytes();
  369. {
  370. MutexLock lock(shader_work_results_mutex);
  371. shader_work_results[p_work_item.cache_path].variant_data.ptrw()[p_work_item.variant] = shader_bytes;
  372. }
  373. }
  374. }
  375. }
  376. {
  377. MutexLock lock(tasks_mutex);
  378. tasks_processed++;
  379. }
  380. tasks_condition.notify_one();
  381. }
  382. ShaderBakerExportPlugin::ShaderBakerExportPlugin() {
  383. // Do nothing.
  384. }
  385. ShaderBakerExportPlugin::~ShaderBakerExportPlugin() {
  386. // Do nothing.
  387. }
  388. void ShaderBakerExportPlugin::add_platform(Ref<ShaderBakerExportPluginPlatform> p_platform) {
  389. platforms.push_back(p_platform);
  390. }
  391. void ShaderBakerExportPlugin::remove_platform(Ref<ShaderBakerExportPluginPlatform> p_platform) {
  392. platforms.erase(p_platform);
  393. }