resource_importer_texture_atlas.cpp 13 KB

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