resource_importer_texture_atlas.cpp 13 KB

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