resource_importer_texture.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817
  1. /**************************************************************************/
  2. /* resource_importer_texture.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 "resource_importer_texture.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/io/config_file.h"
  33. #include "core/io/image_loader.h"
  34. #include "core/version.h"
  35. #include "editor/editor_file_system.h"
  36. #include "editor/editor_node.h"
  37. #include "editor/gui/editor_toaster.h"
  38. #include "editor/import/resource_importer_texture_settings.h"
  39. #include "editor/themes/editor_scale.h"
  40. #include "editor/themes/editor_theme_manager.h"
  41. #include "scene/resources/compressed_texture.h"
  42. void ResourceImporterTexture::_texture_reimport_roughness(const Ref<CompressedTexture2D> &p_tex, const String &p_normal_path, RS::TextureDetectRoughnessChannel p_channel) {
  43. ERR_FAIL_COND(p_tex.is_null());
  44. MutexLock lock(singleton->mutex);
  45. StringName path = p_tex->get_path();
  46. if (!singleton->make_flags.has(path)) {
  47. singleton->make_flags[path] = MakeInfo();
  48. }
  49. singleton->make_flags[path].flags |= MAKE_ROUGHNESS_FLAG;
  50. singleton->make_flags[path].channel_for_roughness = p_channel;
  51. singleton->make_flags[path].normal_path_for_roughness = p_normal_path;
  52. }
  53. void ResourceImporterTexture::_texture_reimport_3d(const Ref<CompressedTexture2D> &p_tex) {
  54. ERR_FAIL_COND(p_tex.is_null());
  55. MutexLock lock(singleton->mutex);
  56. StringName path = p_tex->get_path();
  57. if (!singleton->make_flags.has(path)) {
  58. singleton->make_flags[path] = MakeInfo();
  59. }
  60. singleton->make_flags[path].flags |= MAKE_3D_FLAG;
  61. }
  62. void ResourceImporterTexture::_texture_reimport_normal(const Ref<CompressedTexture2D> &p_tex) {
  63. ERR_FAIL_COND(p_tex.is_null());
  64. MutexLock lock(singleton->mutex);
  65. StringName path = p_tex->get_path();
  66. if (!singleton->make_flags.has(path)) {
  67. singleton->make_flags[path] = MakeInfo();
  68. }
  69. singleton->make_flags[path].flags |= MAKE_NORMAL_FLAG;
  70. }
  71. void ResourceImporterTexture::update_imports() {
  72. if (EditorFileSystem::get_singleton()->is_scanning() || EditorFileSystem::get_singleton()->is_importing()) {
  73. return; // do nothing for now
  74. }
  75. MutexLock lock(mutex);
  76. Vector<String> to_reimport;
  77. {
  78. if (make_flags.is_empty()) {
  79. return;
  80. }
  81. for (const KeyValue<StringName, MakeInfo> &E : make_flags) {
  82. Ref<ConfigFile> cf;
  83. cf.instantiate();
  84. String src_path = String(E.key) + ".import";
  85. Error err = cf->load(src_path);
  86. ERR_CONTINUE(err != OK);
  87. bool changed = false;
  88. if (E.value.flags & MAKE_NORMAL_FLAG && int(cf->get_value("params", "compress/normal_map")) == 0) {
  89. String message = vformat(TTR("%s: Texture detected as used as a normal map in 3D. Enabling red-green texture compression to reduce memory usage (blue channel is discarded)."), String(E.key));
  90. #ifdef TOOLS_ENABLED
  91. EditorToaster::get_singleton()->popup_str(message);
  92. #endif
  93. print_line(message);
  94. cf->set_value("params", "compress/normal_map", 1);
  95. changed = true;
  96. }
  97. if (E.value.flags & MAKE_ROUGHNESS_FLAG && int(cf->get_value("params", "roughness/mode")) == 0) {
  98. String message = vformat(TTR("%s: Texture detected as used as a roughness map in 3D. Enabling roughness limiter based on the detected associated normal map at %s."), String(E.key), E.value.normal_path_for_roughness);
  99. #ifdef TOOLS_ENABLED
  100. EditorToaster::get_singleton()->popup_str(message);
  101. #endif
  102. print_line(message);
  103. cf->set_value("params", "roughness/mode", E.value.channel_for_roughness + 2);
  104. cf->set_value("params", "roughness/src_normal", E.value.normal_path_for_roughness);
  105. changed = true;
  106. }
  107. if (E.value.flags & MAKE_3D_FLAG && bool(cf->get_value("params", "detect_3d/compress_to"))) {
  108. const int compress_to = cf->get_value("params", "detect_3d/compress_to");
  109. String compress_string;
  110. cf->set_value("params", "detect_3d/compress_to", 0);
  111. if (compress_to == 1) {
  112. cf->set_value("params", "compress/mode", COMPRESS_VRAM_COMPRESSED);
  113. compress_string = "VRAM Compressed (S3TC/ETC/BPTC)";
  114. } else if (compress_to == 2) {
  115. cf->set_value("params", "compress/mode", COMPRESS_BASIS_UNIVERSAL);
  116. compress_string = "Basis Universal";
  117. }
  118. String message = vformat(TTR("%s: Texture detected as used in 3D. Enabling mipmap generation and setting the texture compression mode to %s."), String(E.key), compress_string);
  119. #ifdef TOOLS_ENABLED
  120. EditorToaster::get_singleton()->popup_str(message);
  121. #endif
  122. print_line(message);
  123. cf->set_value("params", "mipmaps/generate", true);
  124. changed = true;
  125. }
  126. if (changed) {
  127. cf->save(src_path);
  128. to_reimport.push_back(E.key);
  129. }
  130. }
  131. make_flags.clear();
  132. }
  133. if (to_reimport.size()) {
  134. EditorFileSystem::get_singleton()->reimport_files(to_reimport);
  135. }
  136. }
  137. String ResourceImporterTexture::get_importer_name() const {
  138. return "texture";
  139. }
  140. String ResourceImporterTexture::get_visible_name() const {
  141. return "Texture2D";
  142. }
  143. void ResourceImporterTexture::get_recognized_extensions(List<String> *p_extensions) const {
  144. ImageLoader::get_recognized_extensions(p_extensions);
  145. }
  146. String ResourceImporterTexture::get_save_extension() const {
  147. return "ctex";
  148. }
  149. String ResourceImporterTexture::get_resource_type() const {
  150. return "CompressedTexture2D";
  151. }
  152. bool ResourceImporterTexture::get_option_visibility(const String &p_path, const String &p_option, const HashMap<StringName, Variant> &p_options) const {
  153. if (p_option == "compress/high_quality" || p_option == "compress/hdr_compression") {
  154. int compress_mode = int(p_options["compress/mode"]);
  155. if (compress_mode != COMPRESS_VRAM_COMPRESSED) {
  156. return false;
  157. }
  158. } else if (p_option == "compress/lossy_quality") {
  159. int compress_mode = int(p_options["compress/mode"]);
  160. if (compress_mode != COMPRESS_LOSSY) {
  161. return false;
  162. }
  163. } else if (p_option == "compress/hdr_mode") {
  164. int compress_mode = int(p_options["compress/mode"]);
  165. if (compress_mode < COMPRESS_VRAM_COMPRESSED) {
  166. return false;
  167. }
  168. } else if (p_option == "compress/normal_map") {
  169. int compress_mode = int(p_options["compress/mode"]);
  170. if (compress_mode == COMPRESS_LOSSLESS) {
  171. return false;
  172. }
  173. } else if (p_option == "mipmaps/limit") {
  174. return p_options["mipmaps/generate"];
  175. }
  176. return true;
  177. }
  178. int ResourceImporterTexture::get_preset_count() const {
  179. return 3;
  180. }
  181. String ResourceImporterTexture::get_preset_name(int p_idx) const {
  182. static const char *preset_names[] = {
  183. TTRC("2D/3D (Auto-Detect)"),
  184. TTRC("2D"),
  185. TTRC("3D"),
  186. };
  187. return TTRGET(preset_names[p_idx]);
  188. }
  189. void ResourceImporterTexture::get_import_options(const String &p_path, List<ImportOption> *r_options, int p_preset) const {
  190. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "compress/mode", PROPERTY_HINT_ENUM, "Lossless,Lossy,VRAM Compressed,VRAM Uncompressed,Basis Universal", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), p_preset == PRESET_3D ? 2 : 0));
  191. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "compress/high_quality"), false));
  192. r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "compress/lossy_quality", PROPERTY_HINT_RANGE, "0,1,0.01"), 0.7));
  193. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "compress/hdr_compression", PROPERTY_HINT_ENUM, "Disabled,Opaque Only,Always"), 1));
  194. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "compress/normal_map", PROPERTY_HINT_ENUM, "Detect,Enable,Disabled"), 0));
  195. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "compress/channel_pack", PROPERTY_HINT_ENUM, "sRGB Friendly,Optimized"), 0));
  196. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "mipmaps/generate"), (p_preset == PRESET_3D ? true : false)));
  197. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "mipmaps/limit", PROPERTY_HINT_RANGE, "-1,256"), -1));
  198. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "roughness/mode", PROPERTY_HINT_ENUM, "Detect,Disabled,Red,Green,Blue,Alpha,Gray"), 0));
  199. r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "roughness/src_normal", PROPERTY_HINT_FILE, "*.bmp,*.dds,*.exr,*.jpeg,*.jpg,*.hdr,*.png,*.svg,*.tga,*.webp"), ""));
  200. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "process/fix_alpha_border"), p_preset != PRESET_3D));
  201. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "process/premult_alpha"), false));
  202. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "process/normal_map_invert_y"), false));
  203. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "process/hdr_as_srgb"), false));
  204. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "process/hdr_clamp_exposure"), false));
  205. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "process/size_limit", PROPERTY_HINT_RANGE, "0,4096,1"), 0));
  206. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "detect_3d/compress_to", PROPERTY_HINT_ENUM, "Disabled,VRAM Compressed,Basis Universal"), (p_preset == PRESET_DETECT) ? 1 : 0));
  207. // Do path based customization only if a path was passed.
  208. if (p_path.is_empty() || p_path.get_extension() == "svg") {
  209. r_options->push_back(ImportOption(PropertyInfo(Variant::FLOAT, "svg/scale", PROPERTY_HINT_RANGE, "0.001,100,0.001"), 1.0));
  210. // Editor use only, applies to SVG.
  211. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "editor/scale_with_editor_scale"), false));
  212. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "editor/convert_colors_with_editor_theme"), false));
  213. }
  214. }
  215. void ResourceImporterTexture::save_to_ctex_format(Ref<FileAccess> f, const Ref<Image> &p_image, CompressMode p_compress_mode, Image::UsedChannels p_channels, Image::CompressMode p_compress_format, float p_lossy_quality) {
  216. switch (p_compress_mode) {
  217. case COMPRESS_LOSSLESS: {
  218. bool lossless_force_png = GLOBAL_GET("rendering/textures/lossless_compression/force_png") ||
  219. !Image::_webp_mem_loader_func; // WebP module disabled.
  220. bool use_webp = !lossless_force_png && p_image->get_width() <= 16383 && p_image->get_height() <= 16383; // WebP has a size limit
  221. f->store_32(use_webp ? CompressedTexture2D::DATA_FORMAT_WEBP : CompressedTexture2D::DATA_FORMAT_PNG);
  222. f->store_16(p_image->get_width());
  223. f->store_16(p_image->get_height());
  224. f->store_32(p_image->get_mipmap_count());
  225. f->store_32(p_image->get_format());
  226. for (int i = 0; i < p_image->get_mipmap_count() + 1; i++) {
  227. Vector<uint8_t> data;
  228. if (use_webp) {
  229. data = Image::webp_lossless_packer(p_image->get_image_from_mipmap(i));
  230. } else {
  231. data = Image::png_packer(p_image->get_image_from_mipmap(i));
  232. }
  233. int data_len = data.size();
  234. f->store_32(data_len);
  235. const uint8_t *r = data.ptr();
  236. f->store_buffer(r, data_len);
  237. }
  238. } break;
  239. case COMPRESS_LOSSY: {
  240. f->store_32(CompressedTexture2D::DATA_FORMAT_WEBP);
  241. f->store_16(p_image->get_width());
  242. f->store_16(p_image->get_height());
  243. f->store_32(p_image->get_mipmap_count());
  244. f->store_32(p_image->get_format());
  245. for (int i = 0; i < p_image->get_mipmap_count() + 1; i++) {
  246. Vector<uint8_t> data = Image::webp_lossy_packer(p_image->get_image_from_mipmap(i), p_lossy_quality);
  247. int data_len = data.size();
  248. f->store_32(data_len);
  249. const uint8_t *r = data.ptr();
  250. f->store_buffer(r, data_len);
  251. }
  252. } break;
  253. case COMPRESS_VRAM_COMPRESSED: {
  254. Ref<Image> image = p_image->duplicate();
  255. image->compress_from_channels(p_compress_format, p_channels);
  256. f->store_32(CompressedTexture2D::DATA_FORMAT_IMAGE);
  257. f->store_16(image->get_width());
  258. f->store_16(image->get_height());
  259. f->store_32(image->get_mipmap_count());
  260. f->store_32(image->get_format());
  261. Vector<uint8_t> data = image->get_data();
  262. int dl = data.size();
  263. const uint8_t *r = data.ptr();
  264. f->store_buffer(r, dl);
  265. } break;
  266. case COMPRESS_VRAM_UNCOMPRESSED: {
  267. f->store_32(CompressedTexture2D::DATA_FORMAT_IMAGE);
  268. f->store_16(p_image->get_width());
  269. f->store_16(p_image->get_height());
  270. f->store_32(p_image->get_mipmap_count());
  271. f->store_32(p_image->get_format());
  272. Vector<uint8_t> data = p_image->get_data();
  273. int dl = data.size();
  274. const uint8_t *r = data.ptr();
  275. f->store_buffer(r, dl);
  276. } break;
  277. case COMPRESS_BASIS_UNIVERSAL: {
  278. f->store_32(CompressedTexture2D::DATA_FORMAT_BASIS_UNIVERSAL);
  279. f->store_16(p_image->get_width());
  280. f->store_16(p_image->get_height());
  281. f->store_32(p_image->get_mipmap_count());
  282. f->store_32(p_image->get_format());
  283. Vector<uint8_t> data = Image::basis_universal_packer(p_image, p_channels);
  284. int data_len = data.size();
  285. f->store_32(data_len);
  286. const uint8_t *r = data.ptr();
  287. f->store_buffer(r, data_len);
  288. } break;
  289. }
  290. }
  291. void ResourceImporterTexture::_save_ctex(const Ref<Image> &p_image, const String &p_to_path, CompressMode p_compress_mode, float p_lossy_quality, Image::CompressMode p_vram_compression, bool p_mipmaps, bool p_streamable, bool p_detect_3d, bool p_detect_roughness, bool p_detect_normal, bool p_force_normal, bool p_srgb_friendly, bool p_force_po2_for_compressed, uint32_t p_limit_mipmap, const Ref<Image> &p_normal, Image::RoughnessChannel p_roughness_channel) {
  292. Ref<FileAccess> f = FileAccess::open(p_to_path, FileAccess::WRITE);
  293. ERR_FAIL_COND(f.is_null());
  294. f->store_8('G');
  295. f->store_8('S');
  296. f->store_8('T');
  297. f->store_8('2'); //godot streamable texture 2D
  298. //format version
  299. f->store_32(CompressedTexture2D::FORMAT_VERSION);
  300. //texture may be resized later, so original size must be saved first
  301. f->store_32(p_image->get_width());
  302. f->store_32(p_image->get_height());
  303. uint32_t flags = 0;
  304. if (p_streamable) {
  305. flags |= CompressedTexture2D::FORMAT_BIT_STREAM;
  306. }
  307. if (p_mipmaps) {
  308. flags |= CompressedTexture2D::FORMAT_BIT_HAS_MIPMAPS; //mipmaps bit
  309. }
  310. if (p_detect_3d) {
  311. flags |= CompressedTexture2D::FORMAT_BIT_DETECT_3D;
  312. }
  313. if (p_detect_roughness) {
  314. flags |= CompressedTexture2D::FORMAT_BIT_DETECT_ROUGNESS;
  315. }
  316. if (p_detect_normal) {
  317. flags |= CompressedTexture2D::FORMAT_BIT_DETECT_NORMAL;
  318. }
  319. f->store_32(flags);
  320. f->store_32(p_limit_mipmap);
  321. //reserved for future use
  322. f->store_32(0);
  323. f->store_32(0);
  324. f->store_32(0);
  325. if ((p_compress_mode == COMPRESS_LOSSLESS || p_compress_mode == COMPRESS_LOSSY) && p_image->get_format() > Image::FORMAT_RGBA8) {
  326. p_compress_mode = COMPRESS_VRAM_UNCOMPRESSED; //these can't go as lossy
  327. }
  328. Ref<Image> image = p_image->duplicate();
  329. if (p_force_po2_for_compressed && p_mipmaps && ((p_compress_mode == COMPRESS_BASIS_UNIVERSAL) || (p_compress_mode == COMPRESS_VRAM_COMPRESSED))) {
  330. image->resize_to_po2();
  331. }
  332. if (p_mipmaps && (!image->has_mipmaps() || p_force_normal)) {
  333. image->generate_mipmaps(p_force_normal);
  334. }
  335. if (!p_mipmaps) {
  336. image->clear_mipmaps();
  337. }
  338. if (image->has_mipmaps() && p_normal.is_valid()) {
  339. image->generate_mipmap_roughness(p_roughness_channel, p_normal);
  340. }
  341. Image::CompressSource csource = Image::COMPRESS_SOURCE_GENERIC;
  342. if (p_force_normal) {
  343. csource = Image::COMPRESS_SOURCE_NORMAL;
  344. } else if (p_srgb_friendly) {
  345. csource = Image::COMPRESS_SOURCE_SRGB;
  346. }
  347. Image::UsedChannels used_channels = image->detect_used_channels(csource);
  348. save_to_ctex_format(f, image, p_compress_mode, used_channels, p_vram_compression, p_lossy_quality);
  349. }
  350. void ResourceImporterTexture::_save_editor_meta(const Dictionary &p_metadata, const String &p_to_path) {
  351. Ref<FileAccess> f = FileAccess::open(p_to_path, FileAccess::WRITE);
  352. ERR_FAIL_COND(f.is_null());
  353. f->store_var(p_metadata);
  354. }
  355. Dictionary ResourceImporterTexture::_load_editor_meta(const String &p_path) const {
  356. Ref<FileAccess> f = FileAccess::open(p_path, FileAccess::READ);
  357. ERR_FAIL_COND_V_MSG(f.is_null(), Dictionary(), vformat("Missing required editor-specific import metadata for a texture (please reimport it using the 'Import' tab): '%s'", p_path));
  358. return f->get_var();
  359. }
  360. Error ResourceImporterTexture::import(const String &p_source_file, const String &p_save_path, const HashMap<StringName, Variant> &p_options, List<String> *r_platform_variants, List<String> *r_gen_files, Variant *r_metadata) {
  361. // Parse import options.
  362. int32_t loader_flags = ImageFormatLoader::FLAG_NONE;
  363. // Compression.
  364. CompressMode compress_mode = CompressMode(int(p_options["compress/mode"]));
  365. const float lossy = p_options["compress/lossy_quality"];
  366. const int pack_channels = p_options["compress/channel_pack"];
  367. const int normal = p_options["compress/normal_map"];
  368. const int hdr_compression = p_options["compress/hdr_compression"];
  369. const int high_quality = p_options["compress/high_quality"];
  370. // Mipmaps.
  371. const bool mipmaps = p_options["mipmaps/generate"];
  372. const uint32_t mipmap_limit = mipmaps ? uint32_t(p_options["mipmaps/limit"]) : uint32_t(-1);
  373. // Roughness.
  374. const int roughness = p_options["roughness/mode"];
  375. const String normal_map = p_options["roughness/src_normal"];
  376. // Processing.
  377. const bool fix_alpha_border = p_options["process/fix_alpha_border"];
  378. const bool premult_alpha = p_options["process/premult_alpha"];
  379. const bool normal_map_invert_y = p_options["process/normal_map_invert_y"];
  380. // Support for texture streaming is not implemented yet.
  381. const bool stream = false;
  382. const int size_limit = p_options["process/size_limit"];
  383. const bool hdr_as_srgb = p_options["process/hdr_as_srgb"];
  384. if (hdr_as_srgb) {
  385. loader_flags |= ImageFormatLoader::FLAG_FORCE_LINEAR;
  386. }
  387. const bool hdr_clamp_exposure = p_options["process/hdr_clamp_exposure"];
  388. float scale = 1.0;
  389. // SVG-specific options.
  390. if (p_options.has("svg/scale")) {
  391. scale = p_options["svg/scale"];
  392. }
  393. // Editor-specific options.
  394. bool use_editor_scale = p_options.has("editor/scale_with_editor_scale") && p_options["editor/scale_with_editor_scale"];
  395. bool convert_editor_colors = p_options.has("editor/convert_colors_with_editor_theme") && p_options["editor/convert_colors_with_editor_theme"];
  396. // Start importing images.
  397. List<Ref<Image>> images_imported;
  398. // Load the normal image.
  399. Ref<Image> normal_image;
  400. Image::RoughnessChannel roughness_channel = Image::ROUGHNESS_CHANNEL_R;
  401. if (mipmaps && roughness > 1 && FileAccess::exists(normal_map)) {
  402. normal_image.instantiate();
  403. if (ImageLoader::load_image(normal_map, normal_image) == OK) {
  404. roughness_channel = Image::RoughnessChannel(roughness - 2);
  405. }
  406. }
  407. // Load the main image.
  408. Ref<Image> image;
  409. image.instantiate();
  410. Error err = ImageLoader::load_image(p_source_file, image, nullptr, loader_flags, scale);
  411. if (err != OK) {
  412. return err;
  413. }
  414. images_imported.push_back(image);
  415. // Load the editor-only image.
  416. Ref<Image> editor_image;
  417. bool import_editor_image = use_editor_scale || convert_editor_colors;
  418. if (import_editor_image) {
  419. float editor_scale = scale;
  420. if (use_editor_scale) {
  421. editor_scale = scale * EDSCALE;
  422. }
  423. int32_t editor_loader_flags = loader_flags;
  424. if (convert_editor_colors) {
  425. editor_loader_flags |= ImageFormatLoader::FLAG_CONVERT_COLORS;
  426. }
  427. editor_image.instantiate();
  428. err = ImageLoader::load_image(p_source_file, editor_image, nullptr, editor_loader_flags, editor_scale);
  429. if (err != OK) {
  430. WARN_PRINT("Failed to import an image resource for editor use from '" + p_source_file + "'");
  431. } else {
  432. images_imported.push_back(editor_image);
  433. }
  434. }
  435. for (Ref<Image> &target_image : images_imported) {
  436. // Apply the size limit.
  437. if (size_limit > 0 && (target_image->get_width() > size_limit || target_image->get_height() > size_limit)) {
  438. if (target_image->get_width() >= target_image->get_height()) {
  439. int new_width = size_limit;
  440. int new_height = target_image->get_height() * new_width / target_image->get_width();
  441. target_image->resize(new_width, new_height, Image::INTERPOLATE_CUBIC);
  442. } else {
  443. int new_height = size_limit;
  444. int new_width = target_image->get_width() * new_height / target_image->get_height();
  445. target_image->resize(new_width, new_height, Image::INTERPOLATE_CUBIC);
  446. }
  447. if (normal == 1) {
  448. target_image->normalize();
  449. }
  450. }
  451. // Fix alpha border.
  452. if (fix_alpha_border) {
  453. target_image->fix_alpha_edges();
  454. }
  455. // Premultiply the alpha.
  456. if (premult_alpha) {
  457. target_image->premultiply_alpha();
  458. }
  459. // Invert the green channel of the image to flip the normal map it contains.
  460. if (normal_map_invert_y) {
  461. // Inverting the green channel can be used to flip a normal map's direction.
  462. // There's no standard when it comes to normal map Y direction, so this is
  463. // sometimes needed when using a normal map exported from another program.
  464. // See <http://wiki.polycount.com/wiki/Normal_Map_Technical_Details#Common_Swizzle_Coordinates>.
  465. const int height = target_image->get_height();
  466. const int width = target_image->get_width();
  467. for (int i = 0; i < width; i++) {
  468. for (int j = 0; j < height; j++) {
  469. const Color color = target_image->get_pixel(i, j);
  470. target_image->set_pixel(i, j, Color(color.r, 1 - color.g, color.b));
  471. }
  472. }
  473. }
  474. // Clamp HDR exposure.
  475. if (hdr_clamp_exposure) {
  476. // Clamp HDR exposure following Filament's tonemapping formula.
  477. // This can be used to reduce fireflies in environment maps or reduce the influence
  478. // of the sun from an HDRI panorama on environment lighting (when a DirectionalLight3D is used instead).
  479. const int height = target_image->get_height();
  480. const int width = target_image->get_width();
  481. // These values are chosen arbitrarily and seem to produce good results with 4,096 samples.
  482. const float linear = 4096.0;
  483. const float compressed = 16384.0;
  484. for (int i = 0; i < width; i++) {
  485. for (int j = 0; j < height; j++) {
  486. const Color color = target_image->get_pixel(i, j);
  487. const float luma = color.get_luminance();
  488. Color clamped_color;
  489. if (luma <= linear) {
  490. clamped_color = color;
  491. } else {
  492. clamped_color = (color / luma) * ((linear * linear - compressed * luma) / (2 * linear - compressed - luma));
  493. }
  494. target_image->set_pixel(i, j, clamped_color);
  495. }
  496. }
  497. }
  498. }
  499. if (compress_mode == COMPRESS_BASIS_UNIVERSAL && image->get_format() >= Image::FORMAT_RF) {
  500. // Basis universal does not support float formats, fallback.
  501. compress_mode = COMPRESS_VRAM_COMPRESSED;
  502. }
  503. bool detect_3d = int(p_options["detect_3d/compress_to"]) > 0;
  504. bool detect_roughness = roughness == 0;
  505. bool detect_normal = normal == 0;
  506. bool force_normal = normal == 1;
  507. bool srgb_friendly_pack = pack_channels == 0;
  508. Array formats_imported;
  509. if (compress_mode == COMPRESS_VRAM_COMPRESSED) {
  510. // Must import in all formats, in order of priority (so platform choses the best supported one. IE, etc2 over etc).
  511. // Android, GLES 2.x
  512. const bool is_hdr = (image->get_format() >= Image::FORMAT_RF && image->get_format() <= Image::FORMAT_RGBE9995);
  513. const bool can_s3tc_bptc = ResourceImporterTextureSettings::should_import_s3tc_bptc();
  514. const bool can_etc2_astc = ResourceImporterTextureSettings::should_import_etc2_astc();
  515. // Add list of formats imported
  516. if (can_s3tc_bptc) {
  517. formats_imported.push_back("s3tc_bptc");
  518. }
  519. if (can_etc2_astc) {
  520. formats_imported.push_back("etc2_astc");
  521. }
  522. bool can_compress_hdr = hdr_compression > 0;
  523. bool has_alpha = image->detect_alpha() != Image::ALPHA_NONE;
  524. bool use_uncompressed = false;
  525. if (is_hdr) {
  526. if (has_alpha) {
  527. // Can compress HDR, but HDR with alpha is not compressible.
  528. if (hdr_compression == 2) {
  529. // But user selected to compress HDR anyway, so force an alpha-less format.
  530. if (image->get_format() == Image::FORMAT_RGBAF) {
  531. image->convert(Image::FORMAT_RGBF);
  532. } else if (image->get_format() == Image::FORMAT_RGBAH) {
  533. image->convert(Image::FORMAT_RGBH);
  534. }
  535. } else {
  536. can_compress_hdr = false;
  537. }
  538. }
  539. if (!can_compress_hdr) {
  540. // Fallback to RGBE99995.
  541. if (image->get_format() != Image::FORMAT_RGBE9995) {
  542. image->convert(Image::FORMAT_RGBE9995);
  543. use_uncompressed = true;
  544. }
  545. }
  546. }
  547. if (use_uncompressed) {
  548. _save_ctex(image, p_save_path + ".ctex", COMPRESS_VRAM_UNCOMPRESSED, lossy, Image::COMPRESS_S3TC /*this is ignored */, mipmaps, stream, detect_3d, detect_roughness, detect_normal, force_normal, srgb_friendly_pack, false, mipmap_limit, normal_image, roughness_channel);
  549. } else {
  550. if (can_s3tc_bptc) {
  551. Image::CompressMode image_compress_mode;
  552. String image_compress_format;
  553. if (high_quality || is_hdr) {
  554. image_compress_mode = Image::COMPRESS_BPTC;
  555. image_compress_format = "bptc";
  556. } else {
  557. image_compress_mode = Image::COMPRESS_S3TC;
  558. image_compress_format = "s3tc";
  559. }
  560. _save_ctex(image, p_save_path + "." + image_compress_format + ".ctex", compress_mode, lossy, image_compress_mode, mipmaps, stream, detect_3d, detect_roughness, detect_normal, force_normal, srgb_friendly_pack, false, mipmap_limit, normal_image, roughness_channel);
  561. r_platform_variants->push_back(image_compress_format);
  562. }
  563. if (can_etc2_astc) {
  564. Image::CompressMode image_compress_mode;
  565. String image_compress_format;
  566. if (high_quality || is_hdr) {
  567. image_compress_mode = Image::COMPRESS_ASTC;
  568. image_compress_format = "astc";
  569. } else {
  570. image_compress_mode = Image::COMPRESS_ETC2;
  571. image_compress_format = "etc2";
  572. }
  573. _save_ctex(image, p_save_path + "." + image_compress_format + ".ctex", compress_mode, lossy, image_compress_mode, mipmaps, stream, detect_3d, detect_roughness, detect_normal, force_normal, srgb_friendly_pack, false, mipmap_limit, normal_image, roughness_channel);
  574. r_platform_variants->push_back(image_compress_format);
  575. }
  576. }
  577. } else {
  578. // Import normally.
  579. _save_ctex(image, p_save_path + ".ctex", compress_mode, lossy, Image::COMPRESS_S3TC /*this is ignored */, mipmaps, stream, detect_3d, detect_roughness, detect_normal, force_normal, srgb_friendly_pack, false, mipmap_limit, normal_image, roughness_channel);
  580. }
  581. if (editor_image.is_valid()) {
  582. _save_ctex(editor_image, p_save_path + ".editor.ctex", compress_mode, lossy, Image::COMPRESS_S3TC /*this is ignored */, mipmaps, stream, detect_3d, detect_roughness, detect_normal, force_normal, srgb_friendly_pack, false, mipmap_limit, normal_image, roughness_channel);
  583. // Generate and save editor-specific metadata, which we cannot save to the .import file.
  584. Dictionary editor_meta;
  585. if (use_editor_scale) {
  586. editor_meta["editor_scale"] = EDSCALE;
  587. }
  588. if (convert_editor_colors) {
  589. editor_meta["editor_dark_theme"] = EditorThemeManager::is_dark_theme();
  590. }
  591. _save_editor_meta(editor_meta, p_save_path + ".editor.meta");
  592. }
  593. if (r_metadata) {
  594. Dictionary meta;
  595. meta["vram_texture"] = compress_mode == COMPRESS_VRAM_COMPRESSED;
  596. if (formats_imported.size()) {
  597. meta["imported_formats"] = formats_imported;
  598. }
  599. if (editor_image.is_valid()) {
  600. meta["has_editor_variant"] = true;
  601. }
  602. *r_metadata = meta;
  603. }
  604. return OK;
  605. }
  606. const char *ResourceImporterTexture::compression_formats[] = {
  607. "s3tc_bptc",
  608. "etc2_astc",
  609. nullptr
  610. };
  611. String ResourceImporterTexture::get_import_settings_string() const {
  612. String s;
  613. int index = 0;
  614. while (compression_formats[index]) {
  615. String setting_path = "rendering/textures/vram_compression/import_" + String(compression_formats[index]);
  616. bool test = GLOBAL_GET(setting_path);
  617. if (test) {
  618. s += String(compression_formats[index]);
  619. }
  620. index++;
  621. }
  622. return s;
  623. }
  624. bool ResourceImporterTexture::are_import_settings_valid(const String &p_path) const {
  625. Dictionary meta = ResourceFormatImporter::get_singleton()->get_resource_metadata(p_path);
  626. if (meta.has("has_editor_variant")) {
  627. String imported_path = ResourceFormatImporter::get_singleton()->get_internal_resource_path(p_path);
  628. if (!FileAccess::exists(imported_path)) {
  629. return false;
  630. }
  631. String editor_meta_path = imported_path.replace(".editor.ctex", ".editor.meta");
  632. Dictionary editor_meta = _load_editor_meta(editor_meta_path);
  633. if (editor_meta.has("editor_scale") && (float)editor_meta["editor_scale"] != EDSCALE) {
  634. return false;
  635. }
  636. if (editor_meta.has("editor_dark_theme") && (bool)editor_meta["editor_dark_theme"] != EditorThemeManager::is_dark_theme()) {
  637. return false;
  638. }
  639. }
  640. if (!meta.has("vram_texture")) {
  641. return false;
  642. }
  643. bool vram = meta["vram_texture"];
  644. if (!vram) {
  645. return true; // Do not care about non-VRAM.
  646. }
  647. // Will become invalid if formats are missing to import.
  648. Vector<String> formats_imported;
  649. if (meta.has("imported_formats")) {
  650. formats_imported = meta["imported_formats"];
  651. }
  652. int index = 0;
  653. bool valid = true;
  654. while (compression_formats[index]) {
  655. String setting_path = "rendering/textures/vram_compression/import_" + String(compression_formats[index]);
  656. if (ProjectSettings::get_singleton()->has_setting(setting_path)) {
  657. bool test = GLOBAL_GET(setting_path);
  658. if (test) {
  659. if (!formats_imported.has(compression_formats[index])) {
  660. valid = false;
  661. break;
  662. }
  663. }
  664. } else {
  665. WARN_PRINT("Setting for imported format not found: " + setting_path);
  666. }
  667. index++;
  668. }
  669. return valid;
  670. }
  671. ResourceImporterTexture *ResourceImporterTexture::singleton = nullptr;
  672. ResourceImporterTexture::ResourceImporterTexture(bool p_singleton) {
  673. // This should only be set through the EditorNode.
  674. if (p_singleton) {
  675. singleton = this;
  676. }
  677. CompressedTexture2D::request_3d_callback = _texture_reimport_3d;
  678. CompressedTexture2D::request_roughness_callback = _texture_reimport_roughness;
  679. CompressedTexture2D::request_normal_callback = _texture_reimport_normal;
  680. }
  681. ResourceImporterTexture::~ResourceImporterTexture() {
  682. if (singleton == this) {
  683. singleton = nullptr;
  684. }
  685. }