FBXMeshGeometry.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. /*************************************************************************/
  2. /* FBXMeshGeometry.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. /*
  31. Open Asset Import Library (assimp)
  32. ----------------------------------------------------------------------
  33. Copyright (c) 2006-2019, assimp team
  34. All rights reserved.
  35. Redistribution and use of this software in source and binary forms,
  36. with or without modification, are permitted provided that the
  37. following conditions are met:
  38. * Redistributions of source code must retain the above
  39. copyright notice, this list of conditions and the
  40. following disclaimer.
  41. * Redistributions in binary form must reproduce the above
  42. copyright notice, this list of conditions and the
  43. following disclaimer in the documentation and/or other
  44. materials provided with the distribution.
  45. * Neither the name of the assimp team, nor the names of its
  46. contributors may be used to endorse or promote products
  47. derived from this software without specific prior
  48. written permission of the assimp team.
  49. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  50. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  51. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  52. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  53. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  54. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  55. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  56. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  57. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  58. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  59. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  60. ----------------------------------------------------------------------
  61. */
  62. /** @file FBXMeshGeometry.cpp
  63. * @brief Assimp::FBX::MeshGeometry implementation
  64. */
  65. #include <functional>
  66. #include "FBXDocument.h"
  67. #include "FBXDocumentUtil.h"
  68. #include "FBXImportSettings.h"
  69. #include "FBXMeshGeometry.h"
  70. #include "core/math/vector3.h"
  71. namespace FBXDocParser {
  72. using namespace Util;
  73. // ------------------------------------------------------------------------------------------------
  74. Geometry::Geometry(uint64_t id, const ElementPtr element, const std::string &name, const Document &doc) :
  75. Object(id, element, name), skin() {
  76. const std::vector<const Connection *> &conns = doc.GetConnectionsByDestinationSequenced(ID(), "Deformer");
  77. for (const Connection *con : conns) {
  78. const Skin *sk = ProcessSimpleConnection<Skin>(*con, false, "Skin -> Geometry", element);
  79. if (sk) {
  80. skin = sk;
  81. }
  82. const BlendShape *bsp = ProcessSimpleConnection<BlendShape>(*con, false, "BlendShape -> Geometry",
  83. element);
  84. if (bsp) {
  85. blendShapes.push_back(bsp);
  86. }
  87. }
  88. }
  89. // ------------------------------------------------------------------------------------------------
  90. Geometry::~Geometry() {
  91. // empty
  92. }
  93. // ------------------------------------------------------------------------------------------------
  94. const std::vector<const BlendShape *> &Geometry::get_blend_shapes() const {
  95. return blendShapes;
  96. }
  97. // ------------------------------------------------------------------------------------------------
  98. const Skin *Geometry::DeformerSkin() const {
  99. return skin;
  100. }
  101. // ------------------------------------------------------------------------------------------------
  102. MeshGeometry::MeshGeometry(uint64_t id, const ElementPtr element, const std::string &name, const Document &doc) :
  103. Geometry(id, element, name, doc) {
  104. print_verbose("mesh name: " + String(name.c_str()));
  105. ScopePtr sc = element->Compound();
  106. ERR_FAIL_COND_MSG(sc == nullptr, "failed to read geometry, prevented crash");
  107. ERR_FAIL_COND_MSG(!HasElement(sc, "Vertices"), "Detected mesh with no vertexes, didn't populate the mesh");
  108. // must have Mesh elements:
  109. const ElementPtr Vertices = GetRequiredElement(sc, "Vertices", element);
  110. const ElementPtr PolygonVertexIndex = GetRequiredElement(sc, "PolygonVertexIndex", element);
  111. if (HasElement(sc, "Edges")) {
  112. const ElementPtr element_edges = GetRequiredElement(sc, "Edges", element);
  113. ParseVectorDataArray(m_edges, element_edges);
  114. }
  115. // read mesh data into arrays
  116. ParseVectorDataArray(m_vertices, Vertices);
  117. ParseVectorDataArray(m_face_indices, PolygonVertexIndex);
  118. ERR_FAIL_COND_MSG(m_vertices.empty(), "mesh with no vertexes in FBX file, did you mean to delete it?");
  119. ERR_FAIL_COND_MSG(m_face_indices.empty(), "mesh has no faces, was this intended?");
  120. // Retrieve layer elements, for all of the mesh
  121. const ElementCollection &Layer = sc->GetCollection("Layer");
  122. // Store all layers
  123. std::vector<std::tuple<int, std::string>> valid_layers;
  124. // now read the sub mesh information from the geometry (normals, uvs, etc)
  125. for (ElementMap::const_iterator it = Layer.first; it != Layer.second; ++it) {
  126. const ScopePtr layer = GetRequiredScope(it->second);
  127. const ElementCollection &LayerElement = layer->GetCollection("LayerElement");
  128. for (ElementMap::const_iterator eit = LayerElement.first; eit != LayerElement.second; ++eit) {
  129. std::string layer_name = eit->first;
  130. ElementPtr element_layer = eit->second;
  131. const ScopePtr layer_element = GetRequiredScope(element_layer);
  132. // Actual usable 'type' LayerElementUV, LayerElementNormal, etc
  133. const ElementPtr Type = GetRequiredElement(layer_element, "Type");
  134. const ElementPtr TypedIndex = GetRequiredElement(layer_element, "TypedIndex");
  135. const std::string &type = ParseTokenAsString(GetRequiredToken(Type, 0));
  136. const int typedIndex = ParseTokenAsInt(GetRequiredToken(TypedIndex, 0));
  137. // we only need the layer name and the typed index.
  138. valid_layers.push_back(std::tuple<int, std::string>(typedIndex, type));
  139. }
  140. }
  141. // get object / mesh directly from the FBX by the element ID.
  142. const ScopePtr top = GetRequiredScope(element);
  143. // iterate over all layers for the mesh (uvs, normals, smoothing groups, colors, etc)
  144. for (size_t x = 0; x < valid_layers.size(); x++) {
  145. const int layer_id = std::get<0>(valid_layers[x]);
  146. const std::string &layer_type_name = std::get<1>(valid_layers[x]);
  147. // Get collection of elements from the XLayerMap (example: LayerElementUV)
  148. // this must contain our proper elements.
  149. // This is stupid, because it means we select them ALL not just the one we want.
  150. // but it's fine we can match by id.
  151. const ElementCollection &candidates = top->GetCollection(layer_type_name);
  152. ElementMap::const_iterator iter;
  153. for (iter = candidates.first; iter != candidates.second; ++iter) {
  154. const ScopePtr layer_scope = GetRequiredScope(iter->second);
  155. TokenPtr layer_token = GetRequiredToken(iter->second, 0);
  156. const int index = ParseTokenAsInt(layer_token);
  157. ERR_FAIL_COND_MSG(layer_scope == nullptr, "prevented crash, layer scope is invalid");
  158. if (index == layer_id) {
  159. const std::string &MappingInformationType = ParseTokenAsString(GetRequiredToken(
  160. GetRequiredElement(layer_scope, "MappingInformationType"), 0));
  161. const std::string &ReferenceInformationType = ParseTokenAsString(GetRequiredToken(
  162. GetRequiredElement(layer_scope, "ReferenceInformationType"), 0));
  163. if (layer_type_name == "LayerElementUV") {
  164. if (index == 0) {
  165. m_uv_0 = resolve_vertex_data_array<Vector2>(layer_scope, MappingInformationType, ReferenceInformationType, "UV");
  166. } else if (index == 1) {
  167. m_uv_1 = resolve_vertex_data_array<Vector2>(layer_scope, MappingInformationType, ReferenceInformationType, "UV");
  168. }
  169. } else if (layer_type_name == "LayerElementMaterial") {
  170. m_material_allocation_ids = resolve_vertex_data_array<int>(layer_scope, MappingInformationType, ReferenceInformationType, "Materials");
  171. } else if (layer_type_name == "LayerElementNormal") {
  172. m_normals = resolve_vertex_data_array<Vector3>(layer_scope, MappingInformationType, ReferenceInformationType, "Normals");
  173. } else if (layer_type_name == "LayerElementColor") {
  174. m_colors = resolve_vertex_data_array<Color>(layer_scope, MappingInformationType, ReferenceInformationType, "Colors", "ColorIndex");
  175. // NOTE: this is a useful sanity check to ensure you're getting any color data which is not default.
  176. // const Color first_color_check = m_colors.data[0];
  177. // bool colors_are_all_the_same = true;
  178. // size_t i = 1;
  179. // for(i = 1; i < m_colors.data.size(); i++)
  180. // {
  181. // const Color current_color = m_colors.data[i];
  182. // if(current_color.is_equal_approx(first_color_check))
  183. // {
  184. // continue;
  185. // }
  186. // else
  187. // {
  188. // colors_are_all_the_same = false;
  189. // break;
  190. // }
  191. // }
  192. //
  193. // if(colors_are_all_the_same)
  194. // {
  195. // print_error("Color serialisation is not working for vertex colors some should be different in the test asset.");
  196. // }
  197. // else
  198. // {
  199. // print_verbose("Color array has unique colors at index: " + itos(i));
  200. // }
  201. }
  202. }
  203. }
  204. }
  205. print_verbose("Mesh statistics \nuv_0: " + m_uv_0.debug_info() + "\nuv_1: " + m_uv_1.debug_info() + "\nvertices: " + itos(m_vertices.size()));
  206. // Compose the edge of the mesh.
  207. // You can see how the edges are stored into the FBX here: https://gist.github.com/AndreaCatania/da81840f5aa3b2feedf189e26c5a87e6
  208. for (size_t i = 0; i < m_edges.size(); i += 1) {
  209. ERR_FAIL_INDEX_MSG((size_t)m_edges[i], m_face_indices.size(), "The edge is pointing to a weird location in the face indices. The FBX is corrupted.");
  210. int polygon_vertex_0 = m_face_indices[m_edges[i]];
  211. int polygon_vertex_1;
  212. if (polygon_vertex_0 < 0) {
  213. // The polygon_vertex_0 points to the end of a polygon, so it's
  214. // connected with the beginning of polygon in the edge list.
  215. // Fist invert the vertex.
  216. polygon_vertex_0 = ~polygon_vertex_0;
  217. // Search the start vertex of the polygon.
  218. // Iterate from the polygon_vertex_index backward till the start of
  219. // the polygon is found.
  220. ERR_FAIL_COND_MSG(m_edges[i] - 1 < 0, "The polygon is not yet started and we already need the final vertex. This FBX is corrupted.");
  221. bool found_it = false;
  222. for (int x = m_edges[i] - 1; x >= 0; x -= 1) {
  223. if (x == 0) {
  224. // This for sure is the start.
  225. polygon_vertex_1 = m_face_indices[x];
  226. found_it = true;
  227. break;
  228. } else if (m_face_indices[x] < 0) {
  229. // This is the end of the previous polygon, so the next is
  230. // the start of the polygon we need.
  231. polygon_vertex_1 = m_face_indices[x + 1];
  232. found_it = true;
  233. break;
  234. }
  235. }
  236. // As the algorithm above, this check is useless. Because the first
  237. // ever vertex is always considered the begining of a polygon.
  238. ERR_FAIL_COND_MSG(found_it == false, "Was not possible to find the first vertex of this polygon. FBX file is corrupted.");
  239. } else {
  240. ERR_FAIL_INDEX_MSG((size_t)(m_edges[i] + 1), m_face_indices.size(), "FBX The other FBX edge seems to point to an invalid vertices. This FBX file is corrupted.");
  241. // Take the next vertex
  242. polygon_vertex_1 = m_face_indices[m_edges[i] + 1];
  243. }
  244. if (polygon_vertex_1 < 0) {
  245. // We don't care if the `polygon_vertex_1` is the end of the polygon,
  246. // for `polygon_vertex_1` so we can just invert it.
  247. polygon_vertex_1 = ~polygon_vertex_1;
  248. }
  249. ERR_FAIL_COND_MSG(polygon_vertex_0 == polygon_vertex_1, "The vertices of this edge can't be the same, Is this a point???. This FBX file is corrupted.");
  250. // Just create the edge.
  251. edge_map.push_back({ polygon_vertex_0, polygon_vertex_1 });
  252. }
  253. }
  254. MeshGeometry::~MeshGeometry() {
  255. // empty
  256. }
  257. const std::vector<Vector3> &MeshGeometry::get_vertices() const {
  258. return m_vertices;
  259. }
  260. const std::vector<MeshGeometry::Edge> &MeshGeometry::get_edge_map() const {
  261. return edge_map;
  262. }
  263. const std::vector<int> &MeshGeometry::get_polygon_indices() const {
  264. return m_face_indices;
  265. }
  266. const std::vector<int> &MeshGeometry::get_edges() const {
  267. return m_edges;
  268. }
  269. const MeshGeometry::MappingData<Vector3> &MeshGeometry::get_normals() const {
  270. return m_normals;
  271. }
  272. const MeshGeometry::MappingData<Vector2> &MeshGeometry::get_uv_0() const {
  273. //print_verbose("get uv_0 " + m_uv_0.debug_info() );
  274. return m_uv_0;
  275. }
  276. const MeshGeometry::MappingData<Vector2> &MeshGeometry::get_uv_1() const {
  277. //print_verbose("get uv_1 " + m_uv_1.debug_info() );
  278. return m_uv_1;
  279. }
  280. const MeshGeometry::MappingData<Color> &MeshGeometry::get_colors() const {
  281. return m_colors;
  282. }
  283. const MeshGeometry::MappingData<int> &MeshGeometry::get_material_allocation_id() const {
  284. return m_material_allocation_ids;
  285. }
  286. int MeshGeometry::get_edge_id(const std::vector<Edge> &p_map, int p_vertex_a, int p_vertex_b) {
  287. for (size_t i = 0; i < p_map.size(); i += 1) {
  288. if ((p_map[i].vertex_0 == p_vertex_a && p_map[i].vertex_1 == p_vertex_b) || (p_map[i].vertex_1 == p_vertex_a && p_map[i].vertex_0 == p_vertex_b)) {
  289. return i;
  290. }
  291. }
  292. return -1;
  293. }
  294. MeshGeometry::Edge MeshGeometry::get_edge(const std::vector<Edge> &p_map, int p_id) {
  295. ERR_FAIL_INDEX_V_MSG((size_t)p_id, p_map.size(), Edge({ -1, -1 }), "ID not found.");
  296. return p_map[p_id];
  297. }
  298. template <class T>
  299. MeshGeometry::MappingData<T> MeshGeometry::resolve_vertex_data_array(
  300. const ScopePtr source,
  301. const std::string &MappingInformationType,
  302. const std::string &ReferenceInformationType,
  303. const std::string &dataElementName,
  304. const std::string &indexOverride) {
  305. ERR_FAIL_COND_V_MSG(source == nullptr, MappingData<T>(), "Invalid scope operator preventing memory corruption");
  306. // UVIndex, MaterialIndex, NormalIndex, etc..
  307. std::string indexDataElementName;
  308. if (indexOverride != "") {
  309. // Colors should become ColorIndex
  310. indexDataElementName = indexOverride;
  311. } else {
  312. // Some indexes will exist.
  313. indexDataElementName = dataElementName + "Index";
  314. }
  315. // goal: expand everything to be per vertex
  316. ReferenceType l_ref_type = ReferenceType::direct;
  317. // Read the reference type into the enumeration
  318. if (ReferenceInformationType == "IndexToDirect") {
  319. l_ref_type = ReferenceType::index_to_direct;
  320. } else if (ReferenceInformationType == "Index") {
  321. // set non legacy index to direct mapping
  322. l_ref_type = ReferenceType::index;
  323. } else if (ReferenceInformationType == "Direct") {
  324. l_ref_type = ReferenceType::direct;
  325. } else {
  326. ERR_FAIL_V_MSG(MappingData<T>(), "invalid reference type has the FBX format changed?");
  327. }
  328. MapType l_map_type = MapType::none;
  329. if (MappingInformationType == "None") {
  330. l_map_type = MapType::none;
  331. } else if (MappingInformationType == "ByVertice") {
  332. l_map_type = MapType::vertex;
  333. } else if (MappingInformationType == "ByPolygonVertex") {
  334. l_map_type = MapType::polygon_vertex;
  335. } else if (MappingInformationType == "ByPolygon") {
  336. l_map_type = MapType::polygon;
  337. } else if (MappingInformationType == "ByEdge") {
  338. l_map_type = MapType::edge;
  339. } else if (MappingInformationType == "AllSame") {
  340. l_map_type = MapType::all_the_same;
  341. } else {
  342. print_error("invalid mapping type: " + String(MappingInformationType.c_str()));
  343. }
  344. // create mapping data
  345. MeshGeometry::MappingData<T> tempData;
  346. tempData.map_type = l_map_type;
  347. tempData.ref_type = l_ref_type;
  348. // parse data into array
  349. ParseVectorDataArray(tempData.data, GetRequiredElement(source, dataElementName));
  350. // index array wont always exist
  351. const ElementPtr element = GetOptionalElement(source, indexDataElementName);
  352. if (element) {
  353. ParseVectorDataArray(tempData.index, element);
  354. }
  355. return tempData;
  356. }
  357. // ------------------------------------------------------------------------------------------------
  358. ShapeGeometry::ShapeGeometry(uint64_t id, const ElementPtr element, const std::string &name, const Document &doc) :
  359. Geometry(id, element, name, doc) {
  360. const ScopePtr sc = element->Compound();
  361. if (nullptr == sc) {
  362. DOMError("failed to read Geometry object (class: Shape), no data scope found");
  363. }
  364. const ElementPtr Indexes = GetRequiredElement(sc, "Indexes", element);
  365. const ElementPtr Normals = GetRequiredElement(sc, "Normals", element);
  366. const ElementPtr Vertices = GetRequiredElement(sc, "Vertices", element);
  367. ParseVectorDataArray(m_indices, Indexes);
  368. ParseVectorDataArray(m_vertices, Vertices);
  369. ParseVectorDataArray(m_normals, Normals);
  370. }
  371. // ------------------------------------------------------------------------------------------------
  372. ShapeGeometry::~ShapeGeometry() {
  373. // empty
  374. }
  375. // ------------------------------------------------------------------------------------------------
  376. const std::vector<Vector3> &ShapeGeometry::GetVertices() const {
  377. return m_vertices;
  378. }
  379. // ------------------------------------------------------------------------------------------------
  380. const std::vector<Vector3> &ShapeGeometry::GetNormals() const {
  381. return m_normals;
  382. }
  383. // ------------------------------------------------------------------------------------------------
  384. const std::vector<unsigned int> &ShapeGeometry::GetIndices() const {
  385. return m_indices;
  386. }
  387. // ------------------------------------------------------------------------------------------------
  388. LineGeometry::LineGeometry(uint64_t id, const ElementPtr element, const std::string &name, const Document &doc) :
  389. Geometry(id, element, name, doc) {
  390. const ScopePtr sc = element->Compound();
  391. if (!sc) {
  392. DOMError("failed to read Geometry object (class: Line), no data scope found");
  393. }
  394. const ElementPtr Points = GetRequiredElement(sc, "Points", element);
  395. const ElementPtr PointsIndex = GetRequiredElement(sc, "PointsIndex", element);
  396. ParseVectorDataArray(m_vertices, Points);
  397. ParseVectorDataArray(m_indices, PointsIndex);
  398. }
  399. // ------------------------------------------------------------------------------------------------
  400. LineGeometry::~LineGeometry() {
  401. // empty
  402. }
  403. // ------------------------------------------------------------------------------------------------
  404. const std::vector<Vector3> &LineGeometry::GetVertices() const {
  405. return m_vertices;
  406. }
  407. // ------------------------------------------------------------------------------------------------
  408. const std::vector<int> &LineGeometry::GetIndices() const {
  409. return m_indices;
  410. }
  411. } // namespace FBXDocParser