Path: blob/master/editor/import/resource_importer_texture_atlas.cpp
9898 views
/**************************************************************************/1/* resource_importer_texture_atlas.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "resource_importer_texture_atlas.h"3132#include "atlas_import_failed.xpm"33#include "core/config/project_settings.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/import/editor_atlas_packer.h"38#include "scene/resources/atlas_texture.h"39#include "scene/resources/bit_map.h"40#include "scene/resources/image_texture.h"41#include "scene/resources/mesh.h"42#include "scene/resources/mesh_texture.h"4344String ResourceImporterTextureAtlas::get_importer_name() const {45return "texture_atlas";46}4748String ResourceImporterTextureAtlas::get_visible_name() const {49return "TextureAtlas";50}5152void ResourceImporterTextureAtlas::get_recognized_extensions(List<String> *p_extensions) const {53ImageLoader::get_recognized_extensions(p_extensions);54}5556String ResourceImporterTextureAtlas::get_save_extension() const {57return "res";58}5960String ResourceImporterTextureAtlas::get_resource_type() const {61return "Texture2D";62}6364bool ResourceImporterTextureAtlas::get_option_visibility(const String &p_path, const String &p_option, const HashMap<StringName, Variant> &p_options) const {65if (p_option == "crop_to_region" && int(p_options["import_mode"]) != IMPORT_MODE_REGION) {66return false;67} else if (p_option == "trim_alpha_border_from_region" && int(p_options["import_mode"]) != IMPORT_MODE_REGION) {68return false;69}7071return true;72}7374int ResourceImporterTextureAtlas::get_preset_count() const {75return 0;76}7778String ResourceImporterTextureAtlas::get_preset_name(int p_idx) const {79return String();80}8182void ResourceImporterTextureAtlas::get_import_options(const String &p_path, List<ImportOption> *r_options, int p_preset) const {83r_options->push_back(ImportOption(PropertyInfo(Variant::STRING, "atlas_file", PROPERTY_HINT_SAVE_FILE, "*.png"), ""));84r_options->push_back(ImportOption(PropertyInfo(Variant::INT, "import_mode", PROPERTY_HINT_ENUM, "Region,Mesh2D", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), 0));85r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "crop_to_region"), false));86r_options->push_back(ImportOption(PropertyInfo(Variant::BOOL, "trim_alpha_border_from_region"), true));87}8889String ResourceImporterTextureAtlas::get_option_group_file() const {90return "atlas_file";91}9293Error ResourceImporterTextureAtlas::import(ResourceUID::ID p_source_id, 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) {94/* If this happens, it's because the atlas_file field was not filled, so just import a broken texture */9596//use an xpm because it's size independent, the editor images are vector and size dependent97//it's a simple hack98Ref<Image> broken = memnew(Image((const char **)atlas_import_failed_xpm));99ResourceSaver::save(ImageTexture::create_from_image(broken), p_save_path + ".tex");100101return OK;102}103104// FIXME: Rasterization has issues, see https://github.com/godotengine/godot/issues/68350#issuecomment-1305610290105static void _plot_triangle(Vector2i *p_vertices, const Vector2i &p_offset, bool p_transposed, Ref<Image> p_image, const Ref<Image> &p_src_image) {106int width = p_image->get_width();107int height = p_image->get_height();108int src_width = p_src_image->get_width();109int src_height = p_src_image->get_height();110111int x[3];112int y[3];113114for (int j = 0; j < 3; j++) {115x[j] = p_vertices[j].x;116y[j] = p_vertices[j].y;117}118119// sort the points vertically120if (y[1] > y[2]) {121SWAP(x[1], x[2]);122SWAP(y[1], y[2]);123}124if (y[0] > y[1]) {125SWAP(x[0], x[1]);126SWAP(y[0], y[1]);127}128if (y[1] > y[2]) {129SWAP(x[1], x[2]);130SWAP(y[1], y[2]);131}132133double dx_far = double(x[2] - x[0]) / (y[2] - y[0] + 1);134double dx_upper = double(x[1] - x[0]) / (y[1] - y[0] + 1);135double dx_low = double(x[2] - x[1]) / (y[2] - y[1] + 1);136double xf = x[0];137double xt = x[0] + dx_upper; // if y[0] == y[1], special case138int max_y = MIN(y[2], p_transposed ? (width - p_offset.x - 1) : (height - p_offset.y - 1));139for (int yi = y[0]; yi < max_y; yi++) {140if (yi >= 0) {141for (int xi = (xf > 0 ? int(xf) : 0); xi < (xt <= src_width ? xt : src_width); xi++) {142int px = xi, py = yi;143int sx = px, sy = py;144sx = CLAMP(sx, 0, src_width - 1);145sy = CLAMP(sy, 0, src_height - 1);146Color color = p_src_image->get_pixel(sx, sy);147if (p_transposed) {148SWAP(px, py);149}150px += p_offset.x;151py += p_offset.y;152153//may have been cropped, so don't blit what is not visible?154if (px < 0 || px >= width) {155continue;156}157if (py < 0 || py >= height) {158continue;159}160p_image->set_pixel(px, py, color);161}162163for (int xi = (xf < src_width ? int(xf) : src_width - 1); xi >= (xt > 0 ? xt : 0); xi--) {164int px = xi, py = yi;165int sx = px, sy = py;166sx = CLAMP(sx, 0, src_width - 1);167sy = CLAMP(sy, 0, src_height - 1);168Color color = p_src_image->get_pixel(sx, sy);169if (p_transposed) {170SWAP(px, py);171}172px += p_offset.x;173py += p_offset.y;174175//may have been cropped, so don't blit what is not visible?176if (px < 0 || px >= width) {177continue;178}179if (py < 0 || py >= height) {180continue;181}182p_image->set_pixel(px, py, color);183}184}185xf += dx_far;186if (yi < y[1]) {187xt += dx_upper;188} else {189xt += dx_low;190}191}192}193194Error 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) {195ERR_FAIL_COND_V(p_source_file_options.is_empty(), ERR_BUG); //should never happen196197Vector<EditorAtlasPacker::Chart> charts;198Vector<PackData> pack_data_files;199200pack_data_files.resize(p_source_file_options.size());201202int idx = 0;203for (const KeyValue<String, HashMap<StringName, Variant>> &E : p_source_file_options) {204PackData &pack_data = pack_data_files.write[idx];205const String &source = E.key;206const HashMap<StringName, Variant> &options = E.value;207208Ref<Image> image;209image.instantiate();210Error err = ImageLoader::load_image(source, image);211ERR_CONTINUE(err != OK);212213pack_data.image = image;214215int mode = options["import_mode"];216217if (mode == IMPORT_MODE_REGION) {218pack_data.is_mesh = false;219pack_data.is_cropped = options["crop_to_region"];220221EditorAtlasPacker::Chart chart;222223Rect2i used_rect = Rect2i(Vector2i(), image->get_size());224if (options["trim_alpha_border_from_region"]) {225// Clip a region from the image.226used_rect = image->get_used_rect();227}228pack_data.region = used_rect;229230chart.vertices.push_back(used_rect.position);231chart.vertices.push_back(used_rect.position + Vector2i(used_rect.size.x, 0));232chart.vertices.push_back(used_rect.position + Vector2i(used_rect.size.x, used_rect.size.y));233chart.vertices.push_back(used_rect.position + Vector2i(0, used_rect.size.y));234EditorAtlasPacker::Chart::Face f;235f.vertex[0] = 0;236f.vertex[1] = 1;237f.vertex[2] = 2;238chart.faces.push_back(f);239f.vertex[0] = 0;240f.vertex[1] = 2;241f.vertex[2] = 3;242chart.faces.push_back(f);243chart.can_transpose = false;244pack_data.chart_vertices.push_back(chart.vertices);245pack_data.chart_pieces.push_back(charts.size());246charts.push_back(chart);247248} else {249pack_data.is_mesh = true;250251Ref<BitMap> bit_map;252bit_map.instantiate();253bit_map->create_from_image_alpha(image);254Vector<Vector<Vector2>> polygons = bit_map->clip_opaque_to_polygons(Rect2(Vector2(), image->get_size()));255256for (int j = 0; j < polygons.size(); j++) {257EditorAtlasPacker::Chart chart;258chart.vertices = polygons[j];259chart.can_transpose = true;260261Vector<int> poly = Geometry2D::triangulate_polygon(polygons[j]);262for (int i = 0; i < poly.size(); i += 3) {263EditorAtlasPacker::Chart::Face f;264f.vertex[0] = poly[i + 0];265f.vertex[1] = poly[i + 1];266f.vertex[2] = poly[i + 2];267chart.faces.push_back(f);268}269270pack_data.chart_pieces.push_back(charts.size());271charts.push_back(chart);272273pack_data.chart_vertices.push_back(polygons[j]);274}275}276idx++;277}278279const int max_width = (int)GLOBAL_GET("editor/import/atlas_max_width");280281//pack the charts282int atlas_width, atlas_height;283EditorAtlasPacker::chart_pack(charts, atlas_width, atlas_height, max_width);284285if (atlas_height > max_width * 2) {286WARN_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));287}288289//blit the atlas290Ref<Image> new_atlas = Image::create_empty(atlas_width, atlas_height, false, Image::FORMAT_RGBA8);291292for (int i = 0; i < pack_data_files.size(); i++) {293PackData &pack_data = pack_data_files.write[i];294295for (int j = 0; j < pack_data.chart_pieces.size(); j++) {296const EditorAtlasPacker::Chart &chart = charts[pack_data.chart_pieces[j]];297for (int k = 0; k < chart.faces.size(); k++) {298Vector2i positions[3];299for (int l = 0; l < 3; l++) {300int vertex_idx = chart.faces[k].vertex[l];301positions[l] = Vector2i(chart.vertices[vertex_idx]);302}303304_plot_triangle(positions, Vector2i(chart.final_offset), chart.transposed, new_atlas, pack_data.image);305}306}307}308309//save the atlas310311new_atlas->save_png(p_group_file);312313//update cache if existing, else create314Ref<Texture2D> cache;315cache = ResourceCache::get_ref(p_group_file);316if (cache.is_null()) {317Ref<ImageTexture> res_cache = ImageTexture::create_from_image(new_atlas);318res_cache->set_path(p_group_file);319cache = res_cache;320}321322//save the images323idx = 0;324for (const KeyValue<String, HashMap<StringName, Variant>> &E : p_source_file_options) {325PackData &pack_data = pack_data_files.write[idx];326327Ref<Texture2D> texture;328329if (!pack_data.is_mesh) {330Vector2 offset = charts[pack_data.chart_pieces[0]].vertices[0] + charts[pack_data.chart_pieces[0]].final_offset;331332//region333Ref<AtlasTexture> atlas_texture;334atlas_texture.instantiate();335atlas_texture->set_atlas(cache);336atlas_texture->set_region(Rect2(offset, pack_data.region.size));337338if (!pack_data.is_cropped) {339atlas_texture->set_margin(Rect2(pack_data.region.position, pack_data.image->get_size() - pack_data.region.size));340}341342texture = atlas_texture;343} else {344Ref<ArrayMesh> mesh;345mesh.instantiate();346347for (int i = 0; i < pack_data.chart_pieces.size(); i++) {348const EditorAtlasPacker::Chart &chart = charts[pack_data.chart_pieces[i]];349Vector<Vector2> vertices;350Vector<int> indices;351Vector<Vector2> uvs;352int vc = chart.vertices.size();353int fc = chart.faces.size();354vertices.resize(vc);355uvs.resize(vc);356indices.resize(fc * 3);357358{359Vector2 *vw = vertices.ptrw();360int *iw = indices.ptrw();361Vector2 *uvw = uvs.ptrw();362363for (int j = 0; j < vc; j++) {364vw[j] = chart.vertices[j];365Vector2 uv = chart.vertices[j];366if (chart.transposed) {367SWAP(uv.x, uv.y);368}369uv += chart.final_offset;370uv /= new_atlas->get_size(); //normalize uv to 0-1 range371uvw[j] = uv;372}373374for (int j = 0; j < fc; j++) {375iw[j * 3 + 0] = chart.faces[j].vertex[0];376iw[j * 3 + 1] = chart.faces[j].vertex[1];377iw[j * 3 + 2] = chart.faces[j].vertex[2];378}379}380381Array arrays;382arrays.resize(Mesh::ARRAY_MAX);383arrays[Mesh::ARRAY_VERTEX] = vertices;384arrays[Mesh::ARRAY_TEX_UV] = uvs;385arrays[Mesh::ARRAY_INDEX] = indices;386387mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arrays);388}389390Ref<MeshTexture> mesh_texture;391mesh_texture.instantiate();392mesh_texture->set_base_texture(cache);393mesh_texture->set_image_size(pack_data.image->get_size());394mesh_texture->set_mesh(mesh);395396texture = mesh_texture;397}398399String save_path = p_base_paths[E.key] + ".res";400ResourceSaver::save(texture, save_path);401idx++;402}403404return OK;405}406407408