resource_importer_texture_atlas.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. /**************************************************************************/
  2. /* resource_importer_texture_atlas.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_atlas.h"
  31. #include "atlas_import_failed.xpm"
  32. #include "core/config/project_settings.h"
  33. #include "core/io/file_access.h"
  34. #include "core/io/image_loader.h"
  35. #include "core/io/resource_saver.h"
  36. #include "core/math/geometry_2d.h"
  37. #include "editor/editor_atlas_packer.h"
  38. #include "scene/resources/atlas_texture.h"
  39. #include "scene/resources/image_texture.h"
  40. #include "scene/resources/mesh.h"
  41. #include "scene/resources/mesh_texture.h"
  42. String ResourceImporterTextureAtlas::get_importer_name() const {
  43. return "texture_atlas";
  44. }
  45. String ResourceImporterTextureAtlas::get_visible_name() const {
  46. return "TextureAtlas";
  47. }
  48. void ResourceImporterTextureAtlas::get_recognized_extensions(List<String> *p_extensions) const {
  49. ImageLoader::get_recognized_extensions(p_extensions);
  50. }
  51. String ResourceImporterTextureAtlas::get_save_extension() const {
  52. return "res";
  53. }
  54. String ResourceImporterTextureAtlas::get_resource_type() const {
  55. return "Texture2D";
  56. }
  57. bool ResourceImporterTextureAtlas::get_option_visibility(const String &p_path, const String &p_option, const HashMap<StringName, Variant> &p_options) const {
  58. if (p_option == "crop_to_region" && int(p_options["import_mode"]) != IMPORT_MODE_REGION) {
  59. return false;
  60. } else if (p_option == "trim_alpha_border_from_region" && int(p_options["import_mode"]) != IMPORT_MODE_REGION) {
  61. return false;
  62. }
  63. return true;
  64. }
  65. int ResourceImporterTextureAtlas::get_preset_count() const {
  66. return 0;
  67. }
  68. String ResourceImporterTextureAtlas::get_preset_name(int p_idx) const {
  69. return String();
  70. }
  71. void ResourceImporterTextureAtlas::get_import_options(const String &p_path, List<ImportOption> *r_options, int p_preset) const {
  72. r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "atlas_file", PROPERTY_HINT_SAVE_FILE, "*.png"), ""));
  73. r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "import_mode", PROPERTY_HINT_ENUM, "Region,Mesh2D", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), 0));
  74. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "crop_to_region"), false));
  75. r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "trim_alpha_border_from_region"), true));
  76. }
  77. String ResourceImporterTextureAtlas::get_option_group_file() const {
  78. return "atlas_file";
  79. }
  80. Error ResourceImporterTextureAtlas::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) {
  81. /* If this happens, it's because the atlas_file field was not filled, so just import a broken texture */
  82. //use an xpm because it's size independent, the editor images are vector and size dependent
  83. //it's a simple hack
  84. Ref<Image> broken = memnew(Image((const char **)atlas_import_failed_xpm));
  85. ResourceSaver::save(ImageTexture::create_from_image(broken), p_save_path + ".tex");
  86. return OK;
  87. }
  88. // FIXME: Rasterization has issues, see https://github.com/godotengine/godot/issues/68350#issuecomment-1305610290
  89. static void _plot_triangle(Vector2i *p_vertices, const Vector2i &p_offset, bool p_transposed, Ref<Image> p_image, const Ref<Image> &p_src_image) {
  90. int width = p_image->get_width();
  91. int height = p_image->get_height();
  92. int src_width = p_src_image->get_width();
  93. int src_height = p_src_image->get_height();
  94. int x[3];
  95. int y[3];
  96. for (int j = 0; j < 3; j++) {
  97. x[j] = p_vertices[j].x;
  98. y[j] = p_vertices[j].y;
  99. }
  100. // sort the points vertically
  101. if (y[1] > y[2]) {
  102. SWAP(x[1], x[2]);
  103. SWAP(y[1], y[2]);
  104. }
  105. if (y[0] > y[1]) {
  106. SWAP(x[0], x[1]);
  107. SWAP(y[0], y[1]);
  108. }
  109. if (y[1] > y[2]) {
  110. SWAP(x[1], x[2]);
  111. SWAP(y[1], y[2]);
  112. }
  113. double dx_far = double(x[2] - x[0]) / (y[2] - y[0] + 1);
  114. double dx_upper = double(x[1] - x[0]) / (y[1] - y[0] + 1);
  115. double dx_low = double(x[2] - x[1]) / (y[2] - y[1] + 1);
  116. double xf = x[0];
  117. double xt = x[0] + dx_upper; // if y[0] == y[1], special case
  118. int max_y = MIN(y[2], p_transposed ? (width - p_offset.x - 1) : (height - p_offset.y - 1));
  119. for (int yi = y[0]; yi < max_y; yi++) {
  120. if (yi >= 0) {
  121. for (int xi = (xf > 0 ? int(xf) : 0); xi < (xt <= src_width ? xt : src_width); xi++) {
  122. int px = xi, py = yi;
  123. int sx = px, sy = py;
  124. sx = CLAMP(sx, 0, src_width - 1);
  125. sy = CLAMP(sy, 0, src_height - 1);
  126. Color color = p_src_image->get_pixel(sx, sy);
  127. if (p_transposed) {
  128. SWAP(px, py);
  129. }
  130. px += p_offset.x;
  131. py += p_offset.y;
  132. //may have been cropped, so don't blit what is not visible?
  133. if (px < 0 || px >= width) {
  134. continue;
  135. }
  136. if (py < 0 || py >= height) {
  137. continue;
  138. }
  139. p_image->set_pixel(px, py, color);
  140. }
  141. for (int xi = (xf < src_width ? int(xf) : src_width - 1); xi >= (xt > 0 ? xt : 0); xi--) {
  142. int px = xi, py = yi;
  143. int sx = px, sy = py;
  144. sx = CLAMP(sx, 0, src_width - 1);
  145. sy = CLAMP(sy, 0, src_height - 1);
  146. Color color = p_src_image->get_pixel(sx, sy);
  147. if (p_transposed) {
  148. SWAP(px, py);
  149. }
  150. px += p_offset.x;
  151. py += p_offset.y;
  152. //may have been cropped, so don't blit what is not visible?
  153. if (px < 0 || px >= width) {
  154. continue;
  155. }
  156. if (py < 0 || py >= height) {
  157. continue;
  158. }
  159. p_image->set_pixel(px, py, color);
  160. }
  161. }
  162. xf += dx_far;
  163. if (yi < y[1]) {
  164. xt += dx_upper;
  165. } else {
  166. xt += dx_low;
  167. }
  168. }
  169. }
  170. Error ResourceImporterTextureAtlas::import_group_file(const String &p_group_file, const HashMap<String, HashMap<StringName, Variant>> &p_source_file_options, const HashMap<String, String> &p_base_paths) {
  171. ERR_FAIL_COND_V(p_source_file_options.is_empty(), ERR_BUG); //should never happen
  172. Vector<EditorAtlasPacker::Chart> charts;
  173. Vector<PackData> pack_data_files;
  174. pack_data_files.resize(p_source_file_options.size());
  175. int idx = 0;
  176. for (const KeyValue<String, HashMap<StringName, Variant>> &E : p_source_file_options) {
  177. PackData &pack_data = pack_data_files.write[idx];
  178. const String &source = E.key;
  179. const HashMap<StringName, Variant> &options = E.value;
  180. Ref<Image> image;
  181. image.instantiate();
  182. Error err = ImageLoader::load_image(source, image);
  183. ERR_CONTINUE(err != OK);
  184. pack_data.image = image;
  185. int mode = options["import_mode"];
  186. if (mode == IMPORT_MODE_REGION) {
  187. pack_data.is_mesh = false;
  188. pack_data.is_cropped = options["crop_to_region"];
  189. EditorAtlasPacker::Chart chart;
  190. Rect2i used_rect = Rect2i(Vector2i(), image->get_size());
  191. if (options["trim_alpha_border_from_region"]) {
  192. // Clip a region from the image.
  193. used_rect = image->get_used_rect();
  194. }
  195. pack_data.region = used_rect;
  196. chart.vertices.push_back(used_rect.position);
  197. chart.vertices.push_back(used_rect.position + Vector2i(used_rect.size.x, 0));
  198. chart.vertices.push_back(used_rect.position + Vector2i(used_rect.size.x, used_rect.size.y));
  199. chart.vertices.push_back(used_rect.position + Vector2i(0, used_rect.size.y));
  200. EditorAtlasPacker::Chart::Face f;
  201. f.vertex[0] = 0;
  202. f.vertex[1] = 1;
  203. f.vertex[2] = 2;
  204. chart.faces.push_back(f);
  205. f.vertex[0] = 0;
  206. f.vertex[1] = 2;
  207. f.vertex[2] = 3;
  208. chart.faces.push_back(f);
  209. chart.can_transpose = false;
  210. pack_data.chart_vertices.push_back(chart.vertices);
  211. pack_data.chart_pieces.push_back(charts.size());
  212. charts.push_back(chart);
  213. } else {
  214. pack_data.is_mesh = true;
  215. Ref<BitMap> bit_map;
  216. bit_map.instantiate();
  217. bit_map->create_from_image_alpha(image);
  218. Vector<Vector<Vector2>> polygons = bit_map->clip_opaque_to_polygons(Rect2(Vector2(), image->get_size()));
  219. for (int j = 0; j < polygons.size(); j++) {
  220. EditorAtlasPacker::Chart chart;
  221. chart.vertices = polygons[j];
  222. chart.can_transpose = true;
  223. Vector<int> poly = Geometry2D::triangulate_polygon(polygons[j]);
  224. for (int i = 0; i < poly.size(); i += 3) {
  225. EditorAtlasPacker::Chart::Face f;
  226. f.vertex[0] = poly[i + 0];
  227. f.vertex[1] = poly[i + 1];
  228. f.vertex[2] = poly[i + 2];
  229. chart.faces.push_back(f);
  230. }
  231. pack_data.chart_pieces.push_back(charts.size());
  232. charts.push_back(chart);
  233. pack_data.chart_vertices.push_back(polygons[j]);
  234. }
  235. }
  236. idx++;
  237. }
  238. const int max_width = (int)GLOBAL_GET("editor/import/atlas_max_width");
  239. //pack the charts
  240. int atlas_width, atlas_height;
  241. EditorAtlasPacker::chart_pack(charts, atlas_width, atlas_height, max_width);
  242. if (atlas_height > max_width * 2) {
  243. WARN_PRINT(vformat(TTR("%s: Atlas texture significantly larger on one axis (%d), consider changing the `editor/import/atlas_max_width` Project Setting to allow a wider texture, making the result more even in size."), p_group_file, atlas_height));
  244. }
  245. //blit the atlas
  246. Ref<Image> new_atlas = Image::create_empty(atlas_width, atlas_height, false, Image::FORMAT_RGBA8);
  247. for (int i = 0; i < pack_data_files.size(); i++) {
  248. PackData &pack_data = pack_data_files.write[i];
  249. for (int j = 0; j < pack_data.chart_pieces.size(); j++) {
  250. const EditorAtlasPacker::Chart &chart = charts[pack_data.chart_pieces[j]];
  251. for (int k = 0; k < chart.faces.size(); k++) {
  252. Vector2i positions[3];
  253. for (int l = 0; l < 3; l++) {
  254. int vertex_idx = chart.faces[k].vertex[l];
  255. positions[l] = Vector2i(chart.vertices[vertex_idx]);
  256. }
  257. _plot_triangle(positions, Vector2i(chart.final_offset), chart.transposed, new_atlas, pack_data.image);
  258. }
  259. }
  260. }
  261. //save the atlas
  262. new_atlas->save_png(p_group_file);
  263. //update cache if existing, else create
  264. Ref<Texture2D> cache;
  265. cache = ResourceCache::get_ref(p_group_file);
  266. if (!cache.is_valid()) {
  267. Ref<ImageTexture> res_cache = ImageTexture::create_from_image(new_atlas);
  268. res_cache->set_path(p_group_file);
  269. cache = res_cache;
  270. }
  271. //save the images
  272. idx = 0;
  273. for (const KeyValue<String, HashMap<StringName, Variant>> &E : p_source_file_options) {
  274. PackData &pack_data = pack_data_files.write[idx];
  275. Ref<Texture2D> texture;
  276. if (!pack_data.is_mesh) {
  277. Vector2 offset = charts[pack_data.chart_pieces[0]].vertices[0] + charts[pack_data.chart_pieces[0]].final_offset;
  278. //region
  279. Ref<AtlasTexture> atlas_texture;
  280. atlas_texture.instantiate();
  281. atlas_texture->set_atlas(cache);
  282. atlas_texture->set_region(Rect2(offset, pack_data.region.size));
  283. if (!pack_data.is_cropped) {
  284. atlas_texture->set_margin(Rect2(pack_data.region.position, pack_data.image->get_size() - pack_data.region.size));
  285. }
  286. texture = atlas_texture;
  287. } else {
  288. Ref<ArrayMesh> mesh;
  289. mesh.instantiate();
  290. for (int i = 0; i < pack_data.chart_pieces.size(); i++) {
  291. const EditorAtlasPacker::Chart &chart = charts[pack_data.chart_pieces[i]];
  292. Vector<Vector2> vertices;
  293. Vector<int> indices;
  294. Vector<Vector2> uvs;
  295. int vc = chart.vertices.size();
  296. int fc = chart.faces.size();
  297. vertices.resize(vc);
  298. uvs.resize(vc);
  299. indices.resize(fc * 3);
  300. {
  301. Vector2 *vw = vertices.ptrw();
  302. int *iw = indices.ptrw();
  303. Vector2 *uvw = uvs.ptrw();
  304. for (int j = 0; j < vc; j++) {
  305. vw[j] = chart.vertices[j];
  306. Vector2 uv = chart.vertices[j];
  307. if (chart.transposed) {
  308. SWAP(uv.x, uv.y);
  309. }
  310. uv += chart.final_offset;
  311. uv /= new_atlas->get_size(); //normalize uv to 0-1 range
  312. uvw[j] = uv;
  313. }
  314. for (int j = 0; j < fc; j++) {
  315. iw[j * 3 + 0] = chart.faces[j].vertex[0];
  316. iw[j * 3 + 1] = chart.faces[j].vertex[1];
  317. iw[j * 3 + 2] = chart.faces[j].vertex[2];
  318. }
  319. }
  320. Array arrays;
  321. arrays.resize(Mesh::ARRAY_MAX);
  322. arrays[Mesh::ARRAY_VERTEX] = vertices;
  323. arrays[Mesh::ARRAY_TEX_UV] = uvs;
  324. arrays[Mesh::ARRAY_INDEX] = indices;
  325. mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arrays);
  326. }
  327. Ref<MeshTexture> mesh_texture;
  328. mesh_texture.instantiate();
  329. mesh_texture->set_base_texture(cache);
  330. mesh_texture->set_image_size(pack_data.image->get_size());
  331. mesh_texture->set_mesh(mesh);
  332. texture = mesh_texture;
  333. }
  334. String save_path = p_base_paths[E.key] + ".res";
  335. ResourceSaver::save(texture, save_path);
  336. idx++;
  337. }
  338. return OK;
  339. }
  340. ResourceImporterTextureAtlas::ResourceImporterTextureAtlas() {
  341. }