Path: blob/master/scene/resources/3d/importer_mesh.cpp
21151 views
/**************************************************************************/1/* importer_mesh.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 "importer_mesh.h"3132#include "core/io/marshalls.h"33#include "core/math/random_pcg.h"34#include "scene/resources/surface_tool.h"3536#ifndef PHYSICS_3D_DISABLED37#include "core/math/convex_hull.h"38#endif // PHYSICS_3D_DISABLED3940String ImporterMesh::validate_blend_shape_name(const String &p_name) {41return p_name.replace_char(':', '_');42}4344void ImporterMesh::add_blend_shape(const String &p_name) {45ERR_FAIL_COND(surfaces.size() > 0);46blend_shapes.push_back(validate_blend_shape_name(p_name));47}4849int ImporterMesh::get_blend_shape_count() const {50return blend_shapes.size();51}5253String ImporterMesh::get_blend_shape_name(int p_blend_shape) const {54ERR_FAIL_INDEX_V(p_blend_shape, blend_shapes.size(), String());55return blend_shapes[p_blend_shape];56}5758void ImporterMesh::set_blend_shape_mode(Mesh::BlendShapeMode p_blend_shape_mode) {59blend_shape_mode = p_blend_shape_mode;60}6162Mesh::BlendShapeMode ImporterMesh::get_blend_shape_mode() const {63return blend_shape_mode;64}6566void ImporterMesh::add_surface(Mesh::PrimitiveType p_primitive, const Array &p_arrays, const TypedArray<Array> &p_blend_shapes, const Dictionary &p_lods, const Ref<Material> &p_material, const String &p_surface_name, const uint64_t p_flags) {67ERR_FAIL_COND(p_blend_shapes.size() != blend_shapes.size());68ERR_FAIL_COND(p_arrays.size() != Mesh::ARRAY_MAX);69Surface s;70s.primitive = p_primitive;71s.arrays = p_arrays;72s.name = p_surface_name;73s.flags = p_flags;7475Vector<Vector3> vertex_array = p_arrays[Mesh::ARRAY_VERTEX];76int vertex_count = vertex_array.size();77ERR_FAIL_COND(vertex_count == 0);7879for (int i = 0; i < blend_shapes.size(); i++) {80Array bsdata = p_blend_shapes[i];81ERR_FAIL_COND(bsdata.size() != Mesh::ARRAY_MAX);82Vector<Vector3> vertex_data = bsdata[Mesh::ARRAY_VERTEX];83ERR_FAIL_COND(vertex_data.size() != vertex_count);84Surface::BlendShape bs;85bs.arrays = bsdata;86s.blend_shape_data.push_back(bs);87}8889for (const KeyValue<Variant, Variant> &kv : p_lods) {90ERR_CONTINUE(!kv.key.is_num());91Surface::LOD lod;92lod.distance = kv.key;93lod.indices = kv.value;94ERR_CONTINUE(lod.indices.is_empty());95s.lods.push_back(lod);96}9798s.material = p_material;99100surfaces.push_back(s);101mesh.unref();102}103104int ImporterMesh::get_surface_count() const {105return surfaces.size();106}107108Mesh::PrimitiveType ImporterMesh::get_surface_primitive_type(int p_surface) {109ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Mesh::PRIMITIVE_MAX);110return surfaces[p_surface].primitive;111}112Array ImporterMesh::get_surface_arrays(int p_surface) const {113ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Array());114return surfaces[p_surface].arrays;115}116String ImporterMesh::get_surface_name(int p_surface) const {117ERR_FAIL_INDEX_V(p_surface, surfaces.size(), String());118return surfaces[p_surface].name;119}120void ImporterMesh::set_surface_name(int p_surface, const String &p_name) {121ERR_FAIL_INDEX(p_surface, surfaces.size());122surfaces.write[p_surface].name = p_name;123mesh.unref();124}125126Array ImporterMesh::get_surface_blend_shape_arrays(int p_surface, int p_blend_shape) const {127ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Array());128ERR_FAIL_INDEX_V(p_blend_shape, surfaces[p_surface].blend_shape_data.size(), Array());129return surfaces[p_surface].blend_shape_data[p_blend_shape].arrays;130}131int ImporterMesh::get_surface_lod_count(int p_surface) const {132ERR_FAIL_INDEX_V(p_surface, surfaces.size(), 0);133return surfaces[p_surface].lods.size();134}135Vector<int> ImporterMesh::get_surface_lod_indices(int p_surface, int p_lod) const {136ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Vector<int>());137ERR_FAIL_INDEX_V(p_lod, surfaces[p_surface].lods.size(), Vector<int>());138139return surfaces[p_surface].lods[p_lod].indices;140}141142float ImporterMesh::get_surface_lod_size(int p_surface, int p_lod) const {143ERR_FAIL_INDEX_V(p_surface, surfaces.size(), 0);144ERR_FAIL_INDEX_V(p_lod, surfaces[p_surface].lods.size(), 0);145return surfaces[p_surface].lods[p_lod].distance;146}147148uint64_t ImporterMesh::get_surface_format(int p_surface) const {149ERR_FAIL_INDEX_V(p_surface, surfaces.size(), 0);150return surfaces[p_surface].flags;151}152153Ref<Material> ImporterMesh::get_surface_material(int p_surface) const {154ERR_FAIL_INDEX_V(p_surface, surfaces.size(), Ref<Material>());155return surfaces[p_surface].material;156}157158void ImporterMesh::set_surface_material(int p_surface, const Ref<Material> &p_material) {159ERR_FAIL_INDEX(p_surface, surfaces.size());160surfaces.write[p_surface].material = p_material;161mesh.unref();162}163164template <typename T>165static Vector<T> _remap_array(Vector<T> p_array, const Vector<uint32_t> &p_remap, uint32_t p_vertex_count) {166ERR_FAIL_COND_V(p_array.size() % p_remap.size() != 0, p_array);167int num_elements = p_array.size() / p_remap.size();168T *data = p_array.ptrw();169SurfaceTool::remap_vertex_func(data, data, p_remap.size(), sizeof(T) * num_elements, p_remap.ptr());170p_array.resize(p_vertex_count * num_elements);171return p_array;172}173174static void _remap_arrays(Array &r_arrays, const Vector<uint32_t> &p_remap, uint32_t p_vertex_count) {175for (int i = 0; i < r_arrays.size(); i++) {176if (i == RS::ARRAY_INDEX) {177continue;178}179180switch (r_arrays[i].get_type()) {181case Variant::NIL:182break;183case Variant::PACKED_VECTOR3_ARRAY:184r_arrays[i] = _remap_array<Vector3>(r_arrays[i], p_remap, p_vertex_count);185break;186case Variant::PACKED_VECTOR2_ARRAY:187r_arrays[i] = _remap_array<Vector2>(r_arrays[i], p_remap, p_vertex_count);188break;189case Variant::PACKED_FLOAT32_ARRAY:190r_arrays[i] = _remap_array<float>(r_arrays[i], p_remap, p_vertex_count);191break;192case Variant::PACKED_INT32_ARRAY:193r_arrays[i] = _remap_array<int32_t>(r_arrays[i], p_remap, p_vertex_count);194break;195case Variant::PACKED_BYTE_ARRAY:196r_arrays[i] = _remap_array<uint8_t>(r_arrays[i], p_remap, p_vertex_count);197break;198case Variant::PACKED_COLOR_ARRAY:199r_arrays[i] = _remap_array<Color>(r_arrays[i], p_remap, p_vertex_count);200break;201default:202ERR_FAIL_MSG("Unhandled array type.");203}204}205}206207void ImporterMesh::optimize_indices() {208if (!SurfaceTool::optimize_vertex_cache_func) {209return;210}211if (!SurfaceTool::optimize_vertex_fetch_remap_func || !SurfaceTool::remap_vertex_func || !SurfaceTool::remap_index_func) {212return;213}214215for (int i = 0; i < surfaces.size(); i++) {216if (surfaces[i].primitive != Mesh::PRIMITIVE_TRIANGLES) {217continue;218}219220Vector<Vector3> vertices = surfaces[i].arrays[RS::ARRAY_VERTEX];221PackedInt32Array indices = surfaces[i].arrays[RS::ARRAY_INDEX];222223unsigned int index_count = indices.size();224unsigned int vertex_count = vertices.size();225226if (index_count == 0) {227continue;228}229230// Optimize indices for vertex cache to establish final triangle order.231int *indices_ptr = indices.ptrw();232SurfaceTool::optimize_vertex_cache_func((unsigned int *)indices_ptr, (const unsigned int *)indices_ptr, index_count, vertex_count);233surfaces.write[i].arrays[RS::ARRAY_INDEX] = indices;234235for (int j = 0; j < surfaces[i].lods.size(); ++j) {236Surface::LOD &lod = surfaces.write[i].lods.write[j];237int *lod_indices_ptr = lod.indices.ptrw();238SurfaceTool::optimize_vertex_cache_func((unsigned int *)lod_indices_ptr, (const unsigned int *)lod_indices_ptr, lod.indices.size(), vertex_count);239}240241// Concatenate indices for all LODs in the order of coarse->fine; this establishes the effective order of vertices,242// and is important to optimize for vertex fetch (all GPUs) and shading (Mali GPUs)243PackedInt32Array merged_indices;244for (int j = surfaces[i].lods.size() - 1; j >= 0; --j) {245merged_indices.append_array(surfaces[i].lods[j].indices);246}247merged_indices.append_array(indices);248249// Generate remap array that establishes optimal vertex order according to the order of indices above.250Vector<uint32_t> remap;251remap.resize(vertex_count);252unsigned int new_vertex_count = SurfaceTool::optimize_vertex_fetch_remap_func(remap.ptrw(), (const unsigned int *)merged_indices.ptr(), merged_indices.size(), vertex_count);253254// We need to remap all vertex and index arrays in lockstep according to the remap.255SurfaceTool::remap_index_func((unsigned int *)indices_ptr, (const unsigned int *)indices_ptr, index_count, remap.ptr());256surfaces.write[i].arrays[RS::ARRAY_INDEX] = indices;257258for (int j = 0; j < surfaces[i].lods.size(); ++j) {259Surface::LOD &lod = surfaces.write[i].lods.write[j];260int *lod_indices_ptr = lod.indices.ptrw();261SurfaceTool::remap_index_func((unsigned int *)lod_indices_ptr, (const unsigned int *)lod_indices_ptr, lod.indices.size(), remap.ptr());262}263264_remap_arrays(surfaces.write[i].arrays, remap, new_vertex_count);265for (int j = 0; j < surfaces[i].blend_shape_data.size(); j++) {266_remap_arrays(surfaces.write[i].blend_shape_data.write[j].arrays, remap, new_vertex_count);267}268}269270if (shadow_mesh.is_valid()) {271shadow_mesh->optimize_indices();272}273}274275#define VERTEX_SKIN_FUNC(bone_count, vert_idx, read_array, write_array, transform_array, bone_array, weight_array) \276Vector3 transformed_vert; \277for (unsigned int weight_idx = 0; weight_idx < bone_count; weight_idx++) { \278int bone_idx = bone_array[vert_idx * bone_count + weight_idx]; \279float w = weight_array[vert_idx * bone_count + weight_idx]; \280if (w < FLT_EPSILON) { \281continue; \282} \283ERR_FAIL_INDEX(bone_idx, static_cast<int>(transform_array.size())); \284transformed_vert += transform_array[bone_idx].xform(read_array[vert_idx]) * w; \285} \286write_array[vert_idx] = transformed_vert;287288void ImporterMesh::generate_lods(float p_normal_merge_angle, Array p_bone_transform_array) {289if (!SurfaceTool::simplify_scale_func) {290return;291}292if (!SurfaceTool::simplify_with_attrib_func) {293return;294}295296LocalVector<Transform3D> bone_transform_vector;297for (int i = 0; i < p_bone_transform_array.size(); i++) {298ERR_FAIL_COND(p_bone_transform_array[i].get_type() != Variant::TRANSFORM3D);299bone_transform_vector.push_back(p_bone_transform_array[i]);300}301302for (int i = 0; i < surfaces.size(); i++) {303if (surfaces[i].primitive != Mesh::PRIMITIVE_TRIANGLES) {304continue;305}306307surfaces.write[i].lods.clear();308Vector<Vector3> vertices = surfaces[i].arrays[RS::ARRAY_VERTEX];309PackedInt32Array indices = surfaces[i].arrays[RS::ARRAY_INDEX];310Vector<Vector3> normals = surfaces[i].arrays[RS::ARRAY_NORMAL];311Vector<float> tangents = surfaces[i].arrays[RS::ARRAY_TANGENT];312Vector<Vector2> uvs = surfaces[i].arrays[RS::ARRAY_TEX_UV];313Vector<Vector2> uv2s = surfaces[i].arrays[RS::ARRAY_TEX_UV2];314Vector<int> bones = surfaces[i].arrays[RS::ARRAY_BONES];315Vector<float> weights = surfaces[i].arrays[RS::ARRAY_WEIGHTS];316Vector<Color> colors = surfaces[i].arrays[RS::ARRAY_COLOR];317318unsigned int index_count = indices.size();319unsigned int vertex_count = vertices.size();320321if (index_count == 0) {322continue; //no lods if no indices323}324ERR_FAIL_COND_MSG(index_count % 3 != 0, "ImporterMesh::generate_lods: Indexed triangle meshes MUST have an index array with a size that is a multiple of 3, but got " + itos(index_count) + " indices. Cannot generate LODs for this invalid mesh.");325326const Vector3 *vertices_ptr = vertices.ptr();327const int *indices_ptr = indices.ptr();328329if (normals.is_empty()) {330normals.resize(index_count);331Vector3 *n_ptr = normals.ptrw();332for (unsigned int j = 0; j < index_count; j += 3) {333const Vector3 &v0 = vertices_ptr[indices_ptr[j + 0]];334const Vector3 &v1 = vertices_ptr[indices_ptr[j + 1]];335const Vector3 &v2 = vertices_ptr[indices_ptr[j + 2]];336Vector3 n = vec3_cross(v0 - v2, v0 - v1).normalized();337n_ptr[j + 0] = n;338n_ptr[j + 1] = n;339n_ptr[j + 2] = n;340}341}342343bool deformable = bones.size() > 0 || blend_shapes.size() > 0;344345if (bones.size() > 0 && weights.size() && bone_transform_vector.size() > 0) {346Vector3 *vertices_ptrw = vertices.ptrw();347348// Apply bone transforms to regular surface.349unsigned int bone_weight_length = surfaces[i].flags & Mesh::ARRAY_FLAG_USE_8_BONE_WEIGHTS ? 8 : 4;350351const int *bo = bones.ptr();352const float *we = weights.ptr();353354for (unsigned int j = 0; j < vertex_count; j++) {355VERTEX_SKIN_FUNC(bone_weight_length, j, vertices_ptr, vertices_ptrw, bone_transform_vector, bo, we)356}357358vertices_ptr = vertices.ptr();359}360361float normal_merge_threshold = Math::cos(Math::deg_to_rad(p_normal_merge_angle));362const Vector3 *normals_ptr = normals.ptr();363364HashMap<Vector3, LocalVector<Pair<int, int>>> unique_vertices;365366LocalVector<int> vertex_remap;367LocalVector<int> vertex_inverse_remap;368LocalVector<Vector3> merged_vertices;369LocalVector<Vector3> merged_normals;370LocalVector<int> merged_normals_counts;371const Vector2 *uvs_ptr = uvs.ptr();372const Vector2 *uv2s_ptr = uv2s.ptr();373const float *tangents_ptr = tangents.ptr();374const Color *colors_ptr = colors.ptr();375376for (unsigned int j = 0; j < vertex_count; j++) {377const Vector3 &v = vertices_ptr[j];378const Vector3 &n = normals_ptr[j];379380HashMap<Vector3, LocalVector<Pair<int, int>>>::Iterator E = unique_vertices.find(v);381382if (E) {383const LocalVector<Pair<int, int>> &close_verts = E->value;384385bool found = false;386for (const Pair<int, int> &idx : close_verts) {387bool is_uvs_close = (!uvs_ptr || uvs_ptr[j].distance_squared_to(uvs_ptr[idx.second]) < CMP_EPSILON2);388bool is_uv2s_close = (!uv2s_ptr || uv2s_ptr[j].distance_squared_to(uv2s_ptr[idx.second]) < CMP_EPSILON2);389bool is_tang_aligned = !tangents_ptr || (tangents_ptr[j * 4 + 3] < 0) == (tangents_ptr[idx.second * 4 + 3] < 0);390ERR_FAIL_INDEX(idx.second, normals.size());391bool is_normals_close = normals[idx.second].dot(n) > normal_merge_threshold;392bool is_col_close = (!colors_ptr || colors_ptr[j].is_equal_approx(colors_ptr[idx.second]));393if (is_uvs_close && is_uv2s_close && is_normals_close && is_tang_aligned && is_col_close) {394vertex_remap.push_back(idx.first);395merged_normals[idx.first] += normals[idx.second];396merged_normals_counts[idx.first]++;397found = true;398break;399}400}401402if (!found) {403int vcount = merged_vertices.size();404unique_vertices[v].push_back(Pair<int, int>(vcount, j));405vertex_inverse_remap.push_back(j);406merged_vertices.push_back(v);407vertex_remap.push_back(vcount);408merged_normals.push_back(normals_ptr[j]);409merged_normals_counts.push_back(1);410}411} else {412int vcount = merged_vertices.size();413unique_vertices[v] = LocalVector<Pair<int, int>>();414unique_vertices[v].push_back(Pair<int, int>(vcount, j));415vertex_inverse_remap.push_back(j);416merged_vertices.push_back(v);417vertex_remap.push_back(vcount);418merged_normals.push_back(normals_ptr[j]);419merged_normals_counts.push_back(1);420}421}422423LocalVector<int> merged_indices;424merged_indices.resize(index_count);425for (unsigned int j = 0; j < index_count; j++) {426merged_indices[j] = vertex_remap[indices[j]];427}428429unsigned int merged_vertex_count = merged_vertices.size();430const Vector3 *merged_vertices_ptr = merged_vertices.ptr();431Vector3 *merged_normals_ptr = merged_normals.ptr();432433{434const int *counts_ptr = merged_normals_counts.ptr();435for (unsigned int j = 0; j < merged_vertex_count; j++) {436merged_normals_ptr[j] /= counts_ptr[j];437}438}439440Vector<float> merged_vertices_f32 = vector3_to_float32_array(merged_vertices_ptr, merged_vertex_count);441float scale = SurfaceTool::simplify_scale_func(merged_vertices_f32.ptr(), merged_vertex_count, sizeof(float) * 3);442443const size_t attrib_count = 6; // 3 for normal + 3 for color (if present)444445float attrib_weights[attrib_count] = {};446447// Give some weight to normal preservation448attrib_weights[0] = attrib_weights[1] = attrib_weights[2] = 1.0f;449450// Give some weight to colors but only if present to avoid redundant computations during simplification451if (colors_ptr) {452attrib_weights[3] = attrib_weights[4] = attrib_weights[5] = 1.0f;453}454455LocalVector<float> merged_attribs;456merged_attribs.resize(merged_vertex_count * attrib_count);457float *merged_attribs_ptr = merged_attribs.ptr();458459memset(merged_attribs_ptr, 0, merged_attribs.size() * sizeof(float));460461for (unsigned int j = 0; j < merged_vertex_count; ++j) {462merged_attribs_ptr[j * attrib_count + 0] = merged_normals_ptr[j].x;463merged_attribs_ptr[j * attrib_count + 1] = merged_normals_ptr[j].y;464merged_attribs_ptr[j * attrib_count + 2] = merged_normals_ptr[j].z;465466if (colors_ptr) {467unsigned int rj = vertex_inverse_remap[j];468469merged_attribs_ptr[j * attrib_count + 3] = colors_ptr[rj].r;470merged_attribs_ptr[j * attrib_count + 4] = colors_ptr[rj].g;471merged_attribs_ptr[j * attrib_count + 5] = colors_ptr[rj].b;472}473}474475print_verbose("LOD Generation: Triangles " + itos(index_count / 3) + ", vertices " + itos(vertex_count) + " (merged " + itos(merged_vertex_count) + ")" + (deformable ? ", deformable" : ""));476477const float max_mesh_error = 1.0f; // We only need LODs that can be selected by error threshold.478const unsigned min_target_indices = 12;479480LocalVector<int> current_indices(merged_indices);481float current_error = 0.0f;482bool allow_prune = true;483484while (current_indices.size() > min_target_indices * 2) {485unsigned int current_index_count = current_indices.size();486unsigned int target_index_count = MAX(((current_index_count / 3) / 2) * 3, min_target_indices);487488PackedInt32Array new_indices;489new_indices.resize(current_index_count);490491int simplify_options = SurfaceTool::SIMPLIFY_SPARSE; // Does not change appearance, but speeds up subsequent iterations.492493// Lock geometric boundary in case the mesh is composed of multiple material subsets.494simplify_options |= SurfaceTool::SIMPLIFY_LOCK_BORDER;495496if (allow_prune) {497// Remove small disconnected components.498simplify_options |= SurfaceTool::SIMPLIFY_PRUNE;499}500501if (deformable) {502// Improves appearance of deformable objects after deformation by using more regular tessellation.503simplify_options |= SurfaceTool::SIMPLIFY_REGULARIZE;504}505506float step_error = 0.0f;507size_t new_index_count = SurfaceTool::simplify_with_attrib_func(508(unsigned int *)new_indices.ptrw(),509(const uint32_t *)current_indices.ptr(), current_index_count,510merged_vertices_f32.ptr(), merged_vertex_count,511sizeof(float) * 3, // Vertex stride512merged_attribs_ptr,513sizeof(float) * attrib_count, // Attribute stride514attrib_weights, attrib_count,515nullptr, // Vertex lock516target_index_count,517max_mesh_error,518simplify_options,519&step_error);520521if (new_index_count == 0 && allow_prune) {522// If the best result the simplifier could arrive at with pruning enabled is 0 triangles, there might still be an opportunity523// to reduce the number of triangles further *without* completely decimating the mesh. It will be impossible to reach the target524// this way - if the target was reachable without going down to 0, the simplifier would have done it! - but we might still be able525// to get one more slightly lower level if we retry without pruning.526allow_prune = false;527continue;528}529530// Accumulate error over iterations. Usually, it's correct to use step_error as is; however, on coarse LODs, we may start531// getting *smaller* relative error compared to the previous LOD. To make sure the error is monotonic and strictly increasing,532// and to limit the switching (pop) distance, we ensure the error grows by an arbitrary factor each iteration.533current_error = MAX(current_error * 1.5f, step_error);534535new_indices.resize(new_index_count);536current_indices = new_indices;537538if (new_index_count == 0 || (new_index_count >= current_index_count * 0.75f)) {539print_verbose(" LOD stop: got " + itos(new_index_count / 3) + " triangles when asking for " + itos(target_index_count / 3));540break;541}542543if (current_error > max_mesh_error) {544print_verbose(" LOD stop: reached " + rtos(current_error) + " cumulative error (step error " + rtos(step_error) + ")");545break;546}547548// We need to remap the LOD indices back to the original vertex array; note that we already copied new_indices into current_indices for subsequent iteration.549{550int *ptrw = new_indices.ptrw();551for (unsigned int j = 0; j < new_index_count; j++) {552ptrw[j] = vertex_inverse_remap[ptrw[j]];553}554}555556Surface::LOD lod;557lod.distance = MAX(current_error * scale, CMP_EPSILON2);558lod.indices = new_indices;559surfaces.write[i].lods.push_back(lod);560561print_verbose(" LOD " + itos(surfaces.write[i].lods.size()) + ": " + itos(new_index_count / 3) + " triangles, error " + rtos(current_error) + " (step error " + rtos(step_error) + ")");562}563564surfaces.write[i].lods.sort_custom<Surface::LODComparator>();565}566}567568void ImporterMesh::_generate_lods_bind(float p_normal_merge_angle, float p_normal_split_angle, Array p_skin_pose_transform_array) {569// p_normal_split_angle is unused, but kept for compatibility570generate_lods(p_normal_merge_angle, p_skin_pose_transform_array);571}572573bool ImporterMesh::has_mesh() const {574return mesh.is_valid();575}576577Ref<ArrayMesh> ImporterMesh::get_mesh(const Ref<ArrayMesh> &p_base) {578ERR_FAIL_COND_V(surfaces.is_empty(), Ref<ArrayMesh>());579580if (mesh.is_null()) {581if (p_base.is_valid()) {582mesh = p_base;583}584if (mesh.is_null()) {585mesh.instantiate();586}587mesh->set_name(get_name());588if (has_meta("import_id")) {589mesh->set_meta("import_id", get_meta("import_id"));590}591for (int i = 0; i < blend_shapes.size(); i++) {592mesh->add_blend_shape(blend_shapes[i]);593}594mesh->set_blend_shape_mode(blend_shape_mode);595for (int i = 0; i < surfaces.size(); i++) {596Array bs_data;597if (surfaces[i].blend_shape_data.size()) {598for (int j = 0; j < surfaces[i].blend_shape_data.size(); j++) {599bs_data.push_back(surfaces[i].blend_shape_data[j].arrays);600}601}602Dictionary lods;603if (surfaces[i].lods.size()) {604for (int j = 0; j < surfaces[i].lods.size(); j++) {605lods[surfaces[i].lods[j].distance] = surfaces[i].lods[j].indices;606}607}608609mesh->add_surface_from_arrays(surfaces[i].primitive, surfaces[i].arrays, bs_data, lods, surfaces[i].flags);610if (surfaces[i].material.is_valid()) {611mesh->surface_set_material(mesh->get_surface_count() - 1, surfaces[i].material);612}613if (!surfaces[i].name.is_empty()) {614mesh->surface_set_name(mesh->get_surface_count() - 1, surfaces[i].name);615}616}617618mesh->set_lightmap_size_hint(lightmap_size_hint);619620if (shadow_mesh.is_valid()) {621Ref<ArrayMesh> shadow = shadow_mesh->get_mesh();622mesh->set_shadow_mesh(shadow);623}624}625626return mesh;627}628629Ref<ImporterMesh> ImporterMesh::from_mesh(const Ref<Mesh> &p_mesh) {630Ref<ImporterMesh> importer_mesh;631importer_mesh.instantiate();632if (p_mesh.is_null()) {633return importer_mesh;634}635Ref<ArrayMesh> array_mesh = p_mesh;636// Convert blend shape mode and names if any.637if (p_mesh->get_blend_shape_count() > 0) {638ArrayMesh::BlendShapeMode shape_mode = ArrayMesh::BLEND_SHAPE_MODE_NORMALIZED;639if (array_mesh.is_valid()) {640shape_mode = array_mesh->get_blend_shape_mode();641}642importer_mesh->set_blend_shape_mode(shape_mode);643for (int morph_i = 0; morph_i < p_mesh->get_blend_shape_count(); morph_i++) {644importer_mesh->add_blend_shape(p_mesh->get_blend_shape_name(morph_i));645}646}647// Add surfaces one by one.648for (int32_t surface_i = 0; surface_i < p_mesh->get_surface_count(); surface_i++) {649Ref<Material> mat = p_mesh->surface_get_material(surface_i);650String surface_name;651if (array_mesh.is_valid()) {652surface_name = array_mesh->surface_get_name(surface_i);653}654if (surface_name.is_empty() && mat.is_valid()) {655surface_name = mat->get_name();656}657importer_mesh->add_surface(p_mesh->surface_get_primitive_type(surface_i), p_mesh->surface_get_arrays(surface_i),658p_mesh->surface_get_blend_shape_arrays(surface_i), p_mesh->surface_get_lods(surface_i),659mat, surface_name, p_mesh->surface_get_format(surface_i));660}661// Merge metadata.662importer_mesh->merge_meta_from(*p_mesh);663importer_mesh->set_name(p_mesh->get_name());664return importer_mesh;665}666667void ImporterMesh::clear() {668surfaces.clear();669blend_shapes.clear();670mesh.unref();671}672673void ImporterMesh::create_shadow_mesh() {674if (shadow_mesh.is_valid()) {675shadow_mesh.unref();676}677678//no shadow mesh for blendshapes679if (blend_shapes.size() > 0) {680return;681}682//no shadow mesh for skeletons683for (int i = 0; i < surfaces.size(); i++) {684if (surfaces[i].arrays[RS::ARRAY_BONES].get_type() != Variant::NIL) {685return;686}687if (surfaces[i].arrays[RS::ARRAY_WEIGHTS].get_type() != Variant::NIL) {688return;689}690}691692shadow_mesh.instantiate();693694for (int i = 0; i < surfaces.size(); i++) {695LocalVector<int> vertex_remap;696Vector<Vector3> new_vertices;697Vector<Vector3> vertices = surfaces[i].arrays[RS::ARRAY_VERTEX];698int vertex_count = vertices.size();699{700HashMap<Vector3, int> unique_vertices;701const Vector3 *vptr = vertices.ptr();702for (int j = 0; j < vertex_count; j++) {703const Vector3 &v = vptr[j];704705HashMap<Vector3, int>::Iterator E = unique_vertices.find(v);706707if (E) {708vertex_remap.push_back(E->value);709} else {710int vcount = unique_vertices.size();711unique_vertices[v] = vcount;712vertex_remap.push_back(vcount);713new_vertices.push_back(v);714}715}716}717718Array new_surface;719new_surface.resize(RS::ARRAY_MAX);720Dictionary lods;721722// print_line("original vertex count: " + itos(vertices.size()) + " new vertex count: " + itos(new_vertices.size()));723724new_surface[RS::ARRAY_VERTEX] = new_vertices;725726Vector<int> indices = surfaces[i].arrays[RS::ARRAY_INDEX];727if (indices.size()) {728int index_count = indices.size();729const int *index_rptr = indices.ptr();730Vector<int> new_indices;731new_indices.resize(indices.size());732int *index_wptr = new_indices.ptrw();733734for (int j = 0; j < index_count; j++) {735int index = index_rptr[j];736ERR_FAIL_INDEX(index, vertex_count);737index_wptr[j] = vertex_remap[index];738}739740new_surface[RS::ARRAY_INDEX] = new_indices;741742// Make sure the same LODs as the full version are used.743// This makes it more coherent between rendered model and its shadows.744for (int j = 0; j < surfaces[i].lods.size(); j++) {745indices = surfaces[i].lods[j].indices;746747index_count = indices.size();748index_rptr = indices.ptr();749new_indices.resize(indices.size());750index_wptr = new_indices.ptrw();751752for (int k = 0; k < index_count; k++) {753int index = index_rptr[k];754ERR_FAIL_INDEX(index, vertex_count);755index_wptr[k] = vertex_remap[index];756}757758lods[surfaces[i].lods[j].distance] = new_indices;759}760}761762shadow_mesh->add_surface(surfaces[i].primitive, new_surface, Array(), lods, Ref<Material>(), surfaces[i].name, surfaces[i].flags);763}764}765766Ref<ImporterMesh> ImporterMesh::get_shadow_mesh() const {767return shadow_mesh;768}769770void ImporterMesh::_set_data(const Dictionary &p_data) {771clear();772if (p_data.has("blend_shape_names")) {773blend_shapes = p_data["blend_shape_names"];774}775if (p_data.has("surfaces")) {776Array surface_arr = p_data["surfaces"];777for (int i = 0; i < surface_arr.size(); i++) {778Dictionary s = surface_arr[i];779ERR_CONTINUE(!s.has("primitive"));780ERR_CONTINUE(!s.has("arrays"));781Mesh::PrimitiveType prim = Mesh::PrimitiveType(int(s["primitive"]));782ERR_CONTINUE(prim >= Mesh::PRIMITIVE_MAX);783Array arr = s["arrays"];784Dictionary lods;785String surf_name;786if (s.has("name")) {787surf_name = s["name"];788}789if (s.has("lods")) {790lods = s["lods"];791}792Array b_shapes;793if (s.has("b_shapes")) {794b_shapes = s["b_shapes"];795}796Ref<Material> material;797if (s.has("material")) {798material = s["material"];799}800uint64_t flags = 0;801if (s.has("flags")) {802flags = s["flags"];803}804add_surface(prim, arr, b_shapes, lods, material, surf_name, flags);805}806}807}808Dictionary ImporterMesh::_get_data() const {809Dictionary data;810if (blend_shapes.size()) {811data["blend_shape_names"] = blend_shapes;812}813Array surface_arr;814for (int i = 0; i < surfaces.size(); i++) {815Dictionary d;816d["primitive"] = surfaces[i].primitive;817d["arrays"] = surfaces[i].arrays;818if (surfaces[i].blend_shape_data.size()) {819Array bs_data;820for (int j = 0; j < surfaces[i].blend_shape_data.size(); j++) {821bs_data.push_back(surfaces[i].blend_shape_data[j].arrays);822}823d["blend_shapes"] = bs_data;824}825if (surfaces[i].lods.size()) {826Dictionary lods;827for (int j = 0; j < surfaces[i].lods.size(); j++) {828lods[surfaces[i].lods[j].distance] = surfaces[i].lods[j].indices;829}830d["lods"] = lods;831}832833if (surfaces[i].material.is_valid()) {834d["material"] = surfaces[i].material;835}836837if (!surfaces[i].name.is_empty()) {838d["name"] = surfaces[i].name;839}840841d["flags"] = surfaces[i].flags;842843surface_arr.push_back(d);844}845data["surfaces"] = surface_arr;846return data;847}848849Vector<Face3> ImporterMesh::get_faces() const {850Vector<Face3> faces;851for (int i = 0; i < surfaces.size(); i++) {852if (surfaces[i].primitive == Mesh::PRIMITIVE_TRIANGLES) {853Vector<Vector3> vertices = surfaces[i].arrays[Mesh::ARRAY_VERTEX];854Vector<int> indices = surfaces[i].arrays[Mesh::ARRAY_INDEX];855if (indices.size()) {856for (int j = 0; j < indices.size(); j += 3) {857Face3 f;858f.vertex[0] = vertices[indices[j + 0]];859f.vertex[1] = vertices[indices[j + 1]];860f.vertex[2] = vertices[indices[j + 2]];861faces.push_back(f);862}863} else {864for (int j = 0; j < vertices.size(); j += 3) {865Face3 f;866f.vertex[0] = vertices[j + 0];867f.vertex[1] = vertices[j + 1];868f.vertex[2] = vertices[j + 2];869faces.push_back(f);870}871}872}873}874875return faces;876}877878#ifndef PHYSICS_3D_DISABLED879Vector<Ref<Shape3D>> ImporterMesh::convex_decompose(const Ref<MeshConvexDecompositionSettings> &p_settings) const {880ERR_FAIL_NULL_V(Mesh::convex_decomposition_function, Vector<Ref<Shape3D>>());881882const Vector<Face3> faces = get_faces();883int face_count = faces.size();884885Vector<Vector3> vertices;886uint32_t vertex_count = 0;887vertices.resize(face_count * 3);888Vector<uint32_t> indices;889indices.resize(face_count * 3);890{891HashMap<Vector3, uint32_t> vertex_map;892Vector3 *vertex_w = vertices.ptrw();893uint32_t *index_w = indices.ptrw();894for (int i = 0; i < face_count; i++) {895for (int j = 0; j < 3; j++) {896const Vector3 &vertex = faces[i].vertex[j];897HashMap<Vector3, uint32_t>::Iterator found_vertex = vertex_map.find(vertex);898uint32_t index;899if (found_vertex) {900index = found_vertex->value;901} else {902index = vertex_count++;903vertex_map[vertex] = index;904vertex_w[index] = vertex;905}906index_w[i * 3 + j] = index;907}908}909}910vertices.resize(vertex_count);911912Vector<Vector<Vector3>> decomposed = Mesh::convex_decomposition_function((real_t *)vertices.ptr(), vertex_count, indices.ptr(), face_count, p_settings, nullptr);913914Vector<Ref<Shape3D>> ret;915916for (int i = 0; i < decomposed.size(); i++) {917Ref<ConvexPolygonShape3D> shape;918shape.instantiate();919shape->set_points(decomposed[i]);920ret.push_back(shape);921}922923return ret;924}925926Ref<ConvexPolygonShape3D> ImporterMesh::create_convex_shape(bool p_clean, bool p_simplify) const {927if (p_simplify) {928Ref<MeshConvexDecompositionSettings> settings;929settings.instantiate();930settings->set_max_convex_hulls(1);931Vector<Ref<Shape3D>> decomposed = convex_decompose(settings);932if (decomposed.size() == 1) {933return decomposed[0];934} else {935ERR_PRINT("Convex shape simplification failed, falling back to simpler process.");936}937}938939Vector<Vector3> vertices;940for (int i = 0; i < get_surface_count(); i++) {941Array a = get_surface_arrays(i);942ERR_FAIL_COND_V(a.is_empty(), Ref<ConvexPolygonShape3D>());943Vector<Vector3> v = a[Mesh::ARRAY_VERTEX];944vertices.append_array(v);945}946947Ref<ConvexPolygonShape3D> shape = memnew(ConvexPolygonShape3D);948949if (p_clean) {950Geometry3D::MeshData md;951Error err = ConvexHullComputer::convex_hull(vertices, md);952if (err == OK) {953shape->set_points(Vector<Vector3>(md.vertices));954return shape;955} else {956ERR_PRINT("Convex shape cleaning failed, falling back to simpler process.");957}958}959960shape->set_points(vertices);961return shape;962}963964Ref<ConcavePolygonShape3D> ImporterMesh::create_trimesh_shape() const {965Vector<Face3> faces = get_faces();966if (faces.is_empty()) {967return Ref<ConcavePolygonShape3D>();968}969970Vector<Vector3> face_points;971face_points.resize(faces.size() * 3);972973for (int i = 0; i < face_points.size(); i += 3) {974Face3 f = faces.get(i / 3);975face_points.set(i, f.vertex[0]);976face_points.set(i + 1, f.vertex[1]);977face_points.set(i + 2, f.vertex[2]);978}979980Ref<ConcavePolygonShape3D> shape = memnew(ConcavePolygonShape3D);981shape->set_faces(face_points);982return shape;983}984#endif // PHYSICS_3D_DISABLED985986Ref<NavigationMesh> ImporterMesh::create_navigation_mesh() {987Vector<Face3> faces = get_faces();988if (faces.is_empty()) {989return Ref<NavigationMesh>();990}991992HashMap<Vector3, int> unique_vertices;993Vector<Vector<int>> face_polygons;994face_polygons.resize(faces.size());995996for (int i = 0; i < faces.size(); i++) {997Vector<int> face_indices;998face_indices.resize(3);999for (int j = 0; j < 3; j++) {1000Vector3 v = faces[i].vertex[j];1001int idx;1002if (unique_vertices.has(v)) {1003idx = unique_vertices[v];1004} else {1005idx = unique_vertices.size();1006unique_vertices[v] = idx;1007}1008face_indices.write[j] = idx;1009}1010face_polygons.write[i] = face_indices;1011}10121013Vector<Vector3> vertices;1014vertices.resize(unique_vertices.size());1015for (const KeyValue<Vector3, int> &E : unique_vertices) {1016vertices.write[E.value] = E.key;1017}10181019Ref<NavigationMesh> nm;1020nm.instantiate();1021nm->set_data(vertices, face_polygons);10221023return nm;1024}10251026extern bool (*array_mesh_lightmap_unwrap_callback)(float p_texel_size, const float *p_vertices, const float *p_normals, int p_vertex_count, const int *p_indices, int p_index_count, const uint8_t *p_cache_data, bool *r_use_cache, uint8_t **r_mesh_cache, int *r_mesh_cache_size, float **r_uv, int **r_vertex, int *r_vertex_count, int **r_index, int *r_index_count, int *r_size_hint_x, int *r_size_hint_y);10271028struct EditorSceneFormatImporterMeshLightmapSurface {1029Ref<Material> material;1030LocalVector<SurfaceTool::Vertex> vertices;1031Mesh::PrimitiveType primitive = Mesh::PrimitiveType::PRIMITIVE_MAX;1032uint64_t format = 0;1033String name;1034};10351036static const uint32_t custom_shift[RS::ARRAY_CUSTOM_COUNT] = { Mesh::ARRAY_FORMAT_CUSTOM0_SHIFT, Mesh::ARRAY_FORMAT_CUSTOM1_SHIFT, Mesh::ARRAY_FORMAT_CUSTOM2_SHIFT, Mesh::ARRAY_FORMAT_CUSTOM3_SHIFT };10371038Error ImporterMesh::lightmap_unwrap_cached(const Transform3D &p_base_transform, float p_texel_size, const Vector<uint8_t> &p_src_cache, Vector<uint8_t> &r_dst_cache) {1039ERR_FAIL_NULL_V(array_mesh_lightmap_unwrap_callback, ERR_UNCONFIGURED);1040ERR_FAIL_COND_V_MSG(blend_shapes.size() != 0, ERR_UNAVAILABLE, "Can't unwrap mesh with blend shapes.");10411042LocalVector<float> vertices;1043LocalVector<float> normals;1044LocalVector<int> indices;1045LocalVector<float> uv;1046LocalVector<Pair<int, int>> uv_indices;10471048Vector<EditorSceneFormatImporterMeshLightmapSurface> lightmap_surfaces;10491050// Keep only the scale1051Basis basis = p_base_transform.get_basis();1052Vector3 scale = Vector3(basis.get_column(0).length(), basis.get_column(1).length(), basis.get_column(2).length());10531054Transform3D transform;1055transform.scale(scale);10561057Basis normal_basis = transform.basis.inverse().transposed();10581059for (int i = 0; i < get_surface_count(); i++) {1060EditorSceneFormatImporterMeshLightmapSurface s;1061s.primitive = get_surface_primitive_type(i);10621063ERR_FAIL_COND_V_MSG(s.primitive != Mesh::PRIMITIVE_TRIANGLES, ERR_UNAVAILABLE, "Only triangles are supported for lightmap unwrap.");1064Array arrays = get_surface_arrays(i);1065s.material = get_surface_material(i);1066s.name = get_surface_name(i);10671068SurfaceTool::create_vertex_array_from_arrays(arrays, s.vertices, &s.format);10691070PackedVector3Array rvertices = arrays[Mesh::ARRAY_VERTEX];1071int vc = rvertices.size();10721073PackedVector3Array rnormals = arrays[Mesh::ARRAY_NORMAL];10741075if (!rnormals.size()) {1076continue;1077}10781079int vertex_ofs = vertices.size() / 3;10801081vertices.resize((vertex_ofs + vc) * 3);1082normals.resize((vertex_ofs + vc) * 3);1083uv_indices.resize(vertex_ofs + vc);10841085for (int j = 0; j < vc; j++) {1086Vector3 v = transform.xform(rvertices[j]);1087Vector3 n = normal_basis.xform(rnormals[j]).normalized();10881089vertices[(j + vertex_ofs) * 3 + 0] = v.x;1090vertices[(j + vertex_ofs) * 3 + 1] = v.y;1091vertices[(j + vertex_ofs) * 3 + 2] = v.z;1092normals[(j + vertex_ofs) * 3 + 0] = n.x;1093normals[(j + vertex_ofs) * 3 + 1] = n.y;1094normals[(j + vertex_ofs) * 3 + 2] = n.z;1095uv_indices[j + vertex_ofs] = Pair<int, int>(i, j);1096}10971098PackedInt32Array rindices = arrays[Mesh::ARRAY_INDEX];1099int ic = rindices.size();11001101float eps = 1.19209290e-7F; // Taken from xatlas.h1102if (ic == 0) {1103for (int j = 0; j < vc / 3; j++) {1104Vector3 p0 = transform.xform(rvertices[j * 3 + 0]);1105Vector3 p1 = transform.xform(rvertices[j * 3 + 1]);1106Vector3 p2 = transform.xform(rvertices[j * 3 + 2]);11071108if ((p0 - p1).length_squared() < eps || (p1 - p2).length_squared() < eps || (p2 - p0).length_squared() < eps) {1109continue;1110}11111112indices.push_back(vertex_ofs + j * 3 + 0);1113indices.push_back(vertex_ofs + j * 3 + 1);1114indices.push_back(vertex_ofs + j * 3 + 2);1115}11161117} else {1118for (int j = 0; j < ic / 3; j++) {1119ERR_FAIL_INDEX_V(rindices[j * 3 + 0], rvertices.size(), ERR_INVALID_DATA);1120ERR_FAIL_INDEX_V(rindices[j * 3 + 1], rvertices.size(), ERR_INVALID_DATA);1121ERR_FAIL_INDEX_V(rindices[j * 3 + 2], rvertices.size(), ERR_INVALID_DATA);1122Vector3 p0 = transform.xform(rvertices[rindices[j * 3 + 0]]);1123Vector3 p1 = transform.xform(rvertices[rindices[j * 3 + 1]]);1124Vector3 p2 = transform.xform(rvertices[rindices[j * 3 + 2]]);11251126if ((p0 - p1).length_squared() < eps || (p1 - p2).length_squared() < eps || (p2 - p0).length_squared() < eps) {1127continue;1128}11291130indices.push_back(vertex_ofs + rindices[j * 3 + 0]);1131indices.push_back(vertex_ofs + rindices[j * 3 + 1]);1132indices.push_back(vertex_ofs + rindices[j * 3 + 2]);1133}1134}11351136lightmap_surfaces.push_back(s);1137}11381139//unwrap11401141bool use_cache = true; // Used to request cache generation and to know if cache was used1142uint8_t *gen_cache;1143int gen_cache_size;1144float *gen_uvs;1145int *gen_vertices;1146int *gen_indices;1147int gen_vertex_count;1148int gen_index_count;1149int size_x;1150int size_y;11511152bool ok = array_mesh_lightmap_unwrap_callback(p_texel_size, vertices.ptr(), normals.ptr(), vertices.size() / 3, indices.ptr(), indices.size(), p_src_cache.ptr(), &use_cache, &gen_cache, &gen_cache_size, &gen_uvs, &gen_vertices, &gen_vertex_count, &gen_indices, &gen_index_count, &size_x, &size_y);11531154if (!ok) {1155return ERR_CANT_CREATE;1156}11571158//create surfacetools for each surface..1159LocalVector<Ref<SurfaceTool>> surfaces_tools;11601161for (int i = 0; i < lightmap_surfaces.size(); i++) {1162Ref<SurfaceTool> st;1163st.instantiate();1164st->set_skin_weight_count((lightmap_surfaces[i].format & Mesh::ARRAY_FLAG_USE_8_BONE_WEIGHTS) ? SurfaceTool::SKIN_8_WEIGHTS : SurfaceTool::SKIN_4_WEIGHTS);1165st->begin(Mesh::PRIMITIVE_TRIANGLES);1166st->set_material(lightmap_surfaces[i].material);1167st->set_meta("name", lightmap_surfaces[i].name);11681169for (int custom_i = 0; custom_i < RS::ARRAY_CUSTOM_COUNT; custom_i++) {1170st->set_custom_format(custom_i, (SurfaceTool::CustomFormat)((lightmap_surfaces[i].format >> custom_shift[custom_i]) & RS::ARRAY_FORMAT_CUSTOM_MASK));1171}1172surfaces_tools.push_back(st); //stay there1173}11741175//remove surfaces1176clear();11771178print_verbose("Mesh: Gen indices: " + itos(gen_index_count));11791180//go through all indices1181for (int i = 0; i < gen_index_count; i += 3) {1182ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 0]], (int)uv_indices.size(), ERR_BUG);1183ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 1]], (int)uv_indices.size(), ERR_BUG);1184ERR_FAIL_INDEX_V(gen_vertices[gen_indices[i + 2]], (int)uv_indices.size(), ERR_BUG);11851186ERR_FAIL_COND_V(uv_indices[gen_vertices[gen_indices[i + 0]]].first != uv_indices[gen_vertices[gen_indices[i + 1]]].first || uv_indices[gen_vertices[gen_indices[i + 0]]].first != uv_indices[gen_vertices[gen_indices[i + 2]]].first, ERR_BUG);11871188int surface = uv_indices[gen_vertices[gen_indices[i + 0]]].first;11891190for (int j = 0; j < 3; j++) {1191SurfaceTool::Vertex v = lightmap_surfaces[surface].vertices[uv_indices[gen_vertices[gen_indices[i + j]]].second];11921193if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_COLOR) {1194surfaces_tools[surface]->set_color(v.color);1195}1196if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_TEX_UV) {1197surfaces_tools[surface]->set_uv(v.uv);1198}1199if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_NORMAL) {1200surfaces_tools[surface]->set_normal(v.normal);1201}1202if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_TANGENT) {1203Plane t;1204t.normal = v.tangent;1205t.d = v.binormal.dot(v.normal.cross(v.tangent)) < 0 ? -1 : 1;1206surfaces_tools[surface]->set_tangent(t);1207}1208if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_BONES) {1209surfaces_tools[surface]->set_bones(v.bones);1210}1211if (lightmap_surfaces[surface].format & Mesh::ARRAY_FORMAT_WEIGHTS) {1212surfaces_tools[surface]->set_weights(v.weights);1213}1214for (int custom_i = 0; custom_i < RS::ARRAY_CUSTOM_COUNT; custom_i++) {1215if ((lightmap_surfaces[surface].format >> custom_shift[custom_i]) & RS::ARRAY_FORMAT_CUSTOM_MASK) {1216surfaces_tools[surface]->set_custom(custom_i, v.custom[custom_i]);1217}1218}12191220Vector2 uv2(gen_uvs[gen_indices[i + j] * 2 + 0], gen_uvs[gen_indices[i + j] * 2 + 1]);1221surfaces_tools[surface]->set_uv2(uv2);12221223surfaces_tools[surface]->add_vertex(v.vertex);1224}1225}12261227//generate surfaces1228for (int i = 0; i < lightmap_surfaces.size(); i++) {1229Ref<SurfaceTool> &tool = surfaces_tools[i];1230tool->index();1231Array arrays = tool->commit_to_arrays();12321233uint64_t format = lightmap_surfaces[i].format;1234if (tool->get_skin_weight_count() == SurfaceTool::SKIN_8_WEIGHTS) {1235format |= RS::ARRAY_FLAG_USE_8_BONE_WEIGHTS;1236} else {1237format &= ~RS::ARRAY_FLAG_USE_8_BONE_WEIGHTS;1238}12391240add_surface(tool->get_primitive_type(), arrays, Array(), Dictionary(), tool->get_material(), tool->get_meta("name"), format);1241}12421243set_lightmap_size_hint(Size2(size_x, size_y));12441245if (gen_cache_size > 0) {1246r_dst_cache.resize(gen_cache_size);1247memcpy(r_dst_cache.ptrw(), gen_cache, gen_cache_size);1248memfree(gen_cache);1249}12501251if (!use_cache) {1252// Cache was not used, free the buffers1253memfree(gen_vertices);1254memfree(gen_indices);1255memfree(gen_uvs);1256}12571258return OK;1259}12601261void ImporterMesh::set_lightmap_size_hint(const Size2i &p_size) {1262lightmap_size_hint = p_size;1263}12641265Size2i ImporterMesh::get_lightmap_size_hint() const {1266return lightmap_size_hint;1267}12681269void ImporterMesh::_bind_methods() {1270ClassDB::bind_method(D_METHOD("add_blend_shape", "name"), &ImporterMesh::add_blend_shape);1271ClassDB::bind_method(D_METHOD("get_blend_shape_count"), &ImporterMesh::get_blend_shape_count);1272ClassDB::bind_method(D_METHOD("get_blend_shape_name", "blend_shape_idx"), &ImporterMesh::get_blend_shape_name);12731274ClassDB::bind_method(D_METHOD("set_blend_shape_mode", "mode"), &ImporterMesh::set_blend_shape_mode);1275ClassDB::bind_method(D_METHOD("get_blend_shape_mode"), &ImporterMesh::get_blend_shape_mode);12761277ClassDB::bind_method(D_METHOD("add_surface", "primitive", "arrays", "blend_shapes", "lods", "material", "name", "flags"), &ImporterMesh::add_surface, DEFVAL(TypedArray<Array>()), DEFVAL(Dictionary()), DEFVAL(Ref<Material>()), DEFVAL(String()), DEFVAL(0));12781279ClassDB::bind_method(D_METHOD("get_surface_count"), &ImporterMesh::get_surface_count);1280ClassDB::bind_method(D_METHOD("get_surface_primitive_type", "surface_idx"), &ImporterMesh::get_surface_primitive_type);1281ClassDB::bind_method(D_METHOD("get_surface_name", "surface_idx"), &ImporterMesh::get_surface_name);1282ClassDB::bind_method(D_METHOD("get_surface_arrays", "surface_idx"), &ImporterMesh::get_surface_arrays);1283ClassDB::bind_method(D_METHOD("get_surface_blend_shape_arrays", "surface_idx", "blend_shape_idx"), &ImporterMesh::get_surface_blend_shape_arrays);1284ClassDB::bind_method(D_METHOD("get_surface_lod_count", "surface_idx"), &ImporterMesh::get_surface_lod_count);1285ClassDB::bind_method(D_METHOD("get_surface_lod_size", "surface_idx", "lod_idx"), &ImporterMesh::get_surface_lod_size);1286ClassDB::bind_method(D_METHOD("get_surface_lod_indices", "surface_idx", "lod_idx"), &ImporterMesh::get_surface_lod_indices);1287ClassDB::bind_method(D_METHOD("get_surface_material", "surface_idx"), &ImporterMesh::get_surface_material);1288ClassDB::bind_method(D_METHOD("get_surface_format", "surface_idx"), &ImporterMesh::get_surface_format);12891290ClassDB::bind_method(D_METHOD("set_surface_name", "surface_idx", "name"), &ImporterMesh::set_surface_name);1291ClassDB::bind_method(D_METHOD("set_surface_material", "surface_idx", "material"), &ImporterMesh::set_surface_material);12921293ClassDB::bind_method(D_METHOD("generate_lods", "normal_merge_angle", "normal_split_angle", "bone_transform_array"), &ImporterMesh::_generate_lods_bind);1294ClassDB::bind_method(D_METHOD("get_mesh", "base_mesh"), &ImporterMesh::get_mesh, DEFVAL(Ref<ArrayMesh>()));1295ClassDB::bind_static_method("ImporterMesh", D_METHOD("from_mesh", "mesh"), &ImporterMesh::from_mesh);1296ClassDB::bind_method(D_METHOD("clear"), &ImporterMesh::clear);12971298ClassDB::bind_method(D_METHOD("_set_data", "data"), &ImporterMesh::_set_data);1299ClassDB::bind_method(D_METHOD("_get_data"), &ImporterMesh::_get_data);13001301ClassDB::bind_method(D_METHOD("set_lightmap_size_hint", "size"), &ImporterMesh::set_lightmap_size_hint);1302ClassDB::bind_method(D_METHOD("get_lightmap_size_hint"), &ImporterMesh::get_lightmap_size_hint);13031304ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_data", "_get_data");1305}130613071308