Debian Codegraph @

editor/shader/shader_create_dialog.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* shader_create_dialog.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_create_dialog.h"
32
33 #include "core/config/project_settings.h"
34 #include "core/io/dir_access.h"
35 #include "editor/editor_node.h"
36 #include "editor/gui/editor_file_dialog.h"
37 #include "editor/gui/editor_validation_panel.h"
38 #include "editor/shader/editor_shader_language_plugin.h"
39 #include "editor/themes/editor_scale.h"
40 #include "scene/resources/shader_include.h"
41 #include "servers/rendering/shader_types.h"
42
43 void ShaderCreateDialog::_notification(int p_what) {
44 switch (p_what) {
45 case NOTIFICATION_ENTER_TREE: {
46 current_mode = EditorSettings::get_singleton()->get_project_metadata("shader_setup", "last_selected_mode", 0);
47 mode_menu->select(current_mode);
48 } break;
49
50 case NOTIFICATION_THEME_CHANGED: {
51 path_button->set_button_icon(get_editor_theme_icon(SNAME("Folder")));
52 // Note that some of the theme logic happens in `config()` when opening the dialog.
53 } break;
54 }
55 }
56
57 void ShaderCreateDialog::_refresh_type_icons() {
58 for (int i = 0; i < type_menu->get_item_count(); i++) {
59 const String item_name = type_menu->get_item_text(i);
60 Ref<Texture2D> icon = get_editor_theme_icon(item_name);
61 if (icon.is_valid()) {
62 type_menu->set_item_icon(i, icon);
63 } else {
64 icon = get_editor_theme_icon("TextFile");
65 if (icon.is_valid()) {
66 type_menu->set_item_icon(i, icon);
67 }
68 }
69 }
70 }
71
72 void ShaderCreateDialog::_update_language_info() {
73 type_data.clear();
74
75 for (int i = 0; i < EditorShaderLanguagePlugin::get_shader_language_variation_count(); i++) {
76 ShaderTypeData shader_type_data;
77 if (i == 0) {
78 // HACK: The ShaderCreateDialog class currently only shows templates for text shaders. Generalize this later.
79 shader_type_data.use_templates = true;
80 }
81 shader_type_data.default_extension = EditorShaderLanguagePlugin::get_file_extension_for_index(i);
82 shader_type_data.extensions.push_back(shader_type_data.default_extension);
83 if (shader_type_data.default_extension != "tres") {
84 shader_type_data.extensions.push_back("tres");
85 }
86 shader_type_data.extensions.push_back("res");
87 type_data.push_back(shader_type_data);
88 }
89 }
90
91 void ShaderCreateDialog::_path_hbox_sorted() {
92 if (is_visible()) {
93 int filename_start_pos = initial_base_path.rfind_char('/') + 1;
94 int filename_end_pos = initial_base_path.length();
95
96 if (!is_built_in) {
97 file_path->select(filename_start_pos, filename_end_pos);
98 }
99
100 file_path->set_caret_column(file_path->get_text().length());
101 file_path->set_caret_column(filename_start_pos);
102
103 file_path->grab_focus();
104 }
105 }
106
107 void ShaderCreateDialog::_mode_changed(int p_mode) {
108 current_mode = p_mode;
109 EditorSettings::get_singleton()->set_project_metadata("shader_setup", "last_selected_mode", p_mode);
110 }
111
112 void ShaderCreateDialog::_template_changed(int p_template) {
113 current_template = p_template;
114 EditorSettings::get_singleton()->set_project_metadata("shader_setup", "last_selected_template", p_template);
115 }
116
117 void ShaderCreateDialog::ok_pressed() {
118 if (is_new_shader_created) {
119 _create_new();
120 if (built_in_enabled) {
121 // Only save state of built-in checkbox if it's enabled.
122 EditorSettings::get_singleton()->set_project_metadata("shader_setup", "create_built_in_shader", internal->is_pressed());
123 }
124 } else {
125 _load_exist();
126 }
127
128 is_new_shader_created = true;
129 validation_panel->update();
130 }
131
132 void ShaderCreateDialog::_create_new() {
133 Ref<Resource> shader;
134 Ref<Resource> shader_inc;
135
136 const int type_index = type_menu->get_selected();
137 Ref<EditorShaderLanguagePlugin> shader_lang = EditorShaderLanguagePlugin::get_shader_language_for_index(type_index);
138 // A bit of an unfortunate hack because Shader and ShaderInclude do not share a common base class.
139 // We need duplicate code paths for includes vs non-includes, so just check for the string "Include".
140 if (type_menu->get_item_text(type_index).contains("Include")) {
141 shader_inc = shader_lang->create_new_shader_include();
142 } else {
143 shader = shader_lang->create_new_shader(0, Shader::Mode(current_mode), current_template);
144 }
145
146 if (shader.is_null()) {
147 String lpath = ProjectSettings::get_singleton()->localize_path(file_path->get_text());
148 shader_inc->set_path(lpath);
149
150 Error error = ResourceSaver::save(shader_inc, lpath, ResourceSaver::FLAG_CHANGE_PATH);
151 if (error != OK) {
152 alert->set_text(TTR("Error - Could not create shader include in filesystem."));
153 alert->popup_centered();
154 return;
155 }
156
157 emit_signal(SNAME("shader_include_created"), shader_inc);
158 } else {
159 if (is_built_in) {
160 Node *edited_scene = get_tree()->get_edited_scene_root();
161 if (likely(edited_scene)) {
162 shader->set_path(edited_scene->get_scene_file_path() + "::" + shader->generate_scene_unique_id());
163 }
164 } else {
165 String lpath = ProjectSettings::get_singleton()->localize_path(file_path->get_text());
166 shader->set_path(lpath);
167
168 Error error = ResourceSaver::save(shader, lpath, ResourceSaver::FLAG_CHANGE_PATH);
169 if (error != OK) {
170 alert->set_text(TTR("Error - Could not create shader in filesystem."));
171 alert->popup_centered();
172 return;
173 }
174 }
175
176 emit_signal(SNAME("shader_created"), shader);
177 }
178
179 file_path->set_text(file_path->get_text().get_base_dir());
180 hide();
181 }
182
183 void ShaderCreateDialog::_load_exist() {
184 String path = file_path->get_text();
185 Ref<Resource> p_shader = ResourceLoader::load(path, "Shader");
186 if (p_shader.is_null()) {
187 alert->set_text(vformat(TTR("Error loading shader from %s"), path));
188 alert->popup_centered();
189 return;
190 }
191
192 emit_signal(SNAME("shader_created"), p_shader);
193 hide();
194 }
195
196 void ShaderCreateDialog::_type_changed(int p_language) {
197 current_type = p_language;
198 ShaderTypeData shader_type_data = type_data.get(p_language);
199
200 String selected_ext = "." + shader_type_data.default_extension;
201 String path = file_path->get_text();
202 String extension = "";
203
204 if (!path.is_empty()) {
205 if (path.contains_char('.')) {
206 extension = path.get_extension();
207 }
208 if (extension.length() == 0) {
209 path += selected_ext;
210 } else {
211 path = path.get_basename() + selected_ext;
212 }
213 } else {
214 path = "shader" + selected_ext;
215 }
216 _path_changed(path);
217 file_path->set_text(path);
218
219 mode_menu->set_disabled(false);
220 for (int i = 0; i < type_menu->get_item_count(); i++) {
221 const String item_name = type_menu->get_item_text(i);
222 if (item_name.contains("Include")) {
223 type_menu->set_item_disabled(i, load_enabled);
224 if (i == p_language) {
225 mode_menu->set_disabled(true);
226 }
227 } else {
228 type_menu->set_item_disabled(i, false);
229 }
230 }
231 template_menu->set_disabled(!shader_type_data.use_templates);
232 template_menu->clear();
233
234 if (shader_type_data.use_templates) {
235 int last_template = EditorSettings::get_singleton()->get_project_metadata("shader_setup", "last_selected_template", 0);
236
237 template_menu->add_item(TTRC("Default"));
238 template_menu->add_item(TTRC("Empty"));
239
240 template_menu->select(last_template);
241 current_template = last_template;
242 } else {
243 template_menu->add_item(TTRC("N/A"));
244 }
245
246 EditorSettings::get_singleton()->set_project_metadata("shader_setup", "last_selected_language", type_menu->get_item_text(type_menu->get_selected()));
247 validation_panel->update();
248 }
249
250 void ShaderCreateDialog::_built_in_toggled(bool p_enabled) {
251 is_built_in = p_enabled;
252 if (p_enabled) {
253 is_new_shader_created = true;
254 } else {
255 _path_changed(file_path->get_text());
256 }
257 validation_panel->update();
258 }
259
260 void ShaderCreateDialog::_browse_path() {
261 file_browse->set_file_mode(EditorFileDialog::FILE_MODE_SAVE_FILE);
262 file_browse->set_title(TTR("Open Shader / Choose Location"));
263 file_browse->set_ok_button_text(TTR("Open"));
264
265 file_browse->set_customization_flag_enabled(FileDialog::CUSTOMIZATION_OVERWRITE_WARNING, false);
266 file_browse->clear_filters();
267
268 List<String> extensions = type_data.get(type_menu->get_selected()).extensions;
269
270 for (const String &E : extensions) {
271 file_browse->add_filter("*." + E);
272 }
273
274 file_browse->set_current_path(file_path->get_text());
275 file_browse->popup_file_dialog();
276 }
277
278 void ShaderCreateDialog::_file_selected(const String &p_file) {
279 String p = ProjectSettings::get_singleton()->localize_path(p_file);
280 file_path->set_text(p);
281 _path_changed(p);
282
283 String filename = p.get_file().get_basename();
284 int select_start = p.rfind(filename);
285 file_path->select(select_start, select_start + filename.length());
286 file_path->set_caret_column(select_start + filename.length());
287 file_path->grab_focus();
288 }
289
290 void ShaderCreateDialog::_path_changed(const String &p_path) {
291 if (is_built_in) {
292 return;
293 }
294
295 is_path_valid = false;
296 is_new_shader_created = true;
297
298 path_error = _validate_path(p_path);
299 if (!path_error.is_empty()) {
300 validation_panel->update();
301 return;
302 }
303
304 Ref<DirAccess> f = DirAccess::create(DirAccess::ACCESS_RESOURCES);
305 String p = ProjectSettings::get_singleton()->localize_path(p_path.strip_edges());
306 if (f->file_exists(p)) {
307 is_new_shader_created = false;
308 }
309
310 is_path_valid = true;
311 validation_panel->update();
312 }
313
314 void ShaderCreateDialog::_path_submitted(const String &p_path) {
315 if (!get_ok_button()->is_disabled()) {
316 ok_pressed();
317 }
318 }
319
320 void ShaderCreateDialog::config(const String &p_base_path, bool p_built_in_enabled, bool p_load_enabled, const String &p_preferred_type, int p_preferred_mode) {
321 _update_language_info();
322 type_menu->clear();
323 const Vector<Ref<EditorShaderLanguagePlugin>> shader_langs = EditorShaderLanguagePlugin::get_shader_languages_read_only();
324 ERR_FAIL_COND_MSG(shader_langs.is_empty(), "ShaderCreateDialog: Unable to load any shader languages!");
325 for (Ref<EditorShaderLanguagePlugin> shader_lang : shader_langs) {
326 const PackedStringArray variations = shader_lang->get_language_variations();
327 for (const String &variation : variations) {
328 type_menu->add_item(variation);
329 }
330 }
331 _refresh_type_icons();
332
333 int preferred_type = -1;
334 // Select preferred type if specified.
335 for (int i = 0; i < type_menu->get_item_count(); i++) {
336 if (type_menu->get_item_text(i) == p_preferred_type) {
337 preferred_type = i;
338 break;
339 }
340 }
341 if (preferred_type < 0 || preferred_type >= type_menu->get_item_count()) {
342 preferred_type = 0;
343 // Select the last selected language if possible, otherwise default to the first language.
344 String last_lang = EditorSettings::get_singleton()->get_project_metadata("shader_setup", "last_selected_language", "");
345 if (!last_lang.is_empty()) {
346 for (int i = 0; i < type_menu->get_item_count(); i++) {
347 if (type_menu->get_item_text(i) == last_lang) {
348 preferred_type = i;
349 break;
350 }
351 }
352 }
353 }
354 type_menu->select(preferred_type);
355 current_type = 0;
356
357 if (!p_base_path.is_empty()) {
358 initial_base_path = p_base_path.get_basename();
359 file_path->set_text(initial_base_path + "." + type_data.get(type_menu->get_selected()).default_extension);
360 current_type = type_menu->get_selected();
361 } else {
362 initial_base_path = "";
363 file_path->set_text("");
364 }
365 file_path->deselect();
366
367 built_in_enabled = p_built_in_enabled;
368 load_enabled = p_load_enabled;
369
370 if (built_in_enabled) {
371 internal->set_pressed(EditorSettings::get_singleton()->get_project_metadata("shader_setup", "create_built_in_shader", false));
372 }
373
374 if (p_preferred_mode > -1) {
375 mode_menu->select(p_preferred_mode);
376 _mode_changed(p_preferred_mode);
377 }
378
379 _type_changed(current_type);
380 _path_changed(file_path->get_text());
381 }
382
383 String ShaderCreateDialog::_validate_path(const String &p_path) {
384 ERR_FAIL_COND_V(current_type >= type_data.size(), TTR("Invalid shader type selected."));
385 String stripped_file_path = p_path.strip_edges();
386
387 if (stripped_file_path.is_empty()) {
388 return TTR("Path is empty.");
389 }
390 if (stripped_file_path.get_file().get_basename().is_empty()) {
391 return TTR("Filename is empty.");
392 }
393
394 stripped_file_path = ProjectSettings::get_singleton()->localize_path(stripped_file_path);
395 if (!stripped_file_path.begins_with("res://")) {
396 return TTR("Path is not local.");
397 }
398
399 Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_RESOURCES);
400 if (d->change_dir(stripped_file_path.get_base_dir()) != OK) {
401 return TTR("Invalid base path.");
402 }
403
404 Ref<DirAccess> f = DirAccess::create(DirAccess::ACCESS_RESOURCES);
405 if (f->dir_exists(stripped_file_path)) {
406 return TTR("A directory with the same name exists.");
407 }
408
409 const ShaderCreateDialog::ShaderTypeData &current_type_data = type_data.get(current_type);
410 const String file_extension = stripped_file_path.get_extension();
411
412 for (const String &type_ext : current_type_data.extensions) {
413 if (type_ext.nocasecmp_to(file_extension) == 0) {
414 return "";
415 }
416 }
417
418 return TTR("Invalid extension for selected shader type.");
419 }
420
421 void ShaderCreateDialog::_update_dialog() {
422 if (!is_built_in && !is_path_valid) {
423 validation_panel->set_message(MSG_ID_SHADER, TTR("Invalid path."), EditorValidationPanel::MSG_ERROR);
424 }
425 if (!is_built_in && !path_error.is_empty()) {
426 validation_panel->set_message(MSG_ID_PATH, path_error, EditorValidationPanel::MSG_ERROR);
427 } else if (validation_panel->is_valid() && !is_new_shader_created) {
428 validation_panel->set_message(MSG_ID_SHADER, TTR("File exists, it will be reused."), EditorValidationPanel::MSG_OK);
429 }
430 if (!built_in_enabled) {
431 internal->set_pressed(false);
432 }
433
434 if (is_built_in) {
435 file_path->set_editable(false);
436 path_button->set_disabled(true);
437 re_check_path = true;
438 } else {
439 file_path->set_editable(true);
440 path_button->set_disabled(false);
441 if (re_check_path) {
442 re_check_path = false;
443 _path_changed(file_path->get_text());
444 }
445 }
446
447 internal->set_disabled(!built_in_enabled);
448
449 if (is_built_in) {
450 validation_panel->set_message(MSG_ID_BUILT_IN, TTR("Note: Built-in shaders can't be edited using an external editor."), EditorValidationPanel::MSG_INFO, false);
451 }
452
453 if (is_built_in) {
454 set_ok_button_text(TTR("Create"));
455 validation_panel->set_message(MSG_ID_PATH, TTR("Built-in shader (into scene file)."), EditorValidationPanel::MSG_OK);
456 } else if (is_new_shader_created) {
457 set_ok_button_text(TTR("Create"));
458 } else if (load_enabled) {
459 set_ok_button_text(TTR("Load"));
460 if (is_path_valid) {
461 validation_panel->set_message(MSG_ID_PATH, TTR("Will load an existing shader file."), EditorValidationPanel::MSG_OK);
462 }
463 } else {
464 set_ok_button_text(TTR("Create"));
465 validation_panel->set_message(MSG_ID_PATH, TTR("Shader file already exists."), EditorValidationPanel::MSG_ERROR);
466 }
467 }
468
469 void ShaderCreateDialog::_bind_methods() {
470 ClassDB::bind_method(D_METHOD("config", "path", "built_in_enabled", "load_enabled"), &ShaderCreateDialog::config, DEFVAL(true), DEFVAL(true));
471
472 ADD_SIGNAL(MethodInfo("shader_created", PropertyInfo(Variant::OBJECT, "shader", PROPERTY_HINT_RESOURCE_TYPE, "Shader")));
473 ADD_SIGNAL(MethodInfo("shader_include_created", PropertyInfo(Variant::OBJECT, "shader_include", PROPERTY_HINT_RESOURCE_TYPE, "ShaderInclude")));
474 }
475
476 ShaderCreateDialog::ShaderCreateDialog() {
477 _update_language_info();
478
479 // Main Controls.
480
481 gc = memnew(GridContainer);
482 gc->set_columns(2);
483
484 // Error Fields.
485
486 validation_panel = memnew(EditorValidationPanel);
487 validation_panel->add_line(MSG_ID_SHADER, TTR("Shader path/name is valid."));
488 validation_panel->add_line(MSG_ID_PATH, TTR("Will create a new shader file."));
489 validation_panel->add_line(MSG_ID_BUILT_IN);
490 validation_panel->set_update_callback(callable_mp(this, &ShaderCreateDialog::_update_dialog));
491 validation_panel->set_accept_button(get_ok_button());
492
493 // Spacing.
494
495 Control *spacing = memnew(Control);
496 spacing->set_custom_minimum_size(Size2(0, 10 * EDSCALE));
497
498 VBoxContainer *vb = memnew(VBoxContainer);
499 vb->add_child(gc);
500 vb->add_child(spacing);
501 vb->add_child(validation_panel);
502 add_child(vb);
503
504 // Type.
505
506 type_menu = memnew(OptionButton);
507 type_menu->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
508 type_menu->set_accessibility_name(TTRC("Type:"));
509 type_menu->set_custom_minimum_size(Size2(250, 0) * EDSCALE);
510 type_menu->set_h_size_flags(Control::SIZE_EXPAND_FILL);
511 gc->add_child(memnew(Label(TTR("Type:"))));
512 gc->add_child(type_menu);
513
514 type_menu->connect(SceneStringName(item_selected), callable_mp(this, &ShaderCreateDialog::_type_changed));
515
516 // Modes.
517
518 mode_menu = memnew(OptionButton);
519 mode_menu->set_auto_translate_mode(AUTO_TRANSLATE_MODE_DISABLED);
520 mode_menu->set_accessibility_name(TTRC("Mode:"));
521 for (const String &type_name : ShaderTypes::get_singleton()->get_types_list()) {
522 mode_menu->add_item(type_name.capitalize());
523 }
524 gc->add_child(memnew(Label(TTR("Mode:"))));
525 gc->add_child(mode_menu);
526 mode_menu->connect(SceneStringName(item_selected), callable_mp(this, &ShaderCreateDialog::_mode_changed));
527
528 // Templates.
529
530 template_menu = memnew(OptionButton);
531 template_menu->set_accessibility_name(TTRC("Template:"));
532 gc->add_child(memnew(Label(TTR("Template:"))));
533 gc->add_child(template_menu);
534 template_menu->connect(SceneStringName(item_selected), callable_mp(this, &ShaderCreateDialog::_template_changed));
535
536 // Built-in Shader.
537
538 internal = memnew(CheckBox);
539 internal->set_text(TTR("On"));
540 internal->set_accessibility_name(TTRC("Built-in Shader:"));
541 internal->connect(SceneStringName(toggled), callable_mp(this, &ShaderCreateDialog::_built_in_toggled));
542 gc->add_child(memnew(Label(TTR("Built-in Shader:"))));
543 gc->add_child(internal);
544
545 // Path.
546
547 HBoxContainer *hb = memnew(HBoxContainer);
548 hb->set_h_size_flags(Control::SIZE_EXPAND_FILL);
549 hb->connect(SceneStringName(sort_children), callable_mp(this, &ShaderCreateDialog::_path_hbox_sorted));
550 file_path = memnew(LineEdit);
551 file_path->connect(SceneStringName(text_changed), callable_mp(this, &ShaderCreateDialog::_path_changed));
552 file_path->set_accessibility_name(TTRC("Path:"));
553 file_path->set_h_size_flags(Control::SIZE_EXPAND_FILL);
554 hb->add_child(file_path);
555 register_text_enter(file_path);
556 path_button = memnew(Button);
557 path_button->set_accessibility_name(TTRC("Select"));
558 path_button->connect(SceneStringName(pressed), callable_mp(this, &ShaderCreateDialog::_browse_path));
559 hb->add_child(path_button);
560 gc->add_child(memnew(Label(TTR("Path:"))));
561 gc->add_child(hb);
562
563 // Dialog Setup.
564
565 file_browse = memnew(EditorFileDialog);
566 file_browse->connect("file_selected", callable_mp(this, &ShaderCreateDialog::_file_selected));
567 file_browse->set_file_mode(EditorFileDialog::FILE_MODE_OPEN_FILE);
568 add_child(file_browse);
569
570 alert = memnew(AcceptDialog);
571 alert->get_label()->set_autowrap_mode(TextServer::AUTOWRAP_WORD_SMART);
572 alert->get_label()->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
573 alert->get_label()->set_vertical_alignment(VERTICAL_ALIGNMENT_CENTER);
574 alert->get_label()->set_custom_minimum_size(Size2(325, 60) * EDSCALE);
575 add_child(alert);
576
577 set_ok_button_text(TTR("Create"));
578 set_hide_on_ok(false);
579
580 set_title(TTR("Create Shader"));
581 }