resource_importer_texture_atlas.cpp 14 KB

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