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