--- /dev/null
+/// \file AMFImporter.cpp
+/// \brief AMF-format files importer for Assimp: main algorithm implementation.
+/// \date 2016
+/// \author smal.root@gmail.com
+
+#ifndef ASSIMP_BUILD_NO_AMF_IMPORTER
+
+// Header files, Assimp.
+#include "AMFImporter.hpp"
+#include "AMFImporter_Macro.hpp"
+
+#include "fast_atof.h"
+#include "DefaultIOSystem.h"
+
+// Header files, Boost.
+#include <boost/format.hpp>
+#include <boost/scoped_ptr.hpp>
+
+// Header files, stdlib.
+#include <string>
+
+namespace Assimp
+{
+
+/// \var aiImporterDesc AMFImporter::Description
+/// Conastant which hold importer description
+const aiImporterDesc AMFImporter::Description = {
+ "Additive manufacturing file format(AMF) Importer",
+ "smalcom",
+ "",
+ "See documentation in source code. Chapter: Limitations.",
+ aiImporterFlags_SupportTextFlavour | aiImporterFlags_LimitedSupport | aiImporterFlags_Experimental,
+ 0,
+ 0,
+ 0,
+ 0,
+ "amf"
+};
+
+void AMFImporter::Clear()
+{
+ mNodeElement_Cur = NULL;
+ mUnit.clear();
+ mMaterial_Converted.clear();
+ mTexture_Converted.clear();
+ // Delete all elements
+ if(mNodeElement_List.size())
+ {
+ for(std::list<CAMFImporter_NodeElement*>::iterator it = mNodeElement_List.begin(); it != mNodeElement_List.end(); it++) delete *it;
+
+ mNodeElement_List.clear();
+ }
+}
+
+AMFImporter::~AMFImporter()
+{
+ if(mReader != NULL) delete mReader;
+ // Clear() is accounting if data already is deleted. So, just check again if all data is deleted.
+ Clear();
+}
+
+/*********************************************************************************************************************************************/
+/************************************************************ Functions: find set ************************************************************/
+/*********************************************************************************************************************************************/
+
+bool AMFImporter::Find_NodeElement(const std::string& pID, const CAMFImporter_NodeElement::EType pType, CAMFImporter_NodeElement** pNodeElement) const
+{
+ for(std::list<CAMFImporter_NodeElement*>::const_iterator it = mNodeElement_List.begin(); it != mNodeElement_List.end(); it++)
+ {
+ if(((*it)->ID == pID) && ((*it)->Type == pType))
+ {
+ if(pNodeElement != NULL) *pNodeElement = *it;
+
+ return true;
+ }
+ }// for(std::list<CAMFImporter_NodeElement*>::const_iterator it = mNodeElement_List.begin(); it != mNodeElement_List.end(); it++)
+
+ return false;
+}
+
+bool AMFImporter::Find_ConvertedNode(const std::string& pID, std::list<aiNode*>& pNodeList, aiNode** pNode) const
+{
+aiString node_name(pID.c_str());
+
+ for(std::list<aiNode*>::const_iterator it = pNodeList.begin(); it != pNodeList.end(); it++)
+ {
+ if((*it)->mName == node_name)
+ {
+ if(pNode != NULL) *pNode = *it;
+
+ return true;
+ }
+ }// for(std::list<aiNode*>::const_iterator it = pNodeList.begin(); it != pNodeList.end(); it++)
+
+ return false;
+}
+
+bool AMFImporter::Find_ConvertedMaterial(const std::string& pID, const SPP_Material** pConvertedMaterial) const
+{
+ for(std::list<SPP_Material>::const_iterator it = mMaterial_Converted.begin(); it != mMaterial_Converted.end(); it++)
+ {
+ if((*it).ID == pID)
+ {
+ if(pConvertedMaterial != NULL) *pConvertedMaterial = (SPP_Material*)&(*it);
+
+ return true;
+ }
+ }// for(std::list<SPP_Material>::const_iterator it = mMaterial_Converted.begin(); it != mMaterial_Converted.end(); it++)
+
+ return false;
+}
+
+/*********************************************************************************************************************************************/
+/************************************************************ Functions: throw set ***********************************************************/
+/*********************************************************************************************************************************************/
+
+void AMFImporter::Throw_CloseNotFound(const std::string& pNode)
+{
+ throw DeadlyImportError("Close tag for node <" + pNode + "> not found. Seems file is corrupt.");
+}
+
+void AMFImporter::Throw_IncorrectAttr(const std::string& pAttrName)
+{
+ throw DeadlyImportError(boost::str(boost::format("Node <%s> has incorrect attribute \"%s\".") % mReader->getNodeName() % pAttrName));
+}
+
+void AMFImporter::Throw_IncorrectAttrValue(const std::string& pAttrName)
+{
+ throw DeadlyImportError(boost::str(boost::format("Attribute \"%s\" in node <%s> has incorrect value.") % pAttrName % mReader->getNodeName()));
+}
+
+void AMFImporter::Throw_MoreThanOnceDefined(const std::string& pNodeType, const std::string& pDescription)
+{
+ throw DeadlyImportError("\"" + pNodeType + "\" node can be used only once in " + mReader->getNodeName() + ". Description: " + pDescription);
+}
+
+void AMFImporter::Throw_ID_NotFound(const std::string& pID) const
+{
+ throw DeadlyImportError(boost::str(boost::format("Not found node with name \"%s\".") % pID));
+}
+
+/*********************************************************************************************************************************************/
+/************************************************************* Functions: XML set ************************************************************/
+/*********************************************************************************************************************************************/
+
+void AMFImporter::XML_CheckNode_MustHaveChildren()
+{
+ if(mReader->isEmptyElement()) throw DeadlyImportError(std::string("Node <") + mReader->getNodeName() + "> must have children.");
+}
+
+void AMFImporter::XML_CheckNode_SkipUnsupported(const std::string& pParentNodeName)
+{
+const size_t Uns_Skip_Len = 3;
+const char* Uns_Skip[Uns_Skip_Len] = { "composite", "edge", "normal" };
+
+static bool skipped_before[Uns_Skip_Len] = { false, false, false };
+
+std::string nn(mReader->getNodeName());
+bool found = false;
+bool close_found = false;
+size_t sk_idx;
+
+ for(sk_idx = 0; sk_idx < Uns_Skip_Len; sk_idx++)
+ {
+ if(nn != Uns_Skip[sk_idx]) continue;
+
+ found = true;
+ if(mReader->isEmptyElement())
+ {
+ close_found = true;
+
+ goto casu_cres;
+ }
+
+ while(mReader->read())
+ {
+ if((mReader->getNodeType() == irr::io::EXN_ELEMENT_END) && (nn == mReader->getNodeName()))
+ {
+ close_found = true;
+
+ goto casu_cres;
+ }
+ }
+ }// for(sk_idx = 0; sk_idx < Uns_Skip_Len; sk_idx++)
+
+casu_cres:
+
+ if(!found) throw DeadlyImportError(boost::str(boost::format("Unknown node \"%s\" in %s.") % nn % pParentNodeName));
+ if(!close_found) Throw_CloseNotFound(nn);
+
+ if(!skipped_before[sk_idx])
+ {
+ skipped_before[sk_idx] = true;
+ LogWarning(boost::str(boost::format("Skipping node \"%s\" in %s.") % nn % pParentNodeName));
+ }
+}
+
+bool AMFImporter::XML_SearchNode(const std::string& pNodeName)
+{
+ while(mReader->read())
+ {
+ if((mReader->getNodeType() == irr::io::EXN_ELEMENT) && XML_CheckNode_NameEqual(pNodeName)) return true;
+ }
+
+ return false;
+}
+
+bool AMFImporter::XML_ReadNode_GetAttrVal_AsBool(const int pAttrIdx)
+{
+std::string val(mReader->getAttributeValue(pAttrIdx));
+
+ if((val == "false") || (val == "0"))
+ return false;
+ else if((val == "true") || (val == "1"))
+ return true;
+ else
+ throw DeadlyImportError("Bool attribute value can contain \"false\"/\"0\" or \"true\"/\"1\" not the \"" + val + "\"");
+}
+
+float AMFImporter::XML_ReadNode_GetAttrVal_AsFloat(const int pAttrIdx)
+{
+std::string val;
+float tvalf;
+
+ ParseHelper_FixTruncatedFloatString(mReader->getAttributeValue(pAttrIdx), val);
+ fast_atoreal_move(val.c_str(), tvalf, false);
+
+ return tvalf;
+}
+
+uint32_t AMFImporter::XML_ReadNode_GetAttrVal_AsU32(const int pAttrIdx)
+{
+ return strtoul10(mReader->getAttributeValue(pAttrIdx));
+}
+
+float AMFImporter::XML_ReadNode_GetVal_AsFloat()
+{
+std::string val;
+float tvalf;
+
+ if(!mReader->read()) throw DeadlyImportError("XML_ReadNode_GetVal_AsFloat. No data, seems file is corrupt.");
+ if(mReader->getNodeType() != irr::io::EXN_TEXT) throw DeadlyImportError("XML_ReadNode_GetVal_AsFloat. Invalid type of XML element, seems file is corrupt.");
+
+ ParseHelper_FixTruncatedFloatString(mReader->getNodeData(), val);
+ fast_atoreal_move(val.c_str(), tvalf, false);
+
+ return tvalf;
+}
+
+uint32_t AMFImporter::XML_ReadNode_GetVal_AsU32()
+{
+ if(!mReader->read()) throw DeadlyImportError("XML_ReadNode_GetVal_AsU32. No data, seems file is corrupt.");
+ if(mReader->getNodeType() != irr::io::EXN_TEXT) throw DeadlyImportError("XML_ReadNode_GetVal_AsU32. Invalid type of XML element, seems file is corrupt.");
+
+ return strtoul10(mReader->getNodeData());
+}
+
+void AMFImporter::XML_ReadNode_GetVal_AsString(std::string& pValue)
+{
+ if(!mReader->read()) throw DeadlyImportError("XML_ReadNode_GetVal_AsString. No data, seems file is corrupt.");
+ if(mReader->getNodeType() != irr::io::EXN_TEXT)
+ throw DeadlyImportError("XML_ReadNode_GetVal_AsString. Invalid type of XML element, seems file is corrupt.");
+
+ pValue = mReader->getNodeData();
+}
+
+/*********************************************************************************************************************************************/
+/************************************************************ Functions: parse set ***********************************************************/
+/*********************************************************************************************************************************************/
+
+void AMFImporter::ParseHelper_Node_Enter(CAMFImporter_NodeElement* pNode)
+{
+ mNodeElement_Cur->Child.push_back(pNode);// add new element to current element child list.
+ mNodeElement_Cur = pNode;// switch current element to new one.
+}
+
+void AMFImporter::ParseHelper_Node_Exit()
+{
+ // check if we can walk up.
+ if(mNodeElement_Cur != NULL) mNodeElement_Cur = mNodeElement_Cur->Parent;
+}
+
+void AMFImporter::ParseHelper_FixTruncatedFloatString(const char* pInStr, std::string& pOutString)
+{
+size_t instr_len;
+
+ pOutString.clear();
+ instr_len = strlen(pInStr);
+ if(!instr_len) return;
+
+ pOutString.reserve(instr_len * 3 / 2);
+ // check and correct floats in format ".x". Must be "x.y".
+ if(pInStr[0] == '.') pOutString.push_back('0');
+
+ pOutString.push_back(pInStr[0]);
+ for(size_t ci = 1; ci < instr_len; ci++)
+ {
+ if((pInStr[ci] == '.') && ((pInStr[ci - 1] == ' ') || (pInStr[ci - 1] == '-') || (pInStr[ci - 1] == '+') || (pInStr[ci - 1] == '\t')))
+ {
+ pOutString.push_back('0');
+ pOutString.push_back('.');
+ }
+ else
+ {
+ pOutString.push_back(pInStr[ci]);
+ }
+ }
+}
+
+static bool ParseHelper_Decode_Base64_IsBase64(const char pChar)
+{
+ return (isalnum(pChar) || (pChar == '+') || (pChar == '/'));
+}
+
+void AMFImporter::ParseHelper_Decode_Base64(const std::string& pInputBase64, std::vector<uint8_t>& pOutputData) const
+{
+// With help from
+// RenИ Nyffenegger http://www.adp-gmbh.ch/cpp/common/base64.html
+const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+uint8_t tidx = 0;
+uint8_t arr4[4], arr3[3];
+
+ // check input data
+ if(pInputBase64.size() % 4) throw DeadlyImportError("Base64-encoded data must have size multiply of four.");
+ // prepare output place
+ pOutputData.clear();
+ pOutputData.reserve(pInputBase64.size() / 4 * 3);
+
+ for(size_t in_len = pInputBase64.size(), in_idx = 0; (in_len > 0) && (pInputBase64[in_idx] != '='); in_len--)
+ {
+ if(ParseHelper_Decode_Base64_IsBase64(pInputBase64[in_idx]))
+ {
+ arr4[tidx++] = pInputBase64[in_idx++];
+ if(tidx == 4)
+ {
+ for(tidx = 0; tidx < 4; tidx++) arr4[tidx] = (uint8_t)base64_chars.find(arr4[tidx]);
+
+ arr3[0] = (arr4[0] << 2) + ((arr4[1] & 0x30) >> 4);
+ arr3[1] = ((arr4[1] & 0x0F) << 4) + ((arr4[2] & 0x3C) >> 2);
+ arr3[2] = ((arr4[2] & 0x03) << 6) + arr4[3];
+ for(tidx = 0; tidx < 3; tidx++) pOutputData.push_back(arr3[tidx]);
+
+ tidx = 0;
+ }// if(tidx == 4)
+ }// if(ParseHelper_Decode_Base64_IsBase64(pInputBase64[in_idx]))
+ else
+ {
+ in_idx++;
+ }// if(ParseHelper_Decode_Base64_IsBase64(pInputBase64[in_idx])) else
+ }
+
+ if(tidx)
+ {
+ for(uint8_t i = tidx; i < 4; i++) arr4[i] = 0;
+ for(uint8_t i = 0; i < 4; i++) arr4[i] = (uint8_t)(base64_chars.find(arr4[i]));
+
+ arr3[0] = (arr4[0] << 2) + ((arr4[1] & 0x30) >> 4);
+ arr3[1] = ((arr4[1] & 0x0F) << 4) + ((arr4[2] & 0x3C) >> 2);
+ arr3[2] = ((arr4[2] & 0x03) << 6) + arr4[3];
+ for(uint8_t i = 0; i < (tidx - 1); i++) pOutputData.push_back(arr3[i]);
+ }
+}
+
+void AMFImporter::ParseFile(const std::string& pFile, IOSystem* pIOHandler)
+{
+irr::io::IrrXMLReader* OldReader = mReader;// store current XMLreader.
+boost::scoped_ptr<IOStream> file(pIOHandler->Open(pFile, "rb"));
+
+ // Check whether we can read from the file
+ if(file.get() == NULL) throw DeadlyImportError("Failed to open AMF file " + pFile + ".");
+
+ // generate a XML reader for it
+ boost::scoped_ptr<CIrrXML_IOStreamReader> mIOWrapper(new CIrrXML_IOStreamReader(file.get()));
+ mReader = irr::io::createIrrXMLReader(mIOWrapper.get());
+ if(!mReader) throw DeadlyImportError("Failed to create XML reader for file" + pFile + ".");
+ //
+ // start reading
+ // search for root tag <amf>
+ if(XML_SearchNode("amf"))
+ ParseNode_Root();
+ else
+ throw DeadlyImportError("Root node \"amf\" not found.");
+
+ delete mReader;
+ // restore old XMLreader
+ mReader = OldReader;
+}
+
+// <amf
+// unit="" - The units to be used. May be "inch", "millimeter", "meter", "feet", or "micron".
+// version="" - Version of file format.
+// >
+// </amf>
+// Root XML element.
+// Multi elements - No.
+void AMFImporter::ParseNode_Root()
+{
+std::string unit, version;
+CAMFImporter_NodeElement* ne;
+
+ // Read attributes for node <amf>.
+ MACRO_ATTRREAD_LOOPBEG;
+ MACRO_ATTRREAD_CHECK_RET("unit", unit, mReader->getAttributeValue);
+ MACRO_ATTRREAD_CHECK_RET("version", version, mReader->getAttributeValue);
+ MACRO_ATTRREAD_LOOPEND_WSKIP;
+
+ // Check attributes
+ if(!mUnit.empty())
+ {
+ if((mUnit != "inch") && (mUnit != "millimeter") && (mUnit != "meter") && (mUnit != "feet") && (mUnit != "micron")) Throw_IncorrectAttrValue("unit");
+ }
+
+ // create root node element.
+ ne = new CAMFImporter_NodeElement_Root(NULL);
+ mNodeElement_Cur = ne;// set first "current" element
+ // and assign attribute's values
+ ((CAMFImporter_NodeElement_Root*)ne)->Unit = unit;
+ ((CAMFImporter_NodeElement_Root*)ne)->Version = version;
+
+ // Check for child nodes
+ if(!mReader->isEmptyElement())
+ {
+ MACRO_NODECHECK_LOOPBEGIN("amf");
+ if(XML_CheckNode_NameEqual("object")) { ParseNode_Object(); continue; }
+ if(XML_CheckNode_NameEqual("material")) { ParseNode_Material(); continue; }
+ if(XML_CheckNode_NameEqual("texture")) { ParseNode_Texture(); continue; }
+ if(XML_CheckNode_NameEqual("constellation")) { ParseNode_Constellation(); continue; }
+ if(XML_CheckNode_NameEqual("metadata")) { ParseNode_Metadata(); continue; }
+ MACRO_NODECHECK_LOOPEND("amf");
+ mNodeElement_Cur = ne;// force restore "current" element
+ }// if(!mReader->isEmptyElement())
+
+ mNodeElement_List.push_back(ne);// add to node element list because its a new object in graph.
+}
+
+// <constellation
+// id="" - The Object ID of the new constellation being defined.
+// >
+// </constellation>
+// A collection of objects or constellations with specific relative locations.
+// Multi elements - Yes.
+// Parent element - <amf>.
+void AMFImporter::ParseNode_Constellation()
+{
+std::string id;
+CAMFImporter_NodeElement* ne;
+
+ // Read attributes for node <constellation>.
+ MACRO_ATTRREAD_LOOPBEG;
+ MACRO_ATTRREAD_CHECK_RET("id", id, mReader->getAttributeValue);
+ MACRO_ATTRREAD_LOOPEND;
+
+ // create and if needed - define new grouping object.
+ ne = new CAMFImporter_NodeElement_Constellation(mNodeElement_Cur);
+
+ CAMFImporter_NodeElement_Constellation& als = *((CAMFImporter_NodeElement_Constellation*)ne);// alias for convenience
+
+ if(!id.empty()) als.ID = id;
+ // Check for child nodes
+ if(!mReader->isEmptyElement())
+ {
+ ParseHelper_Node_Enter(ne);
+ MACRO_NODECHECK_LOOPBEGIN("constellation");
+ if(XML_CheckNode_NameEqual("instance")) { ParseNode_Instance(); continue; }
+ if(XML_CheckNode_NameEqual("metadata")) { ParseNode_Metadata(); continue; }
+ MACRO_NODECHECK_LOOPEND("constellation");
+ ParseHelper_Node_Exit();
+ }// if(!mReader->isEmptyElement())
+ else
+ {
+ mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
+ }// if(!mReader->isEmptyElement()) else
+
+ mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph.
+}
+
+// <instance
+// objectid="" - The Object ID of the new constellation being defined.
+// >
+// </instance>
+// A collection of objects or constellations with specific relative locations.
+// Multi elements - Yes.
+// Parent element - <amf>.
+void AMFImporter::ParseNode_Instance()
+{
+std::string objectid;
+CAMFImporter_NodeElement* ne;
+
+ // Read attributes for node <constellation>.
+ MACRO_ATTRREAD_LOOPBEG;
+ MACRO_ATTRREAD_CHECK_RET("objectid", objectid, mReader->getAttributeValue);
+ MACRO_ATTRREAD_LOOPEND;
+
+ // used object id must be defined, check that.
+ if(objectid.empty()) throw DeadlyImportError("\"objectid\" in <instance> must be defined.");
+ // create and define new grouping object.
+ ne = new CAMFImporter_NodeElement_Instance(mNodeElement_Cur);
+
+ CAMFImporter_NodeElement_Instance& als = *((CAMFImporter_NodeElement_Instance*)ne);// alias for convenience
+
+ als.ObjectID = objectid;
+ // Check for child nodes
+ if(!mReader->isEmptyElement())
+ {
+ bool read_flag[6] = { false, false, false, false, false, false };
+
+ als.Delta.Set(0, 0, 0);
+ als.Rotation.Set(0, 0, 0);
+ ParseHelper_Node_Enter(ne);
+ MACRO_NODECHECK_LOOPBEGIN("instance");
+ MACRO_NODECHECK_READCOMP_F("deltax", read_flag[0], als.Delta.x);
+ MACRO_NODECHECK_READCOMP_F("deltay", read_flag[1], als.Delta.y);
+ MACRO_NODECHECK_READCOMP_F("deltaz", read_flag[2], als.Delta.z);
+ MACRO_NODECHECK_READCOMP_F("rx", read_flag[3], als.Rotation.x);
+ MACRO_NODECHECK_READCOMP_F("ry", read_flag[4], als.Rotation.y);
+ MACRO_NODECHECK_READCOMP_F("rz", read_flag[5], als.Rotation.z);
+ MACRO_NODECHECK_LOOPEND("instance");
+ ParseHelper_Node_Exit();
+ // also convert degrees to radians.
+ als.Rotation.x = AI_MATH_PI_F * als.Rotation.x / 180.0f;
+ als.Rotation.y = AI_MATH_PI_F * als.Rotation.y / 180.0f;
+ als.Rotation.z = AI_MATH_PI_F * als.Rotation.z / 180.0f;
+ }// if(!mReader->isEmptyElement())
+ else
+ {
+ mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
+ }// if(!mReader->isEmptyElement()) else
+
+ mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph.
+}
+
+// <object
+// id="" - A unique ObjectID for the new object being defined.
+// >
+// </object>
+// An object definition.
+// Multi elements - Yes.
+// Parent element - <amf>.
+void AMFImporter::ParseNode_Object()
+{
+std::string id;
+CAMFImporter_NodeElement* ne;
+
+ // Read attributes for node <object>.
+ MACRO_ATTRREAD_LOOPBEG;
+ MACRO_ATTRREAD_CHECK_RET("id", id, mReader->getAttributeValue);
+ MACRO_ATTRREAD_LOOPEND;
+
+ // create and if needed - define new geometry object.
+ ne = new CAMFImporter_NodeElement_Object(mNodeElement_Cur);
+
+ CAMFImporter_NodeElement_Object& als = *((CAMFImporter_NodeElement_Object*)ne);// alias for convenience
+
+ if(!id.empty()) als.ID = id;
+ // Check for child nodes
+ if(!mReader->isEmptyElement())
+ {
+ bool col_read = false;
+
+ ParseHelper_Node_Enter(ne);
+ MACRO_NODECHECK_LOOPBEGIN("object");
+ if(XML_CheckNode_NameEqual("color"))
+ {
+ // Check if color already defined for object.
+ if(col_read) Throw_MoreThanOnceDefined("color", "Only one color can be defined for <object>.");
+ // read data and set flag about it
+ ParseNode_Color();
+ col_read = true;
+
+ continue;
+ }
+
+ if(XML_CheckNode_NameEqual("mesh")) { ParseNode_Mesh(); continue; }
+ if(XML_CheckNode_NameEqual("metadata")) { ParseNode_Metadata(); continue; }
+ MACRO_NODECHECK_LOOPEND("object");
+ ParseHelper_Node_Exit();
+ }// if(!mReader->isEmptyElement())
+ else
+ {
+ mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
+ }// if(!mReader->isEmptyElement()) else
+
+ mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph.
+}
+
+// <metadata
+// type="" - The type of the attribute.
+// >
+// </metadata>
+// Specify additional information about an entity.
+// Multi elements - Yes.
+// Parent element - <amf>, <object>, <volume>, <material>, <vertex>.
+//
+// Reserved types are:
+// "Name" - The alphanumeric label of the entity, to be used by the interpreter if interacting with the user.
+// "Description" - A description of the content of the entity
+// "URL" - A link to an external resource relating to the entity
+// "Author" - Specifies the name(s) of the author(s) of the entity
+// "Company" - Specifying the company generating the entity
+// "CAD" - specifies the name of the originating CAD software and version
+// "Revision" - specifies the revision of the entity
+// "Tolerance" - specifies the desired manufacturing tolerance of the entity in entity's unit system
+// "Volume" - specifies the total volume of the entity, in the entity's unit system, to be used for verification (object and volume only)
+void AMFImporter::ParseNode_Metadata()
+{
+std::string type, value;
+CAMFImporter_NodeElement* ne;
+
+ // read attribute
+ MACRO_ATTRREAD_LOOPBEG;
+ MACRO_ATTRREAD_CHECK_RET("type", type, mReader->getAttributeValue);
+ MACRO_ATTRREAD_LOOPEND;
+ // and value of node.
+ value = mReader->getNodeData();
+ // Create node element and assign read data.
+ ne = new CAMFImporter_NodeElement_Metadata(mNodeElement_Cur);
+ ((CAMFImporter_NodeElement_Metadata*)ne)->Type = type;
+ ((CAMFImporter_NodeElement_Metadata*)ne)->Value = value;
+ mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
+ mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph.
+}
+
+/*********************************************************************************************************************************************/
+/******************************************************** Functions: BaseImporter set ********************************************************/
+/*********************************************************************************************************************************************/
+
+bool AMFImporter::CanRead(const std::string& pFile, IOSystem* pIOHandler, bool pCheckSig) const
+{
+const std::string extension = GetExtension(pFile);
+
+ if(extension == "amf") return true;
+
+ if(!extension.length() || pCheckSig)
+ {
+ const char* tokens[] = { "<?xml", "<amf" };
+
+ return SearchFileHeaderForToken(pIOHandler, pFile, tokens, 2);
+ }
+
+ return false;
+}
+
+void AMFImporter::GetExtensionList(std::set<std::string>& pExtensionList)
+{
+ pExtensionList.insert("amf");
+}
+
+const aiImporterDesc* AMFImporter::GetInfo () const
+{
+ return &Description;
+}
+
+void AMFImporter::InternReadFile(const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
+{
+ Clear();// delete old graph.
+ ParseFile(pFile, pIOHandler);
+ Postprocess_BuildScene(pScene);
+ // scene graph is ready, exit.
+}
+
+}// namespace Assimp
+
+#endif // !ASSIMP_BUILD_NO_AMF_IMPORTER
--- /dev/null
+/// \file AMFImporter.hpp
+/// \brief AMF-format files importer for Assimp.
+/// \date 2016
+/// \author smal.root@gmail.com
+// Thanks to acorn89 for support.
+
+#ifndef INCLUDED_AI_AMF_IMPORTER_H
+#define INCLUDED_AI_AMF_IMPORTER_H
+
+#include "AMFImporter_Node.hpp"
+
+// Header files, Assimp.
+#include "assimp/DefaultLogger.hpp"
+#include "assimp/importerdesc.h"
+#include "assimp/ProgressHandler.hpp"
+#include "assimp/types.h"
+#include "BaseImporter.h"
+#include "irrXMLWrapper.h"
+
+// Header files, stdlib.
+#include <set>
+
+namespace Assimp
+{
+/// \class AMFImporter
+/// Class that holding scene graph which include: geometry, metadata, materials etc.
+///
+/// Implementing features.
+///
+/// Triangles/faces colors and texture mapping.
+/// In both cases used same method. At begin - Assimp declare that
+/// "A mesh may contain 0 to #AI_MAX_NUMBER_OF_COLOR_SETS vertex colors per vertex. NULL if not present. Each array is mNumVertices in size if present."
+/// and
+/// "A mesh may contain 0 to AI_MAX_NUMBER_OF_TEXTURECOORDS per vertex. NULL if not present. The array is mNumVertices in size.".
+/// As you seen arrays must has mNumVertices in size. But Assimp can not check size of that arrays. So, we can create create arrays with any size.
+/// That is used. For colors importer create two arrays mColors: one for vertices colors and one for faces colors.
+/// For texture mapping used one more feature: Assimp can not store texture ID for every face. In this case importer also create two arrays mTextureCoords:
+/// one for texture coordinates of faces and one for texture IDs of faces.
+///
+/// Using \ref achFormatHint in \ref aiTexture importer set information about texture properties. For now used:
+/// Texture format description used in achFormatHint array:
+/// Byte 0
+/// Bit 0 - texture fill mode:
+/// value 0 - clamp
+/// value 1 - repeat
+///
+///
+/// Limitations.
+///
+/// Unsupported features:
+/// 1. Node <composite>, formulas in <composite> and <color>. For implementing this feature can be used expression parser "muParser" like in project
+/// "amf_tools".
+/// 2. Attribute "profile" in node <color>.
+/// 3. Curved geometry: <edge>, <normal> and children nodes of them.
+/// 4. Attributes: "unit" and "version" in <amf> read but do nothing.
+/// 5. <metadata> stored only for root node <amf>.
+/// 6. When for texture mappinf used set of source textures (r, g, b, a) not only one then attribute "tiled" for all set will be true if it true in any of
+/// source textures.
+/// Example. Triangle use for texture mapping three textures. Two of them has "tiled" set to false and one - set to true. In scene all three textures
+/// will be tiled.
+/// 7. Color averaging of vertices for which <triangle>'s set different colors.
+///
+/// Supported nodes:
+/// General:
+/// <amf>; <constellation>; <instance> and children <deltax>, <deltay>, <deltaz>, <rx>, <ry>, <rz>; <metadata>;
+///
+/// Geometry:
+/// <object>; <mesh>; <vertices>; <vertex>; <coordinates> and children <x>, <y>, <z>; <volume>; <triangle> and children <v1>, <v2>, <v3>;
+///
+/// Material:
+/// <color> and children <r>, <g>, <b>, <a>; <texture>; <material>;
+/// two variants of texture coordinates:
+/// new - <texmap> and children <utex1>, <utex2>, <utex3>, <vtex1>, <vtex2>, <vtex3>
+/// old - <map> and children <u1>, <u2>, <u3>, <v1>, <v2>, <v3>
+///
+class AMFImporter : public BaseImporter
+{
+ /***********************************************/
+ /******************** Types ********************/
+ /***********************************************/
+
+private:
+
+ struct SPP_Material;// forward declaration
+
+ /// \struct SPP_Composite
+ /// Data type for postprocessing step. More suitable container for part of material's composition.
+ struct SPP_Composite
+ {
+ SPP_Material* Material;///< Pointer to material - part of composition.
+ std::string Formula;///< Formula for calculating ratio of \ref Material.
+ };
+
+ /// \struct SPP_Material
+ /// Data type for postprocessing step. More suitable container for material.
+ struct SPP_Material
+ {
+ std::string ID;///< Material ID.
+ std::list<CAMFImporter_NodeElement_Metadata*> Metadata;///< Metadata of material.
+ CAMFImporter_NodeElement_Color* Color;///< Color of material.
+ std::list<SPP_Composite> Composition;///< List of child materials if current material is composition of few another.
+
+ /// \fn aiColor4D GetColor(const float pX, const float pY, const float pZ) const
+ /// Return color calculated for specified coordinate.
+ /// \param [in] pX - "x" coordinate.
+ /// \param [in] pY - "y" coordinate.
+ /// \param [in] pZ - "z" coordinate.
+ /// \return calculated color.
+ aiColor4D GetColor(const float pX, const float pY, const float pZ) const;
+ };
+
+ /// \struct SPP_Texture
+ /// Data type for postprocessing step. More suitable container for texture.
+ struct SPP_Texture
+ {
+ std::string ID;
+ size_t Width, Height, Depth;
+ bool Tiled;
+ decltype(aiTexture::achFormatHint) FormatHint;
+ uint8_t* Data;
+ };
+
+ /// \struct SComplexFace
+ /// Data type for postprocessing step. Contain face data.
+ struct SComplexFace
+ {
+ aiFace Face;///< Face vertices.
+ const CAMFImporter_NodeElement_Color* Color;///< Face color. Equal to nullptr if color is not set for the face.
+ const CAMFImporter_NodeElement_TexMap* TexMap;///< Face texture mapping data. Equal to nullptr if texture mapping is not set for the face.
+ };
+
+
+
+ /***********************************************/
+ /****************** Constants ******************/
+ /***********************************************/
+
+private:
+
+ static const aiImporterDesc Description;
+
+ /***********************************************/
+ /****************** Variables ******************/
+ /***********************************************/
+
+private:
+
+ CAMFImporter_NodeElement* mNodeElement_Cur;///< Current element.
+ std::list<CAMFImporter_NodeElement*> mNodeElement_List;///< All elements of scene graph.
+ irr::io::IrrXMLReader* mReader;///< Pointer to XML-reader object
+ std::string mUnit;
+ std::list<SPP_Material> mMaterial_Converted;///< List of converted materials for postprocessing step.
+ std::list<SPP_Texture> mTexture_Converted;///< List of converted textures for postprocessing step.
+
+ /***********************************************/
+ /****************** Functions ******************/
+ /***********************************************/
+
+private:
+
+ /// \fn AMFImporter(const AMFImporter& pScene)
+ /// Disabled copy constructor.
+ AMFImporter(const AMFImporter& pScene);
+
+ /// \fn AMFImporter& operator=(const AMFImporter& pScene)
+ /// Disabled assign operator.
+ AMFImporter& operator=(const AMFImporter& pScene);
+
+ /// \fn void Clear()
+ /// Clear all temporary data.
+ void Clear();
+
+ /***********************************************/
+ /************* Functions: find set *************/
+ /***********************************************/
+
+ /// \fn bool Find_NodeElement(const std::string& pID, const CAMFImporter_NodeElement::EType pType, aiNode** pNode) const
+ /// Find specified node element in node elements list ( \ref mNodeElement_List).
+ /// \param [in] pID - ID(name) of requested node element.
+ /// \param [in] pType - type of node element.
+ /// \param [out] pNode - pointer to pointer to item found.
+ /// \return true - if the node element is found, else - false.
+ bool Find_NodeElement(const std::string& pID, const CAMFImporter_NodeElement::EType pType, CAMFImporter_NodeElement** pNodeElement) const;
+
+ /// \fn bool Find_ConvertedNode(const std::string& pID, std::list<aiNode*>& pNodeList, aiNode** pNode) const
+ /// Find requested aiNode in node list.
+ /// \param [in] pID - ID(name) of requested node.
+ /// \param [in] pNodeList - list of nodes where to find the node.
+ /// \param [out] pNode - pointer to pointer to item found.
+ /// \return true - if the node is found, else - false.
+ bool Find_ConvertedNode(const std::string& pID, std::list<aiNode*>& pNodeList, aiNode** pNode) const;
+
+ /// \fn bool Find_ConvertedMaterial(const std::string& pID, const SPP_Material** pConvertedMaterial) const
+ /// Find material in list for converted materials. Use at postprocessing step.
+ /// \param [in] pID - material ID.
+ /// \param [out] pConvertedMaterial - pointer to found converted material (\ref SPP_Material).
+ /// \return true - if the material is found, else - false.
+ bool Find_ConvertedMaterial(const std::string& pID, const SPP_Material** pConvertedMaterial) const;
+
+ /// \fn bool Find_ConvertedTexture(const std::string& pID_R, const std::string& pID_G, const std::string& pID_B, const std::string& pID_A, uint32_t* pConvertedTextureIndex = NULL) const
+ /// Find texture in list of converted textures. Use at postprocessing step,
+ /// \param [in] pID_R - ID of source "red" texture.
+ /// \param [in] pID_G - ID of source "green" texture.
+ /// \param [in] pID_B - ID of source "blue" texture.
+ /// \param [in] pID_A - ID of source "alpha" texture. Use empty string to find RGB-texture.
+ /// \param [out] pConvertedTextureIndex - pointer where index in list of found texture will be written. If equivalent to NULL then nothing will be written.
+ /// \return true - if the texture is found, else - false.
+ bool Find_ConvertedTexture(const std::string& pID_R, const std::string& pID_G, const std::string& pID_B, const std::string& pID_A,
+ uint32_t* pConvertedTextureIndex = NULL) const;
+
+ /***********************************************/
+ /********* Functions: postprocess set **********/
+ /***********************************************/
+
+ /// \fn void PostprocessHelper_CreateMeshDataArray(const CAMFImporter_NodeElement_Mesh& pNodeElement, std::vector<aiVector3D>& pVertexCoordinateArray, std::vector<CAMFImporter_NodeElement_Color*>& pVertexColorArray) const
+ /// Get data stored in <vertices> and place it to arrays.
+ /// \param [in] pNodeElement - reference to node element which kept <object> data.
+ /// \param [in] pVertexCoordinateArray - reference to vertices coordinates kept in <vertices>.
+ /// \param [in] pVertexColorArray - reference to vertices colors for all <vertex's. If color for vertex is not set then corresponding member of array
+ /// contain NULL.
+ void PostprocessHelper_CreateMeshDataArray(const CAMFImporter_NodeElement_Mesh& pNodeElement, std::vector<aiVector3D>& pVertexCoordinateArray,
+ std::vector<CAMFImporter_NodeElement_Color*>& pVertexColorArray) const;
+
+ /// \fn size_t PostprocessHelper_GetTextureID_Or_Create(const std::string& pID_R, const std::string& pID_G, const std::string& pID_B, const std::string& pID_A)
+ /// Return converted texture ID which related to specified source textures ID's. If converted texture does not exist then it will be created and ID on new
+ /// converted texture will be returned. Convertion: set of textures from \ref CAMFImporter_NodeElement_Texture to one \ref SPP_Texture and place it
+ /// to converted textures list.
+ /// Any of source ID's can be absent(empty string) or even one ID only specified. But at least one ID must be specified.
+ /// \param [in] pID_R - ID of source "red" texture.
+ /// \param [in] pID_G - ID of source "green" texture.
+ /// \param [in] pID_B - ID of source "blue" texture.
+ /// \param [in] pID_A - ID of source "alpha" texture.
+ /// \return index of the texture in array of the converted textures.
+ size_t PostprocessHelper_GetTextureID_Or_Create(const std::string& pID_R, const std::string& pID_G, const std::string& pID_B, const std::string& pID_A);
+
+ /// \fn void PostprocessHelper_SplitFacesByTextureID(std::list<SComplexFace>& pInputList, std::list<std::list<SComplexFace> > pOutputList_Separated)
+ /// Separate input list by texture IDs. This step is needed because aiMesh can contain mesh which is use only one texture (or set: diffuse, bump etc).
+ /// \param [in] pInputList - input list with faces. Some of them can contain color or texture mapping, or both of them, or nothing. Will be cleared after
+ /// processing.
+ /// \param [out] pOutputList_Separated - output list of the faces lists. Separated faces list by used texture IDs. Will be cleared before processing.
+ void PostprocessHelper_SplitFacesByTextureID(std::list<SComplexFace>& pInputList, std::list<std::list<SComplexFace> >& pOutputList_Separated);
+
+ /// \fn void Postprocess_AddMetadata(const std::list<CAMFImporter_NodeElement_Metadata*>& pMetadataList, aiNode& pSceneNode) const
+ /// Check if child elements of node element is metadata and add it to scene node.
+ /// \param [in] pMetadataList - reference to list with collected metadata.
+ /// \param [out] pSceneNode - scene node in which metadata will be added.
+ void Postprocess_AddMetadata(const std::list<CAMFImporter_NodeElement_Metadata*>& pMetadataList, aiNode& pSceneNode) const;
+
+ /// \fn void Postprocess_BuildNodeAndObject(const CAMFImporter_NodeElement_Object& pNodeElement, std::list<aiMesh*>& pMeshList, aiNode** pSceneNode)
+ /// To create aiMesh and aiNode for it from <object>.
+ /// \param [in] pNodeElement - reference to node element which kept <object> data.
+ /// \param [out] pMeshList - reference to a list with all aiMesh of the scene.
+ /// \param [out] pSceneNode - pointer to place where new aiNode will be created.
+ void Postprocess_BuildNodeAndObject(const CAMFImporter_NodeElement_Object& pNodeElement, std::list<aiMesh*>& pMeshList, aiNode** pSceneNode);
+
+ /// \fn void Postprocess_BuildMeshSet(const CAMFImporter_NodeElement_Mesh& pNodeElement, const std::vector<aiVector3D>& pVertexCoordinateArray, const std::vector<CAMFImporter_NodeElement_Color*>& pVertexColorArray, const CAMFImporter_NodeElement_Color* pObjectColor, std::list<aiMesh*>& pMeshList, aiNode& pSceneNode)
+ /// Create mesh for every <volume> in <mesh>.
+ /// \param [in] pNodeElement - reference to node element which kept <mesh> data.
+ /// \param [in] pVertexCoordinateArray - reference to vertices coordinates for all <volume>'s.
+ /// \param [in] pVertexColorArray - reference to vertices colors for all <volume>'s. If color for vertex is not set then corresponding member of array
+ /// contain NULL.
+ /// \param [in] pObjectColor - pointer to colors for <object>. If color is not set then argument contain NULL.
+ /// \param [in] pMaterialList - reference to a list with defined materials.
+ /// \param [out] pMeshList - reference to a list with all aiMesh of the scene.
+ /// \param [out] pSceneNode - reference to aiNode which will own new aiMesh's.
+ void Postprocess_BuildMeshSet(const CAMFImporter_NodeElement_Mesh& pNodeElement, const std::vector<aiVector3D>& pVertexCoordinateArray,
+ const std::vector<CAMFImporter_NodeElement_Color*>& pVertexColorArray, const CAMFImporter_NodeElement_Color* pObjectColor,
+ std::list<aiMesh*>& pMeshList, aiNode& pSceneNode);
+
+ /// \fn void Postprocess_BuildMaterial(const CAMFImporter_NodeElement_Material& pMaterial)
+ /// Convert material from \ref CAMFImporter_NodeElement_Material to \ref SPP_Material.
+ /// \param [in] pMaterial - source CAMFImporter_NodeElement_Material.
+ void Postprocess_BuildMaterial(const CAMFImporter_NodeElement_Material& pMaterial);
+
+ /// \fn void Postprocess_BuildConstellation(CAMFImporter_NodeElement_Constellation& pConstellation, std::list<aiNode*>& pNodeList) const
+ /// Create and add to aiNode's list new part of scene graph defined by <constellation>.
+ /// \param [in] pConstellation - reference to <constellation> node.
+ /// \param [out] pNodeList - reference to aiNode's list.
+ void Postprocess_BuildConstellation(CAMFImporter_NodeElement_Constellation& pConstellation, std::list<aiNode*>& pNodeList) const;
+
+ /// \fn void Postprocess_BuildScene()
+ /// Build Assimp scene graph in aiScene from collected data.
+ /// \param [out] pScene - pointer to aiScene where tree will be built.
+ void Postprocess_BuildScene(aiScene* pScene);
+
+ /***********************************************/
+ /************* Functions: throw set ************/
+ /***********************************************/
+
+ /// \fn void Throw_CloseNotFound(const std::string& pNode)
+ /// Call that function when close tag of node not found and exception must be raised.
+ /// E.g.:
+ /// <amf>
+ /// <object>
+ /// </amf> <!--- object not closed --->
+ /// \throw DeadlyImportError.
+ /// \param [in] pNode - node name in which exception happened.
+ void Throw_CloseNotFound(const std::string& pNode);
+
+ /// \fn void Throw_IncorrectAttr(const std::string& pAttrName)
+ /// Call that function when attribute name is incorrect and exception must be raised.
+ /// \param [in] pAttrName - attribute name.
+ /// \throw DeadlyImportError.
+ void Throw_IncorrectAttr(const std::string& pAttrName);
+
+ /// \fn void Throw_IncorrectAttrValue(const std::string& pAttrName)
+ /// Call that function when attribute value is incorrect and exception must be raised.
+ /// \param [in] pAttrName - attribute name.
+ /// \throw DeadlyImportError.
+ void Throw_IncorrectAttrValue(const std::string& pAttrName);
+
+ /// \fn void Throw_MoreThanOnceDefined(const std::string& pNode, const std::string& pDescription)
+ /// Call that function when some type of nodes are defined twice or more when must be used only once and exception must be raised.
+ /// E.g.:
+ /// <object>
+ /// <color>... <!--- color defined --->
+ /// <color>... <!--- color defined again --->
+ /// </object>
+ /// \throw DeadlyImportError.
+ /// \param [in] pNodeType - type of node which defined one more time.
+ /// \param [in] pDescription - message about error. E.g. what the node defined while exception raised.
+ void Throw_MoreThanOnceDefined(const std::string& pNodeType, const std::string& pDescription);
+
+ /// \fn void Throw_ID_NotFound(const std::string& pID) const
+ /// Call that function when referenced element ID are not found in graph and exception must be raised.
+ /// \param [in] pID - ID of of element which not found.
+ /// \throw DeadlyImportError.
+ void Throw_ID_NotFound(const std::string& pID) const;
+
+ /***********************************************/
+ /************** Functions: LOG set *************/
+ /***********************************************/
+
+ /// \fn void LogInfo(const std::string& pMessage)
+ /// Short variant for calling \ref DefaultLogger::get()->info()
+ void LogInfo(const std::string& pMessage) { DefaultLogger::get()->info(pMessage); }
+
+ /// \fn void LogWarning(const std::string& pMessage)
+ /// Short variant for calling \ref DefaultLogger::get()->warn()
+ void LogWarning(const std::string& pMessage) { DefaultLogger::get()->warn(pMessage); }
+
+ /// \fn void LogError(const std::string& pMessage)
+ /// Short variant for calling \ref DefaultLogger::get()->error()
+ void LogError(const std::string& pMessage) { DefaultLogger::get()->error(pMessage); }
+
+ /***********************************************/
+ /************** Functions: XML set *************/
+ /***********************************************/
+
+ /// \fn void XML_CheckNode_MustHaveChildren()
+ /// Check if current node have children: <node>...</node>. If not then exception will throwed.
+ void XML_CheckNode_MustHaveChildren();
+
+ /// \fn bool XML_CheckNode_NameEqual(const std::string& pNodeName)
+ /// Chek if current node name is equal to pNodeName.
+ /// \param [in] pNodeName - name for checking.
+ /// return true if current node name is equal to pNodeName, else - false.
+ bool XML_CheckNode_NameEqual(const std::string& pNodeName) { return mReader->getNodeName() == pNodeName; }
+
+ /// \fn void XML_CheckNode_SkipUnsupported(const std::string& pParentNodeName)
+ /// Skip unsupported node and report about that. Depend on node name can be skipped begin tag of node all whole node.
+ /// \param [in] pParentNodeName - parent node name. Used for reporting.
+ void XML_CheckNode_SkipUnsupported(const std::string& pParentNodeName);
+
+ /// \fn bool XML_SearchNode(const std::string& pNodeName)
+ /// Search for specified node in file. XML file read pointer(mReader) will point to found node or file end after search is end.
+ /// \param [in] pNodeName - requested node name.
+ /// return true - if node is found, else - false.
+ bool XML_SearchNode(const std::string& pNodeName);
+
+ /// \fn bool XML_ReadNode_GetAttrVal_AsBool(const int pAttrIdx)
+ /// Read attribute value.
+ /// \param [in] pAttrIdx - attribute index (\ref mReader->getAttribute* set).
+ /// \return read data.
+ bool XML_ReadNode_GetAttrVal_AsBool(const int pAttrIdx);
+
+ /// \fn float XML_ReadNode_GetAttrVal_AsFloat(const int pAttrIdx)
+ /// Read attribute value.
+ /// \param [in] pAttrIdx - attribute index (\ref mReader->getAttribute* set).
+ /// \return read data.
+ float XML_ReadNode_GetAttrVal_AsFloat(const int pAttrIdx);
+
+ /// \fn uint32_t XML_ReadNode_GetAttrVal_AsU32(const int pAttrIdx)
+ /// Read attribute value.
+ /// \param [in] pAttrIdx - attribute index (\ref mReader->getAttribute* set).
+ /// \return read data.
+ uint32_t XML_ReadNode_GetAttrVal_AsU32(const int pAttrIdx);
+
+ /// \fn float XML_ReadNode_GetVal_AsFloat()
+ /// Read node value.
+ /// \return read data.
+ float XML_ReadNode_GetVal_AsFloat();
+
+ /// \fn uint32_t XML_ReadNode_GetVal_AsU32()
+ /// Read node value.
+ /// \return read data.
+ uint32_t XML_ReadNode_GetVal_AsU32();
+
+ /// \fn void XML_ReadNode_GetVal_AsString(std::string& pValue)
+ /// Read node value.
+ /// \return read data.
+ void XML_ReadNode_GetVal_AsString(std::string& pValue);
+
+ /***********************************************/
+ /******** Functions: parse set private *********/
+ /***********************************************/
+
+ /// \fn void ParseHelper_Node_Enter(CAMFImporter_NodeElement* pNode)
+ /// Make pNode as current and enter deeper for parsing child nodes. At end \ref ParseHelper_Node_Exit must be called.
+ /// \param [in] pNode - new current node.
+ void ParseHelper_Node_Enter(CAMFImporter_NodeElement* pNode);
+
+ /// \fn void ParseHelper_Group_End()
+ /// This function must be called when exiting from grouping node. \ref ParseHelper_Group_Begin.
+ void ParseHelper_Node_Exit();
+
+ /// \fn void ParseHelper_FixTruncatedFloatString(const char* pInStr, std::string& pOutString)
+ /// Attribute values of floating point types can take form ".x"(without leading zero). irrXMLReader can not read this form of values and it
+ /// must be converted to right form - "0.xxx".
+ /// \param [in] pInStr - pointer to input string which can contain incorrect form of values.
+ /// \param [out[ pOutString - output string with right form of values.
+ void ParseHelper_FixTruncatedFloatString(const char* pInStr, std::string& pOutString);
+
+ /// \fn void ParseHelper_Decode_Base64(const std::string& pInputBase64, std::vector<uint8_t>& pOutputData) const
+ /// Decode Base64-encoded data.
+ /// \param [in] pInputBase64 - reference to input Base64-encoded string.
+ /// \param [out] pOutputData - reference to output array for decoded data.
+ void ParseHelper_Decode_Base64(const std::string& pInputBase64, std::vector<uint8_t>& pOutputData) const;
+
+ /// \fn void ParseNode_Root()
+ /// Parse <AMF> node of the file.
+ void ParseNode_Root();
+
+ /******** Functions: top nodes *********/
+
+ /// \fn void ParseNode_Constellation()
+ /// Parse <constellation> node of the file.
+ void ParseNode_Constellation();
+
+ /// \fn void ParseNode_Constellation()
+ /// Parse <instance> node of the file.
+ void ParseNode_Instance();
+
+ /// \fn void ParseNode_Material()
+ /// Parse <material> node of the file.
+ void ParseNode_Material();
+
+ /// \fn void ParseNode_Metadata()
+ /// Parse <metadata> node.
+ void ParseNode_Metadata();
+
+ /// \fn void ParseNode_Object()
+ /// Parse <object> node of the file.
+ void ParseNode_Object();
+
+ /// \fn void ParseNode_Texture()
+ /// Parse <texture> node of the file.
+ void ParseNode_Texture();
+
+ /******** Functions: geometry nodes *********/
+
+ /// \fn void ParseNode_Coordinates()
+ /// Parse <coordinates> node of the file.
+ void ParseNode_Coordinates();
+
+ /// \fn void ParseNode_Edge()
+ /// Parse <edge> node of the file.
+ void ParseNode_Edge();
+
+ /// \fn void ParseNode_Mesh()
+ /// Parse <mesh> node of the file.
+ void ParseNode_Mesh();
+
+ /// \fn void ParseNode_Triangle()
+ /// Parse <triangle> node of the file.
+ void ParseNode_Triangle();
+
+ /// \fn void ParseNode_Vertex()
+ /// Parse <vertex> node of the file.
+ void ParseNode_Vertex();
+
+ /// \fn void ParseNode_Vertices()
+ /// Parse <vertices> node of the file.
+ void ParseNode_Vertices();
+
+ /// \fn void ParseNode_Volume()
+ /// Parse <volume> node of the file.
+ void ParseNode_Volume();
+
+ /******** Functions: material nodes *********/
+
+ /// \fn void ParseNode_Color()
+ /// Parse <color> node of the file.
+ void ParseNode_Color();
+
+ /// \fn void ParseNode_TexMap(const bool pUseOldName = false)
+ /// Parse <texmap> of <map> node of the file.
+ /// \param [in] pUseOldName - if true then use old name of node(and children) - <map>, instead of new name - <texmap>.
+ void ParseNode_TexMap(const bool pUseOldName = false);
+
+public:
+
+ /// \fn AMFImporter()
+ /// Default constructor.
+ AMFImporter()
+ : mNodeElement_Cur(NULL), mReader(NULL)
+ {}
+
+ /// \fn ~AMFImporter()
+ /// Default destructor.
+ ~AMFImporter();
+
+ /***********************************************/
+ /******** Functions: parse set, public *********/
+ /***********************************************/
+
+ /// \fn void ParseFile(const std::string& pFile, IOSystem* pIOHandler)
+ /// Parse AMF file and fill scene graph. The function has no return value. Result can be found by analyzing the generated graph.
+ /// Also exception can be throwed if trouble will found.
+ /// \param [in] pFile - name of file to be parsed.
+ /// \param [in] pIOHandler - pointer to IO helper object.
+ void ParseFile(const std::string& pFile, IOSystem* pIOHandler);
+
+ /***********************************************/
+ /********* Functions: BaseImporter set *********/
+ /***********************************************/
+
+ bool CanRead(const std::string& pFile, IOSystem* pIOHandler, bool pCheckSig) const;
+ void GetExtensionList(std::set<std::string>& pExtensionList);
+ void InternReadFile(const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler);
+ const aiImporterDesc* GetInfo ()const;
+
+};// class AMFImporter
+
+}// namespace Assimp
+
+#endif // INCLUDED_AI_AMF_IMPORTER_H
--- /dev/null
+/// \file AMFImporter_Geometry.cpp
+/// \brief Parsing data from geometry nodes.
+/// \date 2016
+/// \author smal.root@gmail.com
+
+#ifndef ASSIMP_BUILD_NO_AMF_IMPORTER
+
+#include "AMFImporter.hpp"
+#include "AMFImporter_Macro.hpp"
+
+namespace Assimp
+{
+
+// <mesh>
+// </mesh>
+// A 3D mesh hull.
+// Multi elements - Yes.
+// Parent element - <object>.
+void AMFImporter::ParseNode_Mesh()
+{
+CAMFImporter_NodeElement* ne;
+
+ // create new mesh object.
+ ne = new CAMFImporter_NodeElement_Mesh(mNodeElement_Cur);
+ // Check for child nodes
+ if(!mReader->isEmptyElement())
+ {
+ bool vert_read = false;
+
+ ParseHelper_Node_Enter(ne);
+ MACRO_NODECHECK_LOOPBEGIN("mesh");
+ if(XML_CheckNode_NameEqual("vertices"))
+ {
+ // Check if data already defined.
+ if(vert_read) Throw_MoreThanOnceDefined("vertices", "Only one vertices set can be defined for <mesh>.");
+ // read data and set flag about it
+ ParseNode_Vertices();
+ vert_read = true;
+
+ continue;
+ }
+
+ if(XML_CheckNode_NameEqual("volume")) { ParseNode_Volume(); continue; }
+ MACRO_NODECHECK_LOOPEND("mesh");
+ ParseHelper_Node_Exit();
+ }// if(!mReader->isEmptyElement())
+ else
+ {
+ mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
+ }// if(!mReader->isEmptyElement()) else
+
+ mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph.
+}
+
+// <vertices>
+// </vertices>
+// The list of vertices to be used in defining triangles.
+// Multi elements - No.
+// Parent element - <mesh>.
+void AMFImporter::ParseNode_Vertices()
+{
+CAMFImporter_NodeElement* ne;
+
+ // create new mesh object.
+ ne = new CAMFImporter_NodeElement_Vertices(mNodeElement_Cur);
+ // Check for child nodes
+ if(!mReader->isEmptyElement())
+ {
+ ParseHelper_Node_Enter(ne);
+ MACRO_NODECHECK_LOOPBEGIN("vertices");
+ if(XML_CheckNode_NameEqual("vertex")) { ParseNode_Vertex(); continue; }
+ MACRO_NODECHECK_LOOPEND("vertices");
+ ParseHelper_Node_Exit();
+ }// if(!mReader->isEmptyElement())
+ else
+ {
+ mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
+ }// if(!mReader->isEmptyElement()) else
+
+ mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph.
+}
+
+// <vertex>
+// </vertex>
+// A vertex to be referenced in triangles.
+// Multi elements - Yes.
+// Parent element - <vertices>.
+void AMFImporter::ParseNode_Vertex()
+{
+CAMFImporter_NodeElement* ne;
+
+ // create new mesh object.
+ ne = new CAMFImporter_NodeElement_Vertex(mNodeElement_Cur);
+ // Check for child nodes
+ if(!mReader->isEmptyElement())
+ {
+ bool col_read = false;
+ bool coord_read = false;
+
+ ParseHelper_Node_Enter(ne);
+ MACRO_NODECHECK_LOOPBEGIN("vertex");
+ if(XML_CheckNode_NameEqual("color"))
+ {
+ // Check if data already defined.
+ if(col_read) Throw_MoreThanOnceDefined("color", "Only one color can be defined for <vertex>.");
+ // read data and set flag about it
+ ParseNode_Color();
+ col_read = true;
+
+ continue;
+ }
+
+ if(XML_CheckNode_NameEqual("coordinates"))
+ {
+ // Check if data already defined.
+ if(coord_read) Throw_MoreThanOnceDefined("coordinates", "Only one coordinates set can be defined for <vertex>.");
+ // read data and set flag about it
+ ParseNode_Coordinates();
+ coord_read = true;
+
+ continue;
+ }
+
+ if(XML_CheckNode_NameEqual("metadata")) { ParseNode_Metadata(); continue; }
+ MACRO_NODECHECK_LOOPEND("vertex");
+ ParseHelper_Node_Exit();
+ }// if(!mReader->isEmptyElement())
+ else
+ {
+ mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
+ }// if(!mReader->isEmptyElement()) else
+
+ mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph.
+}
+
+// <coordinates>
+// </coordinates>
+// Specifies the 3D location of this vertex.
+// Multi elements - No.
+// Parent element - <vertex>.
+//
+// Children elements:
+// <x>, <y>, <z>
+// Multi elements - No.
+// X, Y, or Z coordinate, respectively, of a vertex position in space.
+void AMFImporter::ParseNode_Coordinates()
+{
+CAMFImporter_NodeElement* ne;
+
+ // create new color object.
+ ne = new CAMFImporter_NodeElement_Coordinates(mNodeElement_Cur);
+
+ CAMFImporter_NodeElement_Coordinates& als = *((CAMFImporter_NodeElement_Coordinates*)ne);// alias for convenience
+
+ // Check for child nodes
+ if(!mReader->isEmptyElement())
+ {
+ bool read_flag[3] = { false, false, false };
+
+ ParseHelper_Node_Enter(ne);
+ MACRO_NODECHECK_LOOPBEGIN("coordinates");
+ MACRO_NODECHECK_READCOMP_F("x", read_flag[0], als.Coordinate.x);
+ MACRO_NODECHECK_READCOMP_F("y", read_flag[1], als.Coordinate.y);
+ MACRO_NODECHECK_READCOMP_F("z", read_flag[2], als.Coordinate.z);
+ MACRO_NODECHECK_LOOPEND("coordinates");
+ ParseHelper_Node_Exit();
+ // check that all components was defined
+ if((read_flag[0] && read_flag[1] && read_flag[2]) == 0) throw DeadlyImportError("Not all coordinate's components are defined.");
+
+ }// if(!mReader->isEmptyElement())
+ else
+ {
+ mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
+ }// if(!mReader->isEmptyElement()) else
+
+ mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph.
+}
+
+// <volume
+// materialid="" - Which material to use.
+// type="" - What this volume describes can be “region” or “support”. If none specified, “object” is assumed. If support, then the geometric
+// requirements 1-8 listed in section 5 do not need to be maintained.
+// >
+// </volume>
+// Defines a volume from the established vertex list.
+// Multi elements - Yes.
+// Parent element - <mesh>.
+void AMFImporter::ParseNode_Volume()
+{
+std::string materialid;
+std::string type;
+CAMFImporter_NodeElement* ne;
+
+ // Read attributes for node <color>.
+ MACRO_ATTRREAD_LOOPBEG;
+ MACRO_ATTRREAD_CHECK_RET("materialid", materialid, mReader->getAttributeValue);
+ MACRO_ATTRREAD_CHECK_RET("type", type, mReader->getAttributeValue);
+ MACRO_ATTRREAD_LOOPEND;
+
+ // create new object.
+ ne = new CAMFImporter_NodeElement_Volume(mNodeElement_Cur);
+ // and assign read data
+ ((CAMFImporter_NodeElement_Volume*)ne)->MaterialID = materialid;
+ ((CAMFImporter_NodeElement_Volume*)ne)->Type = type;
+ // Check for child nodes
+ if(!mReader->isEmptyElement())
+ {
+ bool col_read = false;
+
+ ParseHelper_Node_Enter(ne);
+ MACRO_NODECHECK_LOOPBEGIN("volume");
+ if(XML_CheckNode_NameEqual("color"))
+ {
+ // Check if data already defined.
+ if(col_read) Throw_MoreThanOnceDefined("color", "Only one color can be defined for <volume>.");
+ // read data and set flag about it
+ ParseNode_Color();
+ col_read = true;
+
+ continue;
+ }
+
+ if(XML_CheckNode_NameEqual("triangle")) { ParseNode_Triangle(); continue; }
+ if(XML_CheckNode_NameEqual("metadata")) { ParseNode_Metadata(); continue; }
+ MACRO_NODECHECK_LOOPEND("volume");
+ ParseHelper_Node_Exit();
+ }// if(!mReader->isEmptyElement())
+ else
+ {
+ mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
+ }// if(!mReader->isEmptyElement()) else
+
+ mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph.
+}
+
+// <triangle>
+// </triangle>
+// Defines a 3D triangle from three vertices, according to the right-hand rule (counter-clockwise when looking from the outside).
+// Multi elements - Yes.
+// Parent element - <volume>.
+//
+// Children elements:
+// <v1>, <v2>, <v3>
+// Multi elements - No.
+// Index of the desired vertices in a triangle or edge.
+void AMFImporter::ParseNode_Triangle()
+{
+CAMFImporter_NodeElement* ne;
+
+ // create new color object.
+ ne = new CAMFImporter_NodeElement_Triangle(mNodeElement_Cur);
+
+ CAMFImporter_NodeElement_Triangle& als = *((CAMFImporter_NodeElement_Triangle*)ne);// alias for convenience
+
+ // Check for child nodes
+ if(!mReader->isEmptyElement())
+ {
+ bool col_read = false, tex_read = false;
+ bool read_flag[3] = { false, false, false };
+
+ ParseHelper_Node_Enter(ne);
+ MACRO_NODECHECK_LOOPBEGIN("triangle");
+ if(XML_CheckNode_NameEqual("color"))
+ {
+ // Check if data already defined.
+ if(col_read) Throw_MoreThanOnceDefined("color", "Only one color can be defined for <triangle>.");
+ // read data and set flag about it
+ ParseNode_Color();
+ col_read = true;
+
+ continue;
+ }
+
+ if(XML_CheckNode_NameEqual("texmap"))// new name of node: "texmap".
+ {
+ // Check if data already defined.
+ if(tex_read) Throw_MoreThanOnceDefined("texmap", "Only one texture coordinate can be defined for <triangle>.");
+ // read data and set flag about it
+ ParseNode_TexMap();
+ tex_read = true;
+
+ continue;
+ }
+ else if(XML_CheckNode_NameEqual("map"))// old name of node: "map".
+ {
+ // Check if data already defined.
+ if(tex_read) Throw_MoreThanOnceDefined("map", "Only one texture coordinate can be defined for <triangle>.");
+ // read data and set flag about it
+ ParseNode_TexMap(true);
+ tex_read = true;
+
+ continue;
+ }
+
+ MACRO_NODECHECK_READCOMP_U32("v1", read_flag[0], als.V[0]);
+ MACRO_NODECHECK_READCOMP_U32("v2", read_flag[1], als.V[1]);
+ MACRO_NODECHECK_READCOMP_U32("v3", read_flag[2], als.V[2]);
+ MACRO_NODECHECK_LOOPEND("triangle");
+ ParseHelper_Node_Exit();
+ // check that all components was defined
+ if((read_flag[0] && read_flag[1] && read_flag[2]) == 0) throw DeadlyImportError("Not all vertices of the triangle are defined.");
+
+ }// if(!mReader->isEmptyElement())
+ else
+ {
+ mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
+ }// if(!mReader->isEmptyElement()) else
+
+ mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph.
+}
+
+}// namespace Assimp
+
+#endif // !ASSIMP_BUILD_NO_AMF_IMPORTER
--- /dev/null
+/// \file AMFImporter_Macro.hpp
+/// \brief Useful macrodefines.
+/// \date 2016
+/// \author smal.root@gmail.com
+
+#ifndef AMFIMPORTER_MACRO_HPP_INCLUDED
+#define AMFIMPORTER_MACRO_HPP_INCLUDED
+
+/// \def MACRO_ATTRREAD_LOOPBEG
+/// Begin of loop that read attributes values.
+#define MACRO_ATTRREAD_LOOPBEG \
+ for(int idx = 0, idx_end = mReader->getAttributeCount(); idx < idx_end; idx++) \
+ { \
+ std::string an(mReader->getAttributeName(idx));
+
+/// \def MACRO_ATTRREAD_LOOPEND
+/// End of loop that read attributes values.
+#define MACRO_ATTRREAD_LOOPEND \
+ Throw_IncorrectAttr(an); \
+ }
+
+/// \def MACRO_ATTRREAD_LOOPEND_WSKIP
+/// End of loop that read attributes values. Difference from \ref MACRO_ATTRREAD_LOOPEND in that: current macro skip unknown attributes, but
+/// \ref MACRO_ATTRREAD_LOOPEND throw an exception.
+#define MACRO_ATTRREAD_LOOPEND_WSKIP \
+ continue; \
+ }
+
+/// \def MACRO_ATTRREAD_CHECK_REF
+/// Check curent attribute name and if it equal to requested then read value. Result write to output variable by reference. If result was read then
+/// "continue" will called.
+/// \param [in] pAttrName - attribute name.
+/// \param [out] pVarName - output variable name.
+/// \param [in] pFunction - function which read attribute value and write it to pVarName.
+#define MACRO_ATTRREAD_CHECK_REF(pAttrName, pVarName, pFunction) \
+ if(an == pAttrName) \
+ { \
+ pFunction(idx, pVarName); \
+ continue; \
+ }
+
+/// \def MACRO_ATTRREAD_CHECK_RET
+/// Check curent attribute name and if it equal to requested then read value. Result write to output variable using return value of \ref pFunction.
+/// If result was read then "continue" will called.
+/// \param [in] pAttrName - attribute name.
+/// \param [out] pVarName - output variable name.
+/// \param [in] pFunction - function which read attribute value and write it to pVarName.
+#define MACRO_ATTRREAD_CHECK_RET(pAttrName, pVarName, pFunction) \
+ if(an == pAttrName) \
+ { \
+ pVarName = pFunction(idx); \
+ continue; \
+ }
+
+/// \def MACRO_NODECHECK_LOOPBEGIN(pNodeName)
+/// Begin of loop of parsing child nodes. Do not add ';' at end.
+/// \param [in] pNodeName - current node name.
+#define MACRO_NODECHECK_LOOPBEGIN(pNodeName) \
+ do { \
+ bool close_found = false; \
+ \
+ while(mReader->read()) \
+ { \
+ if(mReader->getNodeType() == irr::io::EXN_ELEMENT) \
+ {
+
+/// \def MACRO_NODECHECK_LOOPEND(pNodeName)
+/// End of loop of parsing child nodes.
+/// \param [in] pNodeName - current node name.
+#define MACRO_NODECHECK_LOOPEND(pNodeName) \
+ XML_CheckNode_SkipUnsupported(pNodeName); \
+ }/* if(mReader->getNodeType() == irr::io::EXN_ELEMENT) */ \
+ else if(mReader->getNodeType() == irr::io::EXN_ELEMENT_END) \
+ { \
+ if(XML_CheckNode_NameEqual(pNodeName)) \
+ { \
+ close_found = true; \
+ \
+ break; \
+ } \
+ }/* else if(mReader->getNodeType() == irr::io::EXN_ELEMENT_END) */ \
+ }/* while(mReader->read()) */ \
+ \
+ if(!close_found) Throw_CloseNotFound(pNodeName); \
+ \
+ } while(false)
+
+/// \def MACRO_NODECHECK_READCOMP_F
+/// Check curent node name and if it equal to requested then read value. Result write to output variable of type "float".
+/// If result was read then "continue" will called. Also check if node data already read then raise exception.
+/// \param [in] pNodeName - node name.
+/// \param [in, out] pReadFlag - read flag.
+/// \param [out] pVarName - output variable name.
+#define MACRO_NODECHECK_READCOMP_F(pNodeName, pReadFlag, pVarName) \
+ if(XML_CheckNode_NameEqual(pNodeName)) \
+ { \
+ /* Check if field already read before. */ \
+ if(pReadFlag) Throw_MoreThanOnceDefined(pNodeName, "Only one component can be defined."); \
+ /* Read color component and assign it to object. */ \
+ pVarName = XML_ReadNode_GetVal_AsFloat(); \
+ pReadFlag = true; \
+ continue; \
+ }
+
+/// \def MACRO_NODECHECK_READCOMP_U32
+/// Check curent node name and if it equal to requested then read value. Result write to output variable of type "uint32_t".
+/// If result was read then "continue" will called. Also check if node data already read then raise exception.
+/// \param [in] pNodeName - node name.
+/// \param [in, out] pReadFlag - read flag.
+/// \param [out] pVarName - output variable name.
+#define MACRO_NODECHECK_READCOMP_U32(pNodeName, pReadFlag, pVarName) \
+ if(XML_CheckNode_NameEqual(pNodeName)) \
+ { \
+ /* Check if field already read before. */ \
+ if(pReadFlag) Throw_MoreThanOnceDefined(pNodeName, "Only one component can be defined."); \
+ /* Read color component and assign it to object. */ \
+ pVarName = XML_ReadNode_GetVal_AsU32(); \
+ pReadFlag = true; \
+ continue; \
+ }
+
+#endif // AMFIMPORTER_MACRO_HPP_INCLUDED
--- /dev/null
+/// \file AMFImporter_Material.cpp
+/// \brief Parsing data from material nodes.
+/// \date 2016
+/// \author smal.root@gmail.com
+
+#ifndef ASSIMP_BUILD_NO_AMF_IMPORTER
+
+#include "AMFImporter.hpp"
+#include "AMFImporter_Macro.hpp"
+
+namespace Assimp
+{
+
+// <color
+// profile="" - The ICC color space used to interpret the three color channels <r>, <g> and <b>.
+// >
+// </color>
+// A color definition.
+// Multi elements - No.
+// Parent element - <material>, <object>, <volume>, <vertex>, <triangle>.
+//
+// "profile" can be one of "sRGB", "AdobeRGB", "Wide-Gamut-RGB", "CIERGB", "CIELAB", or "CIEXYZ".
+// Children elements:
+// <r>, <g>, <b>, <a>
+// Multi elements - No.
+// Red, Greed, Blue and Alpha (transparency) component of a color in sRGB space, values ranging from 0 to 1. The
+// values can be specified as constants, or as a formula depending on the coordinates.
+void AMFImporter::ParseNode_Color()
+{
+std::string profile;
+CAMFImporter_NodeElement* ne;
+
+ // Read attributes for node <color>.
+ MACRO_ATTRREAD_LOOPBEG;
+ MACRO_ATTRREAD_CHECK_RET("profile", profile, mReader->getAttributeValue);
+ MACRO_ATTRREAD_LOOPEND;
+
+ // create new color object.
+ ne = new CAMFImporter_NodeElement_Color(mNodeElement_Cur);
+
+ CAMFImporter_NodeElement_Color& als = *((CAMFImporter_NodeElement_Color*)ne);// alias for convenience
+
+ als.Profile = profile;
+ // Check for child nodes
+ if(!mReader->isEmptyElement())
+ {
+ bool read_flag[4] = { false, false, false, false };
+
+ ParseHelper_Node_Enter(ne);
+ MACRO_NODECHECK_LOOPBEGIN("color");
+ MACRO_NODECHECK_READCOMP_F("r", read_flag[0], als.Color.r);
+ MACRO_NODECHECK_READCOMP_F("g", read_flag[1], als.Color.g);
+ MACRO_NODECHECK_READCOMP_F("b", read_flag[2], als.Color.b);
+ MACRO_NODECHECK_READCOMP_F("a", read_flag[3], als.Color.a);
+ MACRO_NODECHECK_LOOPEND("color");
+ ParseHelper_Node_Exit();
+ // check that all components was defined
+ if(!(read_flag[0] && read_flag[1] && read_flag[2])) throw DeadlyImportError("Not all color components are defined.");
+ // check if <a> is absent. Then manualy add "a == 1".
+ if(!read_flag[3]) als.Color.a = 1;
+
+ }// if(!mReader->isEmptyElement())
+ else
+ {
+ mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
+ }// if(!mReader->isEmptyElement()) else
+
+ als.Composed = false;
+ mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph.
+}
+
+// <material
+// id="" - A unique material id. material ID "0" is reserved to denote no material (void) or sacrificial material.
+// >
+// </material>
+// An available material.
+// Multi elements - Yes.
+// Parent element - <amf>.
+void AMFImporter::ParseNode_Material()
+{
+std::string id;
+CAMFImporter_NodeElement* ne;
+
+ // Read attributes for node <color>.
+ MACRO_ATTRREAD_LOOPBEG;
+ MACRO_ATTRREAD_CHECK_RET("id", id, mReader->getAttributeValue);
+ MACRO_ATTRREAD_LOOPEND;
+
+ // create new object.
+ ne = new CAMFImporter_NodeElement_Material(mNodeElement_Cur);
+ // and assign read data
+ ((CAMFImporter_NodeElement_Material*)ne)->ID = id;
+ // Check for child nodes
+ if(!mReader->isEmptyElement())
+ {
+ bool col_read = false;
+
+ ParseHelper_Node_Enter(ne);
+ MACRO_NODECHECK_LOOPBEGIN("material");
+ if(XML_CheckNode_NameEqual("color"))
+ {
+ // Check if data already defined.
+ if(col_read) Throw_MoreThanOnceDefined("color", "Only one color can be defined for <material>.");
+ // read data and set flag about it
+ ParseNode_Color();
+ col_read = true;
+
+ continue;
+ }
+
+ if(XML_CheckNode_NameEqual("metadata")) { ParseNode_Metadata(); continue; }
+ MACRO_NODECHECK_LOOPEND("material");
+ ParseHelper_Node_Exit();
+ }// if(!mReader->isEmptyElement())
+ else
+ {
+ mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
+ }// if(!mReader->isEmptyElement()) else
+
+ mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph.
+}
+
+// <texture
+// id="" - Assigns a unique texture id for the new texture.
+// width="" - Width (horizontal size, x) of the texture, in pixels.
+// height="" - Height (lateral size, y) of the texture, in pixels.
+// depth="" - Depth (vertical size, z) of the texture, in pixels.
+// type="" - Encoding of the data in the texture. Currently allowed values are "grayscale" only. In grayscale mode, each pixel is represented by one byte
+// in the range of 0-255. When the texture is referenced using the tex function, these values are converted into a single floating point number in the
+// range of 0-1 (see Annex 2). A full color graphics will typically require three textures, one for each of the color channels. A graphic involving
+// transparency may require a fourth channel.
+// tiled="" - If true then texture repeated when UV-coordinates is greater than 1.
+// >
+// </triangle>
+// Specifies an texture data to be used as a map. Lists a sequence of Base64 values specifying values for pixels from left to right then top to bottom,
+// then layer by layer.
+// Multi elements - Yes.
+// Parent element - <amf>.
+void AMFImporter::ParseNode_Texture()
+{
+std::string id;
+uint32_t width = 0;
+uint32_t height = 0;
+uint32_t depth = 1;
+std::string type;
+bool tiled = false;
+std::string enc64_data;
+CAMFImporter_NodeElement* ne;
+
+ // Read attributes for node <color>.
+ MACRO_ATTRREAD_LOOPBEG;
+ MACRO_ATTRREAD_CHECK_RET("id", id, mReader->getAttributeValue);
+ MACRO_ATTRREAD_CHECK_RET("width", width, XML_ReadNode_GetAttrVal_AsU32);
+ MACRO_ATTRREAD_CHECK_RET("height", height, XML_ReadNode_GetAttrVal_AsU32);
+ MACRO_ATTRREAD_CHECK_RET("depth", depth, XML_ReadNode_GetAttrVal_AsU32);
+ MACRO_ATTRREAD_CHECK_RET("type", type, mReader->getAttributeValue);
+ MACRO_ATTRREAD_CHECK_RET("tiled", tiled, XML_ReadNode_GetAttrVal_AsBool);
+ MACRO_ATTRREAD_LOOPEND;
+
+ // create new texture object.
+ ne = new CAMFImporter_NodeElement_Texture(mNodeElement_Cur);
+
+ CAMFImporter_NodeElement_Texture& als = *((CAMFImporter_NodeElement_Texture*)ne);// alias for convenience
+
+ // Check for child nodes
+ if(!mReader->isEmptyElement()) XML_ReadNode_GetVal_AsString(enc64_data);
+
+ // check that all components was defined
+ if(id.empty()) throw DeadlyImportError("ID for texture must be defined.");
+ if(width < 1) Throw_IncorrectAttrValue("width");
+ if(height < 1) Throw_IncorrectAttrValue("height");
+ if(depth < 1) Throw_IncorrectAttrValue("depth");
+ if(type != "grayscale") Throw_IncorrectAttrValue("type");
+ if(enc64_data.empty()) throw DeadlyImportError("Texture data not defined.");
+ // copy data
+ als.ID = id;
+ als.Width = width;
+ als.Height = height;
+ als.Depth = depth;
+ als.Tiled = tiled;
+ ParseHelper_Decode_Base64(enc64_data, als.Data);
+ // check data size
+ if((width * height * depth) != als.Data.size()) throw DeadlyImportError("Texture has incorrect data size.");
+
+ mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
+ mNodeElement_List.push_back(ne);// and to node element list because its a new object in graph.
+}
+
+// <texmap
+// rtexid="" - Texture ID for red color component.
+// gtexid="" - Texture ID for green color component.
+// btexid="" - Texture ID for blue color component.
+// atexid="" - Texture ID for alpha color component. Optional.
+// >
+// </texmap>, old name: <map>
+// Specifies texture coordinates for triangle.
+// Multi elements - No.
+// Parent element - <triangle>.
+// Children elements:
+// <utex1>, <utex2>, <utex3>, <vtex1>, <vtex2>, <vtex3>. Old name: <u1>, <u2>, <u3>, <v1>, <v2>, <v3>.
+// Multi elements - No.
+// Texture coordinates for every vertex of triangle.
+void AMFImporter::ParseNode_TexMap(const bool pUseOldName)
+{
+std::string rtexid, gtexid, btexid, atexid;
+CAMFImporter_NodeElement* ne;
+
+ // Read attributes for node <color>.
+ MACRO_ATTRREAD_LOOPBEG;
+ MACRO_ATTRREAD_CHECK_RET("rtexid", rtexid, mReader->getAttributeValue);
+ MACRO_ATTRREAD_CHECK_RET("gtexid", gtexid, mReader->getAttributeValue);
+ MACRO_ATTRREAD_CHECK_RET("btexid", btexid, mReader->getAttributeValue);
+ MACRO_ATTRREAD_CHECK_RET("atexid", atexid, mReader->getAttributeValue);
+ MACRO_ATTRREAD_LOOPEND;
+
+ // create new texture coordinates object.
+ ne = new CAMFImporter_NodeElement_TexMap(mNodeElement_Cur);
+
+ CAMFImporter_NodeElement_TexMap& als = *((CAMFImporter_NodeElement_TexMap*)ne);// alias for convenience
+ // check data
+ if(rtexid.empty() && gtexid.empty() && btexid.empty()) throw DeadlyImportError("ParseNode_TexMap. At least one texture ID must be defined.");
+ // Check for children nodes
+ XML_CheckNode_MustHaveChildren();
+ // read children nodes
+ bool read_flag[6] = { false, false, false, false, false, false };
+
+ ParseHelper_Node_Enter(ne);
+ if(!pUseOldName)
+ {
+ MACRO_NODECHECK_LOOPBEGIN("texmap");
+ MACRO_NODECHECK_READCOMP_F("utex1", read_flag[0], als.TextureCoordinate[0].x);
+ MACRO_NODECHECK_READCOMP_F("utex2", read_flag[1], als.TextureCoordinate[1].x);
+ MACRO_NODECHECK_READCOMP_F("utex3", read_flag[2], als.TextureCoordinate[2].x);
+ MACRO_NODECHECK_READCOMP_F("vtex1", read_flag[3], als.TextureCoordinate[0].y);
+ MACRO_NODECHECK_READCOMP_F("vtex2", read_flag[4], als.TextureCoordinate[1].y);
+ MACRO_NODECHECK_READCOMP_F("vtex3", read_flag[5], als.TextureCoordinate[2].y);
+ MACRO_NODECHECK_LOOPEND("texmap");
+ }
+ else
+ {
+ MACRO_NODECHECK_LOOPBEGIN("map");
+ MACRO_NODECHECK_READCOMP_F("u1", read_flag[0], als.TextureCoordinate[0].x);
+ MACRO_NODECHECK_READCOMP_F("u2", read_flag[1], als.TextureCoordinate[1].x);
+ MACRO_NODECHECK_READCOMP_F("u3", read_flag[2], als.TextureCoordinate[2].x);
+ MACRO_NODECHECK_READCOMP_F("v1", read_flag[3], als.TextureCoordinate[0].y);
+ MACRO_NODECHECK_READCOMP_F("v2", read_flag[4], als.TextureCoordinate[1].y);
+ MACRO_NODECHECK_READCOMP_F("v3", read_flag[5], als.TextureCoordinate[2].y);
+ MACRO_NODECHECK_LOOPEND("map");
+ }// if(!pUseOldName) else
+
+ ParseHelper_Node_Exit();
+
+ // check that all components was defined
+ if(!(read_flag[0] && read_flag[1] && read_flag[2] && read_flag[3] && read_flag[4] && read_flag[5]))
+ throw DeadlyImportError("Not all texture coordinates are defined.");
+
+ // copy attributes data
+ als.TextureID_R = rtexid;
+ als.TextureID_G = gtexid;
+ als.TextureID_B = btexid;
+ als.TextureID_A = atexid;
+
+ mNodeElement_List.push_back(ne);// add to node element list because its a new object in graph.
+}
+
+}// namespace Assimp
+
+#endif // !ASSIMP_BUILD_NO_AMF_IMPORTER
--- /dev/null
+/// \file AMFImporter_Node.hpp
+/// \brief Elements of scene graph.
+/// \date 2016
+/// \author smal.root@gmail.com
+
+#ifndef INCLUDED_AI_AMF_IMPORTER_NODE_H
+#define INCLUDED_AI_AMF_IMPORTER_NODE_H
+
+// Header files, stdlib.
+#include <list>
+#include <string>
+
+// Header files, Assimp.
+#include "assimp/types.h"
+#include "assimp/scene.h"
+
+/// \class CAMFImporter_NodeElement
+/// Base class for elements of nodes.
+class CAMFImporter_NodeElement
+{
+ /***********************************************/
+ /******************** Types ********************/
+ /***********************************************/
+
+public:
+
+ /// \enum EType
+ /// Define what data type contain node element.
+ enum EType
+ {
+ ENET_Color, ///< Color element: <color>.
+ ENET_Constellation,///< Grouping element: <constellation>.
+ ENET_Coordinates, ///< Coordinates element: <coordinates>.
+ ENET_Edge, ///< Edge element: <edge>.
+ ENET_Instance, ///< Grouping element: <constellation>.
+ ENET_Material, ///< Material element: <material>.
+ ENET_Metadata, ///< Metadata element: <metadata>.
+ ENET_Mesh, ///< Metadata element: <mesh>.
+ ENET_Object, ///< Element which hold object: <object>.
+ ENET_Root, ///< Root element: <amf>.
+ ENET_Triangle, ///< Triangle element: <triangle>.
+ ENET_TexMap, ///< Texture coordinates element: <texmap> or <map>.
+ ENET_Texture, ///< Texture element: <texture>.
+ ENET_Vertex, ///< Vertex element: <vertex>.
+ ENET_Vertices, ///< Vertex element: <vertices>.
+ ENET_Volume, ///< Volume element: <volume>.
+
+ ENET_Invalid ///< Element has invalid type and possible contain invalid data.
+ };
+
+ /***********************************************/
+ /****************** Constants ******************/
+ /***********************************************/
+
+public:
+
+ const EType Type;///< Type of element.
+
+ /***********************************************/
+ /****************** Variables ******************/
+ /***********************************************/
+
+public:
+
+ std::string ID;///< ID of element.
+ CAMFImporter_NodeElement* Parent;///< Parrent element. If NULL then this node is root.
+ std::list<CAMFImporter_NodeElement*> Child;///< Child elements.
+
+ /***********************************************/
+ /****************** Functions ******************/
+ /***********************************************/
+
+private:
+
+ /// \fn CAMFImporter_NodeElement(const CAMFImporter_NodeElement& pNodeElement)
+ /// Disabled copy constructor.
+ CAMFImporter_NodeElement(const CAMFImporter_NodeElement& pNodeElement);
+
+ /// \fn CAMFImporter_NodeElement& operator=(const CAMFImporter_NodeElement& pNodeElement)
+ /// Disabled assign operator.
+ CAMFImporter_NodeElement& operator=(const CAMFImporter_NodeElement& pNodeElement);
+
+ /// \fn CAMFImporter_NodeElement()
+ /// Disabled default constructor.
+ CAMFImporter_NodeElement();
+
+protected:
+
+ /// \fn CAMFImporter_NodeElement(const EType pType, CAMFImporter_NodeElement* pParent)
+ /// In constructor inheritor must set element type.
+ /// \param [in] pType - element type.
+ /// \param [in] pParent - parent element.
+ CAMFImporter_NodeElement(const EType pType, CAMFImporter_NodeElement* pParent)
+ : Type(pType), Parent(pParent)
+ {}
+
+};// class IAMFImporter_NodeElement
+
+/// \struct CAMFImporter_NodeElement_Constellation
+/// A collection of objects or constellations with specific relative locations.
+struct CAMFImporter_NodeElement_Constellation : public CAMFImporter_NodeElement
+{
+ /// \fn CAMFImporter_NodeElement_Constellation(CAMFImporter_NodeElement* pParent)
+ /// Constructor.
+ /// \param [in] pParent - pointer to parent node.
+ CAMFImporter_NodeElement_Constellation(CAMFImporter_NodeElement* pParent)
+ : CAMFImporter_NodeElement(ENET_Constellation, pParent)
+ {}
+
+};// struct CAMFImporter_NodeElement_Constellation
+
+/// \struct CAMFImporter_NodeElement_Instance
+/// Part of constellation.
+struct CAMFImporter_NodeElement_Instance : public CAMFImporter_NodeElement
+{
+ /****************** Variables ******************/
+
+ std::string ObjectID;///< ID of object for instanciation.
+ /// \var Delta - The distance of translation in the x, y, or z direction, respectively, in the referenced object's coordinate system, to
+ /// create an instance of the object in the current constellation.
+ aiVector3D Delta;
+
+ /// \var Rotation - The rotation, in degrees, to rotate the referenced object about its x, y, and z axes, respectively, to create an
+ /// instance of the object in the current constellation. Rotations shall be executed in order of x first, then y, then z.
+ aiVector3D Rotation;
+
+ /****************** Functions ******************/
+
+ /// \fn CAMFImporter_NodeElement_Instance(CAMFImporter_NodeElement* pParent)
+ /// Constructor.
+ /// \param [in] pParent - pointer to parent node.
+ CAMFImporter_NodeElement_Instance(CAMFImporter_NodeElement* pParent)
+ : CAMFImporter_NodeElement(ENET_Instance, pParent)
+ {}
+
+};// struct CAMFImporter_NodeElement_Instance
+
+/// \struct CAMFImporter_NodeElement_Metadata
+/// Structure that define metadata node.
+struct CAMFImporter_NodeElement_Metadata : public CAMFImporter_NodeElement
+{
+ /****************** Variables ******************/
+
+ std::string Type;///< Type of "Value".
+ std::string Value;///< Value.
+
+ /****************** Functions ******************/
+
+ /// \fn CAMFImporter_NodeElement_Metadata(CAMFImporter_NodeElement* pParent)
+ /// Constructor.
+ /// \param [in] pParent - pointer to parent node.
+ CAMFImporter_NodeElement_Metadata(CAMFImporter_NodeElement* pParent)
+ : CAMFImporter_NodeElement(ENET_Metadata, pParent)
+ {}
+
+};// struct CAMFImporter_NodeElement_Metadata
+
+/// \struct CAMFImporter_NodeElement_Root
+/// Structure that define root node.
+struct CAMFImporter_NodeElement_Root : public CAMFImporter_NodeElement
+{
+ /****************** Variables ******************/
+
+ std::string Unit;///< The units to be used. May be "inch", "millimeter", "meter", "feet", or "micron".
+ std::string Version;///< Version of format.
+
+ /****************** Functions ******************/
+
+ /// \fn CAMFImporter_NodeElement_Root(CAMFImporter_NodeElement* pParent)
+ /// Constructor.
+ /// \param [in] pParent - pointer to parent node.
+ CAMFImporter_NodeElement_Root(CAMFImporter_NodeElement* pParent)
+ : CAMFImporter_NodeElement(ENET_Root, pParent)
+ {}
+
+};// struct CAMFImporter_NodeElement_Root
+
+/// \struct CAMFImporter_NodeElement_Color
+/// Structure that define object node.
+struct CAMFImporter_NodeElement_Color : public CAMFImporter_NodeElement
+{
+ /****************** Variables ******************/
+
+ bool Composed;///< Type of color stored: if true then look for formula in \ref Color_Composed[4], else - in \ref Color.
+ std::string Color_Composed[4];///< By components formulas of composed color. [0..3] => RGBA.
+ aiColor4D Color;///< Constant color.
+ std::string Profile;///< The ICC color space used to interpret the three color channels <r>, <g> and <b>..
+
+ /****************** Functions ******************/
+
+ /// \fn CAMFImporter_NodeElement_Color(CAMFImporter_NodeElement* pParent)
+ /// Constructor.
+ /// \param [in] pParent - pointer to parent node.
+ CAMFImporter_NodeElement_Color(CAMFImporter_NodeElement* pParent)
+ : CAMFImporter_NodeElement(ENET_Color, pParent)
+ {}
+
+};// struct CAMFImporter_NodeElement_Color
+
+/// \struct CAMFImporter_NodeElement_Material
+/// Structure that define material node.
+struct CAMFImporter_NodeElement_Material : public CAMFImporter_NodeElement
+{
+ /// \fn CAMFImporter_NodeElement_Material(CAMFImporter_NodeElement* pParent)
+ /// Constructor.
+ /// \param [in] pParent - pointer to parent node.
+ CAMFImporter_NodeElement_Material(CAMFImporter_NodeElement* pParent)
+ : CAMFImporter_NodeElement(ENET_Material, pParent)
+ {}
+
+};// struct CAMFImporter_NodeElement_Material
+
+/// \struct CAMFImporter_NodeElement_Object
+/// Structure that define object node.
+struct CAMFImporter_NodeElement_Object : public CAMFImporter_NodeElement
+{
+ /// \fn CAMFImporter_NodeElement_Object(CAMFImporter_NodeElement* pParent)
+ /// Constructor.
+ /// \param [in] pParent - pointer to parent node.
+ CAMFImporter_NodeElement_Object(CAMFImporter_NodeElement* pParent)
+ : CAMFImporter_NodeElement(ENET_Object, pParent)
+ {}
+
+};// struct CAMFImporter_NodeElement_Object
+
+/// \struct CAMFImporter_NodeElement_Mesh
+/// Structure that define mesh node.
+struct CAMFImporter_NodeElement_Mesh : public CAMFImporter_NodeElement
+{
+ /// \fn CAMFImporter_NodeElement_Mesh(CAMFImporter_NodeElement* pParent)
+ /// Constructor.
+ /// \param [in] pParent - pointer to parent node.
+ CAMFImporter_NodeElement_Mesh(CAMFImporter_NodeElement* pParent)
+ : CAMFImporter_NodeElement(ENET_Mesh, pParent)
+ {}
+
+};// struct CAMFImporter_NodeElement_Mesh
+
+/// \struct CAMFImporter_NodeElement_Vertex
+/// Structure that define vertex node.
+struct CAMFImporter_NodeElement_Vertex : public CAMFImporter_NodeElement
+{
+ /// \fn CAMFImporter_NodeElement_Vertex(CAMFImporter_NodeElement* pParent)
+ /// Constructor.
+ /// \param [in] pParent - pointer to parent node.
+ CAMFImporter_NodeElement_Vertex(CAMFImporter_NodeElement* pParent)
+ : CAMFImporter_NodeElement(ENET_Vertex, pParent)
+ {}
+
+};// struct CAMFImporter_NodeElement_Vertex
+
+/// \struct CAMFImporter_NodeElement_Edge
+/// Structure that define edge node.
+struct CAMFImporter_NodeElement_Edge : public CAMFImporter_NodeElement
+{
+ /// \fn CAMFImporter_NodeElement_Edge(CAMFImporter_NodeElement* pParent)
+ /// Constructor.
+ /// \param [in] pParent - pointer to parent node.
+ CAMFImporter_NodeElement_Edge(CAMFImporter_NodeElement* pParent)
+ : CAMFImporter_NodeElement(ENET_Edge, pParent)
+ {}
+
+};// struct CAMFImporter_NodeElement_Vertex
+
+/// \struct CAMFImporter_NodeElement_Vertices
+/// Structure that define vertices node.
+struct CAMFImporter_NodeElement_Vertices : public CAMFImporter_NodeElement
+{
+ /// \fn CAMFImporter_NodeElement_Vertices(CAMFImporter_NodeElement* pParent)
+ /// Constructor.
+ /// \param [in] pParent - pointer to parent node.
+ CAMFImporter_NodeElement_Vertices(CAMFImporter_NodeElement* pParent)
+ : CAMFImporter_NodeElement(ENET_Vertices, pParent)
+ {}
+
+};// struct CAMFImporter_NodeElement_Vertices
+
+/// \struct CAMFImporter_NodeElement_Volume
+/// Structure that define volume node.
+struct CAMFImporter_NodeElement_Volume : public CAMFImporter_NodeElement
+{
+ /****************** Variables ******************/
+
+ std::string MaterialID;///< Which material to use.
+ std::string Type;///< What this volume describes can be “region” or “support”. If none specified, “object” is assumed.
+
+ /****************** Functions ******************/
+
+ /// \fn CAMFImporter_NodeElement_Volume(CAMFImporter_NodeElement* pParent)
+ /// Constructor.
+ /// \param [in] pParent - pointer to parent node.
+ CAMFImporter_NodeElement_Volume(CAMFImporter_NodeElement* pParent)
+ : CAMFImporter_NodeElement(ENET_Volume, pParent)
+ {}
+
+};// struct CAMFImporter_NodeElement_Volume
+
+/// \struct CAMFImporter_NodeElement_Coordinates
+/// Structure that define coordinates node.
+struct CAMFImporter_NodeElement_Coordinates : public CAMFImporter_NodeElement
+{
+ /****************** Variables ******************/
+
+ aiVector3D Coordinate;///< Coordinate.
+
+ /****************** Functions ******************/
+
+ /// \fn CAMFImporter_NodeElement_Coordinates(CAMFImporter_NodeElement* pParent)
+ /// Constructor.
+ /// \param [in] pParent - pointer to parent node.
+ CAMFImporter_NodeElement_Coordinates(CAMFImporter_NodeElement* pParent)
+ : CAMFImporter_NodeElement(ENET_Coordinates, pParent)
+ {}
+
+};// struct CAMFImporter_NodeElement_Coordinates
+
+/// \struct CAMFImporter_NodeElement_TexMap
+/// Structure that define texture coordinates node.
+struct CAMFImporter_NodeElement_TexMap : public CAMFImporter_NodeElement
+{
+ /****************** Variables ******************/
+
+ aiVector3D TextureCoordinate[3];///< Texture coordinates.
+ std::string TextureID_R;///< Texture ID for red color component.
+ std::string TextureID_G;///< Texture ID for green color component.
+ std::string TextureID_B;///< Texture ID for blue color component.
+ std::string TextureID_A;///< Texture ID for alpha color component.
+
+ /****************** Functions ******************/
+
+ /// \fn CAMFImporter_NodeElement_TexMap(CAMFImporter_NodeElement* pParent)
+ /// Constructor.
+ /// \param [in] pParent - pointer to parent node.
+ CAMFImporter_NodeElement_TexMap(CAMFImporter_NodeElement* pParent)
+ : CAMFImporter_NodeElement(ENET_TexMap, pParent)
+ {}
+
+};// struct CAMFImporter_NodeElement_TexMap
+
+/// \struct CAMFImporter_NodeElement_Triangle
+/// Structure that define triangle node.
+struct CAMFImporter_NodeElement_Triangle : public CAMFImporter_NodeElement
+{
+ /****************** Variables ******************/
+
+ size_t V[3];///< Triangle vertices.
+
+ /****************** Functions ******************/
+
+ /// \fn CAMFImporter_NodeElement_Triangle(CAMFImporter_NodeElement* pParent)
+ /// Constructor.
+ /// \param [in] pParent - pointer to parent node.
+ CAMFImporter_NodeElement_Triangle(CAMFImporter_NodeElement* pParent)
+ : CAMFImporter_NodeElement(ENET_Triangle, pParent)
+ {}
+
+};// struct CAMFImporter_NodeElement_Triangle
+
+/// \struct CAMFImporter_NodeElement_Texture
+/// Structure that define texture node.
+struct CAMFImporter_NodeElement_Texture : public CAMFImporter_NodeElement
+{
+ /****************** Variables ******************/
+
+ size_t Width, Height, Depth;///< Size of the texture.
+ std::vector<uint8_t> Data;///< Data of the texture.
+ bool Tiled;
+
+ /****************** Functions ******************/
+
+ /// \fn CAMFImporter_NodeElement_Texture(CAMFImporter_NodeElement* pParent)
+ /// Constructor.
+ /// \param [in] pParent - pointer to parent node.
+ CAMFImporter_NodeElement_Texture(CAMFImporter_NodeElement* pParent)
+ : CAMFImporter_NodeElement(ENET_Texture, pParent)
+ {}
+
+};// struct CAMFImporter_NodeElement_Texture
+
+#endif // INCLUDED_AI_AMF_IMPORTER_NODE_H
--- /dev/null
+/// \file AMFImporter_Postprocess.cpp
+/// \brief Convert built scenegraph and objects to Assimp scenegraph.
+/// \date 2016
+/// \author smal.root@gmail.com
+
+#ifndef ASSIMP_BUILD_NO_AMF_IMPORTER
+
+#include "AMFImporter.hpp"
+
+// Header files, Assimp.
+#include "SceneCombiner.h"
+#include "StandardShapes.h"
+
+// Header files, stdlib.
+#include <algorithm>
+#include <iterator>
+
+namespace Assimp
+{
+
+aiColor4D AMFImporter::SPP_Material::GetColor(const float pX, const float pY, const float pZ) const
+{
+aiColor4D tcol;
+
+ // Check if stored data are supported.
+ if(Composition.size() != 0)
+ {
+ throw DeadlyImportError("IME. GetColor for composition");
+ }
+ else if(Color->Composed)
+ {
+ throw DeadlyImportError("IME. GetColor, composed color");
+ }
+ else
+ {
+ tcol = Color->Color;
+ }
+
+ // Check if default color must be used
+ if((tcol.r == 0) && (tcol.g == 0) && (tcol.b == 0) && (tcol.a == 0))
+ {
+ tcol.r = 0.5f;
+ tcol.g = 0.5f;
+ tcol.b = 0.5f;
+ tcol.a = 1;
+ }
+
+ return tcol;
+}
+
+void AMFImporter::PostprocessHelper_CreateMeshDataArray(const CAMFImporter_NodeElement_Mesh& pNodeElement, std::vector<aiVector3D>& pVertexCoordinateArray,
+ std::vector<CAMFImporter_NodeElement_Color*>& pVertexColorArray) const
+{
+CAMFImporter_NodeElement_Vertices* vn = NULL;
+size_t col_idx;
+
+ // All data stored in "vertices", search for it.
+ for(std::list<CAMFImporter_NodeElement*>::const_iterator it = pNodeElement.Child.begin(); it != pNodeElement.Child.end(); it++)
+ {
+ if((*it)->Type == CAMFImporter_NodeElement::ENET_Vertices) vn = (CAMFImporter_NodeElement_Vertices*)(*it);
+ }
+ // If "vertices" not found then no work for us.
+ if(vn == NULL) return;
+
+ pVertexCoordinateArray.reserve(vn->Child.size());// all coordinates stored as child and we need to reserve space for future push_back's.
+ pVertexColorArray.resize(vn->Child.size());// colors count equal vertices count.
+ col_idx = 0;
+ // Inside vertices collect all data and place to arrays
+ for(std::list<CAMFImporter_NodeElement*>::const_iterator it = vn->Child.begin(); it != vn->Child.end(); it++)
+ {
+ // vertices, colors
+ if((*it)->Type == CAMFImporter_NodeElement::ENET_Vertex)
+ {
+ // by default clear color for current vertex
+ pVertexColorArray[col_idx] = NULL;
+
+ for(std::list<CAMFImporter_NodeElement*>::const_iterator vtx_it = (*it)->Child.begin(); vtx_it != (*it)->Child.end(); vtx_it++)
+ {
+ if((*vtx_it)->Type == CAMFImporter_NodeElement::ENET_Coordinates)
+ {
+ pVertexCoordinateArray.push_back(((CAMFImporter_NodeElement_Coordinates*)(*vtx_it))->Coordinate);
+
+ continue;
+ }// if((*vtx_it)->Type == CAMFImporter_NodeElement::ENET_Coordinates)
+
+ if((*vtx_it)->Type == CAMFImporter_NodeElement::ENET_Color)
+ {
+ pVertexColorArray[col_idx] = (CAMFImporter_NodeElement_Color*)(*vtx_it);
+
+ continue;
+ }// if((*vtx_it)->Type == CAMFImporter_NodeElement::ENET_Coordinates)
+ }// for(std::list<CAMFImporter_NodeElement*>::const_iterator vtx_it = (*it)->Child.begin(); vtx_it != (*it)->Child.end(); vtx_it++)
+
+ col_idx++;
+ }// if((*it)->Type == CAMFImporter_NodeElement::ENET_Vertex)
+ }// for(std::list<CAMFImporter_NodeElement*>::const_iterator it = pNodeElement.Child.begin(); it != pNodeElement.Child.end(); it++)
+}
+
+size_t AMFImporter::PostprocessHelper_GetTextureID_Or_Create(const std::string& pID_R, const std::string& pID_G, const std::string& pID_B,
+ const std::string& pID_A)
+{
+using CNE_Texture = CAMFImporter_NodeElement_Texture;
+using CNE = CAMFImporter_NodeElement;
+
+size_t TextureConverted_Index;
+std::string TextureConverted_ID;
+
+ // check input data
+ if(pID_R.empty() && pID_G.empty() && pID_B.empty() && pID_A.empty())
+ throw DeadlyImportError("PostprocessHelper_GetTextureID_Or_Create. At least one texture ID must be defined.");
+
+ // Create ID
+ TextureConverted_ID = pID_R + "_" + pID_G + "_" + pID_B + "_" + pID_A;
+ // Check if texture specified by set of IDs is converted already.
+ TextureConverted_Index = 0;
+ for(const SPP_Texture& tex_convd: mTexture_Converted)
+ {
+ if(tex_convd.ID == TextureConverted_ID)
+ return TextureConverted_Index;
+ else
+ TextureConverted_Index++;
+ }
+
+ //
+ // Converted texture not found, create it.
+ //
+ CNE_Texture* src_texture[4]{nullptr};
+ std::vector<CNE_Texture*> src_texture_4check;
+ SPP_Texture converted_texture;
+
+ {// find all specified source textures
+ CNE* t_tex;
+
+ // R
+ if(!pID_R.empty())
+ {
+ if(!Find_NodeElement(pID_R, CNE::ENET_Texture, &t_tex)) Throw_ID_NotFound(pID_R);
+
+ src_texture[0] = (CNE_Texture*)t_tex;
+ src_texture_4check.push_back((CNE_Texture*)t_tex);
+ }
+ else
+ {
+ src_texture[0] = nullptr;
+ }
+
+ // G
+ if(!pID_G.empty())
+ {
+ if(!Find_NodeElement(pID_G, CNE::ENET_Texture, &t_tex)) Throw_ID_NotFound(pID_G);
+
+ src_texture[1] = (CNE_Texture*)t_tex;
+ src_texture_4check.push_back((CNE_Texture*)t_tex);
+ }
+ else
+ {
+ src_texture[1] = nullptr;
+ }
+
+ // B
+ if(!pID_B.empty())
+ {
+ if(!Find_NodeElement(pID_B, CNE::ENET_Texture, &t_tex)) Throw_ID_NotFound(pID_B);
+
+ src_texture[2] = (CNE_Texture*)t_tex;
+ src_texture_4check.push_back((CNE_Texture*)t_tex);
+ }
+ else
+ {
+ src_texture[2] = nullptr;
+ }
+
+ // A
+ if(!pID_A.empty())
+ {
+ if(!Find_NodeElement(pID_A, CNE::ENET_Texture, &t_tex)) Throw_ID_NotFound(pID_A);
+
+ src_texture[3] = (CNE_Texture*)t_tex;
+ src_texture_4check.push_back((CNE_Texture*)t_tex);
+ }
+ else
+ {
+ src_texture[3] = nullptr;
+ }
+ }// END: find all specified source textures
+
+ // check that all textures has same size
+ if(src_texture_4check.size() > 1)
+ {
+ for(uint8_t i = 0, i_e = (src_texture_4check.size() - 1); i < i_e; i++)
+ {
+ if((src_texture_4check[i]->Width != src_texture_4check[i + 1]->Width) || (src_texture_4check[i]->Height != src_texture_4check[i + 1]->Height) ||
+ (src_texture_4check[i]->Depth != src_texture_4check[i + 1]->Depth))
+ {
+ throw DeadlyImportError("PostprocessHelper_GetTextureID_Or_Create. Source texture must has the same size.");
+ }
+ }
+ }// if(src_texture_4check.size() > 1)
+
+ // set texture attributes
+ converted_texture.Width = src_texture_4check[0]->Width;
+ converted_texture.Height = src_texture_4check[0]->Height;
+ converted_texture.Depth = src_texture_4check[0]->Depth;
+ // if one of source texture is tiled then converted texture is tiled too.
+ converted_texture.Tiled = false;
+ for(uint8_t i = 0; i < src_texture_4check.size(); i++) converted_texture.Tiled |= src_texture_4check[i]->Tiled;
+
+ // Create format hint.
+ strcpy(converted_texture.FormatHint, "rgba0000");// copy initial string.
+ if(!pID_R.empty()) converted_texture.FormatHint[4] = '8';
+ if(!pID_G.empty()) converted_texture.FormatHint[4] = '8';
+ if(!pID_B.empty()) converted_texture.FormatHint[4] = '8';
+ if(!pID_A.empty()) converted_texture.FormatHint[4] = '8';
+
+ //
+ // Сopy data of textures.
+ //
+ size_t tex_size = 0;
+ size_t step = 0;
+ size_t off_g = 0;
+ size_t off_b = 0;
+
+ // Calculate size of the target array and rule how data will be copied.
+ if(!pID_R.empty()) { tex_size += src_texture[0]->Data.size(); step++, off_g++, off_b++; }
+ if(!pID_G.empty()) { tex_size += src_texture[1]->Data.size(); step++, off_b++; }
+ if(!pID_B.empty()) { tex_size += src_texture[2]->Data.size(); step++; }
+ if(!pID_A.empty()) { tex_size += src_texture[3]->Data.size(); step++; }
+
+ // Create target array.
+ converted_texture.Data = new uint8_t[tex_size];
+ // And copy data
+ auto CopyTextureData = [&](const std::string& pID, const size_t pOffset, const size_t pStep, const uint8_t pSrcTexNum) -> void
+ {
+ if(!pID.empty())
+ {
+ for(size_t idx_target = pOffset, idx_src = 0; idx_target < tex_size; idx_target += pStep, idx_src++)
+ converted_texture.Data[idx_target] = src_texture[pSrcTexNum]->Data.at(idx_src);
+ }
+ };// auto CopyTextureData = [&](const size_t pOffset, const size_t pStep, const uint8_t pSrcTexNum) -> void
+
+ CopyTextureData(pID_R, 0, step, 0);
+ CopyTextureData(pID_G, off_g, step, 1);
+ CopyTextureData(pID_B, off_b, step, 2);
+ CopyTextureData(pID_A, step - 1, step, 3);
+
+ // Store new converted texture ID
+ converted_texture.ID = TextureConverted_ID;
+ // Store new converted texture
+ mTexture_Converted.push_back(converted_texture);
+
+ return TextureConverted_Index;
+}
+
+void AMFImporter::PostprocessHelper_SplitFacesByTextureID(std::list<SComplexFace>& pInputList, std::list<std::list<SComplexFace> >& pOutputList_Separated)
+{
+auto texmap_is_equal = [](const CAMFImporter_NodeElement_TexMap* pTexMap1, const CAMFImporter_NodeElement_TexMap* pTexMap2) -> bool
+{
+ if((pTexMap1 == nullptr) && (pTexMap2 == nullptr)) return true;
+ if(pTexMap1 == nullptr) return false;
+ if(pTexMap2 == nullptr) return false;
+
+ if(pTexMap1->TextureID_R != pTexMap2->TextureID_R) return false;
+ if(pTexMap1->TextureID_G != pTexMap2->TextureID_G) return false;
+ if(pTexMap1->TextureID_B != pTexMap2->TextureID_B) return false;
+ if(pTexMap1->TextureID_A != pTexMap2->TextureID_A) return false;
+
+ return true;
+};
+
+ pOutputList_Separated.clear();
+ if(pInputList.size() == 0) return;
+
+ do
+ {
+ SComplexFace face_start = pInputList.front();
+ std::list<SComplexFace> face_list_cur;
+
+ for(std::list<SComplexFace>::const_iterator it = pInputList.cbegin(), it_end = pInputList.cend(); it != it_end;)
+ {
+ if(texmap_is_equal(face_start.TexMap, it->TexMap))
+ {
+ auto it_old = it;
+
+ it++;
+ face_list_cur.push_back(*it_old);
+ pInputList.erase(it_old);
+ }
+ else
+ {
+ it++;
+ }
+ }
+
+ if(face_list_cur.size() > 0) pOutputList_Separated.push_back(face_list_cur);
+
+ } while(pInputList.size() > 0);
+}
+
+void AMFImporter::Postprocess_AddMetadata(const std::list<CAMFImporter_NodeElement_Metadata*>& pMetadataList, aiNode& pSceneNode) const
+{
+ if(pMetadataList.size() > 0)
+ {
+ if(pSceneNode.mMetaData != NULL) throw DeadlyImportError("Postprocess. MetaData member in node are not NULL. Something went wrong.");
+
+ // copy collected metadata to output node.
+ pSceneNode.mMetaData = new aiMetadata();
+ pSceneNode.mMetaData->mNumProperties = pMetadataList.size();
+ pSceneNode.mMetaData->mKeys = new aiString[pSceneNode.mMetaData->mNumProperties];
+ pSceneNode.mMetaData->mValues = new aiMetadataEntry[pSceneNode.mMetaData->mNumProperties];
+
+ size_t meta_idx = 0;
+
+ for(std::list<CAMFImporter_NodeElement_Metadata*>::const_iterator it = pMetadataList.begin(); it != pMetadataList.end(); it++)
+ {
+ pSceneNode.mMetaData->Set(meta_idx++, (*it)->Type, (*it)->Value.c_str());
+ }
+ }// if(pMetadataList.size() > 0)
+}
+
+void AMFImporter::Postprocess_BuildNodeAndObject(const CAMFImporter_NodeElement_Object& pNodeElement, std::list<aiMesh*>& pMeshList, aiNode** pSceneNode)
+{
+CAMFImporter_NodeElement_Color* object_color = NULL;
+
+ // create new aiNode and set name as <object> has.
+ *pSceneNode = new aiNode;
+ (*pSceneNode)->mName = pNodeElement.ID;
+ // read mesh and color
+ for(std::list<CAMFImporter_NodeElement*>::const_iterator it = pNodeElement.Child.begin(); it != pNodeElement.Child.end(); it++)
+ {
+ std::vector<aiVector3D> vertex_arr;
+ std::vector<CAMFImporter_NodeElement_Color*> color_arr;
+
+ // color for object
+ if((*it)->Type == CAMFImporter_NodeElement::ENET_Color) object_color = (CAMFImporter_NodeElement_Color*)(*it);
+
+ if((*it)->Type == CAMFImporter_NodeElement::ENET_Mesh)
+ {
+ // Create arrays from children of mesh: vertices.
+ PostprocessHelper_CreateMeshDataArray(*((CAMFImporter_NodeElement_Mesh*)*it), vertex_arr, color_arr);
+ // Use this arrays as a source when creating every aiMesh
+ Postprocess_BuildMeshSet(*((CAMFImporter_NodeElement_Mesh*)*it), vertex_arr, color_arr, object_color, pMeshList, **pSceneNode);
+ }// if((*it)->Type == CAMFImporter_NodeElement::ENET_Mesh)
+ }// for(std::list<CAMFImporter_NodeElement*>::const_iterator it = pNodeElement.Child.begin(); it != pNodeElement.Child.end(); it++)
+}
+
+void AMFImporter::Postprocess_BuildMeshSet(const CAMFImporter_NodeElement_Mesh& pNodeElement, const std::vector<aiVector3D>& pVertexCoordinateArray,
+ const std::vector<CAMFImporter_NodeElement_Color*>& pVertexColorArray,
+ const CAMFImporter_NodeElement_Color* pObjectColor, std::list<aiMesh*>& pMeshList, aiNode& pSceneNode)
+{
+using CNE = CAMFImporter_NodeElement;
+using CNE_Color = CAMFImporter_NodeElement_Color;
+using CNE_TexMap = CAMFImporter_NodeElement_TexMap;
+using ComplexFaceList = std::list<SComplexFace>;
+
+std::list<unsigned int> mesh_idx;
+
+ // all data stored in "volume", search for it.
+ for(const CNE* ne_child: pNodeElement.Child)
+ {
+ const CNE_Color* ne_volume_color = nullptr;
+ const SPP_Material* cur_mat = nullptr;
+
+ if(ne_child->Type == CNE::ENET_Volume)
+ {
+ /******************* Get faces *******************/
+ const CAMFImporter_NodeElement_Volume* ne_volume = reinterpret_cast<const CAMFImporter_NodeElement_Volume*>(ne_child);
+
+ ComplexFaceList complex_faces_list;// List of the faces of the volume.
+ std::list<ComplexFaceList> complex_faces_toplist;// List of the face list for every mesh.
+
+ // check if volume use material
+ if(!ne_volume->MaterialID.empty())
+ {
+ if(!Find_ConvertedMaterial(ne_volume->MaterialID, &cur_mat)) Throw_ID_NotFound(ne_volume->MaterialID);
+ }
+
+ // inside "volume" collect all data and place to arrays or create new objects
+ for(const CNE* ne_volume_child: ne_volume->Child)
+ {
+ // color for volume
+ if(ne_volume_child->Type == CNE::ENET_Color)
+ {
+ ne_volume_color = reinterpret_cast<const CNE_Color*>(ne_volume_child);
+ }
+ else if(ne_volume_child->Type == CNE::ENET_Triangle)// triangles, triangles colors
+ {
+ const CAMFImporter_NodeElement_Triangle& tri_al = *reinterpret_cast<const CAMFImporter_NodeElement_Triangle*>(ne_volume_child);
+
+ SComplexFace complex_face;
+
+ // initialize pointers
+ complex_face.Color = nullptr;
+ complex_face.TexMap = nullptr;
+ // get data from triangle children: color, texture coordinates.
+ if(tri_al.Child.size())
+ {
+ for(const CNE* ne_triangle_child: tri_al.Child)
+ {
+ if(ne_triangle_child->Type == CNE::ENET_Color)
+ complex_face.Color = reinterpret_cast<const CNE_Color*>(ne_triangle_child);
+ else if(ne_triangle_child->Type == CNE::ENET_TexMap)
+ complex_face.TexMap = reinterpret_cast<const CNE_TexMap*>(ne_triangle_child);
+ }
+ }// if(tri_al.Child.size())
+
+ // create new face and store it.
+ complex_face.Face.mNumIndices = 3;
+ complex_face.Face.mIndices = new unsigned int[3];
+ complex_face.Face.mIndices[0] = tri_al.V[0];
+ complex_face.Face.mIndices[1] = tri_al.V[1];
+ complex_face.Face.mIndices[2] = tri_al.V[2];
+ complex_faces_list.push_back(complex_face);
+ }
+ }// for(const CNE* ne_volume_child: ne_volume->Child)
+
+ /**** Split faces list: one list per mesh ****/
+ PostprocessHelper_SplitFacesByTextureID(complex_faces_list, complex_faces_toplist);
+
+ /***** Create mesh for every faces list ******/
+ for(ComplexFaceList& face_list_cur: complex_faces_toplist)
+ {
+ auto VertexIndex_GetMinimal = [](const ComplexFaceList& pFaceList, const size_t* pBiggerThan) -> size_t
+ {
+ size_t rv;
+
+ if(pBiggerThan != nullptr)
+ {
+ bool found = false;
+
+ for(const SComplexFace& face: pFaceList)
+ {
+ for(size_t idx_vert = 0; idx_vert < face.Face.mNumIndices; idx_vert++)
+ {
+ if(face.Face.mIndices[idx_vert] > *pBiggerThan)
+ {
+ rv = face.Face.mIndices[idx_vert];
+ found = true;
+
+ break;
+ }
+ }
+
+ if(found) break;
+ }
+
+ if(!found) return *pBiggerThan;
+ }
+ else
+ {
+ rv = pFaceList.front().Face.mIndices[0];
+ }// if(pBiggerThan != nullptr) else
+
+ for(const SComplexFace& face: pFaceList)
+ {
+ for(size_t vi = 0; vi < face.Face.mNumIndices; vi++)
+ {
+ if(face.Face.mIndices[vi] < rv)
+ {
+ if(pBiggerThan != nullptr)
+ {
+ if(face.Face.mIndices[vi] > *pBiggerThan) rv = face.Face.mIndices[vi];
+ }
+ else
+ {
+ rv = face.Face.mIndices[vi];
+ }
+ }
+ }
+ }// for(const SComplexFace& face: pFaceList)
+
+ return rv;
+ };// auto VertexIndex_GetMinimal = [](const ComplexFaceList& pFaceList, const size_t* pBiggerThan) -> size_t
+
+ auto VertexIndex_Replace = [](ComplexFaceList& pFaceList, const size_t pIdx_From, const size_t pIdx_To) -> void
+ {
+ for(const SComplexFace& face: pFaceList)
+ {
+ for(size_t vi = 0; vi < face.Face.mNumIndices; vi++)
+ {
+ if(face.Face.mIndices[vi] == pIdx_From) face.Face.mIndices[vi] = pIdx_To;
+ }
+ }
+ };// auto VertexIndex_Replace = [](ComplexFaceList& pFaceList, const size_t pIdx_From, const size_t pIdx_To) -> void
+
+ auto Vertex_CalculateColor = [&](const size_t pIdx) -> aiColor4D
+ {
+ // Color priorities(In descending order):
+ // 1. triangle color;
+ // 2. vertex color;
+ // 3. volume color;
+ // 4. object color;
+ // 5. material;
+ // 6. default - invisible coat.
+ //
+ // Fill vertices colors in color priority list above that's points from 1 to 6.
+ if((pIdx < pVertexColorArray.size()) && (pVertexColorArray[pIdx] != nullptr))// check for vertex color
+ {
+ if(pVertexColorArray[pIdx]->Composed)
+ throw DeadlyImportError("IME: vertex color composed");
+ else
+ return pVertexColorArray[pIdx]->Color;
+ }
+ else if(ne_volume_color != nullptr)// check for volume color
+ {
+ if(ne_volume_color->Composed)
+ throw DeadlyImportError("IME: volume color composed");
+ else
+ return ne_volume_color->Color;
+ }
+ else if(pObjectColor != nullptr)// check for object color
+ {
+ if(pObjectColor->Composed)
+ throw DeadlyImportError("IME: object color composed");
+ else
+ return pObjectColor->Color;
+ }
+ else if(cur_mat != nullptr)// check for material
+ {
+ return cur_mat->GetColor(pVertexCoordinateArray.at(pIdx).x, pVertexCoordinateArray.at(pIdx).y, pVertexCoordinateArray.at(pIdx).z);
+ }
+ else// set default color.
+ {
+ return {0, 0, 0, 0};
+ }// if((vi < pVertexColorArray.size()) && (pVertexColorArray[vi] != NULL)) else
+
+ };// auto Vertex_CalculateColor = [&](const size_t pIdx) -> aiColor4D
+
+ aiMesh* tmesh = new aiMesh;
+
+ tmesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;// Only triangles is supported by AMF.
+ //
+ // set geometry and colors (vertices)
+ //
+ // copy faces/triangles
+ tmesh->mNumFaces = face_list_cur.size();
+ tmesh->mFaces = new aiFace[tmesh->mNumFaces];
+
+ // Create vertices list and optimize indices. Optimisation mean following.In AMF all volumes use one big list of vertices. And one volume
+ // can use only part of vertices list, for example: vertices list contain few thousands of vertices and volume use vertices 1, 3, 10.
+ // Do you need all this thousands of garbage? Of course no. So, optimisation step transformate sparse indices set to continuous.
+ const size_t VertexCount_Max = tmesh->mNumFaces * 3;// 3 - triangles.
+ std::vector<aiVector3D> vert_arr, texcoord_arr;
+ std::vector<aiColor4D> col_arr;
+
+ vert_arr.reserve(VertexCount_Max * 2);// "* 2" - see below TODO.
+ col_arr.reserve(VertexCount_Max * 2);
+
+ {// fill arrays
+ size_t vert_idx_from, vert_idx_to;
+
+ // first iteration.
+ vert_idx_to = 0;
+ vert_idx_from = VertexIndex_GetMinimal(face_list_cur, nullptr);
+ vert_arr.push_back(pVertexCoordinateArray.at(vert_idx_from));
+ col_arr.push_back(Vertex_CalculateColor(vert_idx_from));
+ if(vert_idx_from != vert_idx_to) VertexIndex_Replace(face_list_cur, vert_idx_from, vert_idx_to);
+
+ // rest iterations
+ do
+ {
+ vert_idx_from = VertexIndex_GetMinimal(face_list_cur, &vert_idx_to);
+ if(vert_idx_from == vert_idx_to) break;// all indices are transfered,
+
+ vert_arr.push_back(pVertexCoordinateArray.at(vert_idx_from));
+ col_arr.push_back(Vertex_CalculateColor(vert_idx_from));
+ vert_idx_to++;
+ if(vert_idx_from != vert_idx_to) VertexIndex_Replace(face_list_cur, vert_idx_from, vert_idx_to);
+
+ } while(true);
+ }// fill arrays. END.
+
+ //
+ // check if triangle colors are used and create additional faces if needed.
+ //
+ for(const SComplexFace& face_cur: face_list_cur)
+ {
+ if(face_cur.Color != nullptr)
+ {
+ aiColor4D face_color;
+ size_t vert_idx_new = vert_arr.size();
+
+ if(face_cur.Color->Composed)
+ throw DeadlyImportError("IME: face color composed");
+ else
+ face_color = face_cur.Color->Color;
+
+ for(size_t idx_ind = 0; idx_ind < face_cur.Face.mNumIndices; idx_ind++)
+ {
+ vert_arr.push_back(vert_arr.at(face_cur.Face.mIndices[idx_ind]));
+ col_arr.push_back(face_color);
+ face_cur.Face.mIndices[idx_ind] = vert_idx_new++;
+ }
+ }// if(face_cur.Color != nullptr)
+ }// for(const SComplexFace& face_cur: face_list_cur)
+
+ //
+ // if texture is used then copy texture coordinates too.
+ //
+ if(face_list_cur.front().TexMap != nullptr)
+ {
+ size_t idx_vert_new = vert_arr.size();
+ ///TODO: clean unused vertices. "* 2": in certain cases - mesh full of triangle colors - vert_arr will contain duplicated vertices for
+ /// colored triangles and initial vertices (for colored vertices) which in real became unused. This part need more thinking about
+ /// optimisation.
+ bool idx_vert_used[VertexCount_Max * 2]{false};
+
+ // This ID's will be used when set materials ID in scene.
+ tmesh->mMaterialIndex = PostprocessHelper_GetTextureID_Or_Create(face_list_cur.front().TexMap->TextureID_R,
+ face_list_cur.front().TexMap->TextureID_G,
+ face_list_cur.front().TexMap->TextureID_B,
+ face_list_cur.front().TexMap->TextureID_A);
+ texcoord_arr.resize(VertexCount_Max * 2);
+ for(const SComplexFace& face_cur: face_list_cur)
+ {
+ for(size_t idx_ind = 0; idx_ind < face_cur.Face.mNumIndices; idx_ind++)
+ {
+ const size_t idx_vert = face_cur.Face.mIndices[idx_ind];
+
+ if(!idx_vert_used[idx_vert])
+ {
+ texcoord_arr.at(idx_vert) = face_cur.TexMap->TextureCoordinate[idx_ind];
+ idx_vert_used[idx_vert] = true;
+ }
+ else if(texcoord_arr.at(idx_vert) != face_cur.TexMap->TextureCoordinate[idx_ind])
+ {
+ // in that case one vertex is shared with many texture coordinates. We need to duplicate vertex with another texture
+ // coordinates.
+ vert_arr.push_back(vert_arr.at(idx_vert));
+ col_arr.push_back(col_arr.at(idx_vert));
+ texcoord_arr.at(idx_vert_new) = face_cur.TexMap->TextureCoordinate[idx_ind];
+ face_cur.Face.mIndices[idx_ind] = idx_vert_new++;
+ }
+ }// for(size_t idx_ind = 0; idx_ind < face_cur.Face.mNumIndices; idx_ind++)
+ }// for(const SComplexFace& face_cur: face_list_cur)
+
+ // shrink array
+ texcoord_arr.resize(idx_vert_new);
+ }// if(face_list_cur.front().TexMap != nullptr)
+
+ //
+ // copy collected data to mesh
+ //
+ tmesh->mNumVertices = vert_arr.size();
+ tmesh->mVertices = new aiVector3D[tmesh->mNumVertices];
+ tmesh->mColors[0] = new aiColor4D[tmesh->mNumVertices];
+ tmesh->mFaces = new aiFace[face_list_cur.size()];
+
+ memcpy(tmesh->mVertices, vert_arr.data(), tmesh->mNumVertices * sizeof(aiVector3D));
+ memcpy(tmesh->mColors[0], col_arr.data(), tmesh->mNumVertices * sizeof(aiColor4D));
+ if(texcoord_arr.size() > 0)
+ {
+ tmesh->mTextureCoords[0] = new aiVector3D[tmesh->mNumVertices];
+ memcpy(tmesh->mTextureCoords[0], texcoord_arr.data(), tmesh->mNumVertices * sizeof(aiVector3D));
+ tmesh->mNumUVComponents[0] = 2;// U and V stored in "x", "y" of aiVector3D.
+ }
+
+ size_t idx_face = 0;
+ for(const SComplexFace& face_cur: face_list_cur) tmesh->mFaces[idx_face++] = face_cur.Face;
+
+ // store new aiMesh
+ mesh_idx.push_back(pMeshList.size());
+ pMeshList.push_back(tmesh);
+ }// for(const ComplexFaceList& face_list_cur: complex_faces_toplist)
+ }// if(ne_child->Type == CAMFImporter_NodeElement::ENET_Volume)
+ }// for(const CNE* ne_child: pNodeElement.Child)
+
+ // if meshes was created then assign new indices with current aiNode
+ if(mesh_idx.size() > 0)
+ {
+ std::list<unsigned int>::const_iterator mit = mesh_idx.begin();
+
+ pSceneNode.mNumMeshes = mesh_idx.size();
+ pSceneNode.mMeshes = new unsigned int[pSceneNode.mNumMeshes];
+ for(size_t i = 0; i < pSceneNode.mNumMeshes; i++) pSceneNode.mMeshes[i] = *mit++;
+ }// if(mesh_idx.size() > 0)
+}
+
+void AMFImporter::Postprocess_BuildMaterial(const CAMFImporter_NodeElement_Material& pMaterial)
+{
+SPP_Material new_mat;
+
+ new_mat.ID = pMaterial.ID;
+ for(std::list<CAMFImporter_NodeElement*>::const_iterator it = pMaterial.Child.begin(); it != pMaterial.Child.end(); it++)
+ {
+ if((*it)->Type == CAMFImporter_NodeElement::ENET_Color)
+ {
+ new_mat.Color = (CAMFImporter_NodeElement_Color*)(*it);
+ }
+ else if((*it)->Type == CAMFImporter_NodeElement::ENET_Metadata)
+ {
+ new_mat.Metadata.push_back((CAMFImporter_NodeElement_Metadata*)(*it));
+ }
+ }// for(std::list<CAMFImporter_NodeElement*>::const_iterator it = pMaterial.Child.begin(); it != pMaterial.Child.end(); it++)
+
+ // place converted material to special list
+ mMaterial_Converted.push_back(new_mat);
+}
+
+void AMFImporter::Postprocess_BuildConstellation(CAMFImporter_NodeElement_Constellation& pConstellation, std::list<aiNode*>& pNodeList) const
+{
+aiNode* con_node;
+std::list<aiNode*> ch_node;
+
+ // We will build next hierarchy:
+ // aiNode as parent (<constellation>) for set of nodes as a children
+ // |- aiNode for transformation (<instance> -> <delta...>, <r...>) - aiNode for pointing to object ("objectid")
+ // ...
+ // \_ aiNode for transformation (<instance> -> <delta...>, <r...>) - aiNode for pointing to object ("objectid")
+ con_node = new aiNode;
+ con_node->mName = pConstellation.ID;
+ // Walk thru children and search for instances of another objects, constellations.
+ for(std::list<CAMFImporter_NodeElement*>::const_iterator it = pConstellation.Child.begin(); it != pConstellation.Child.end(); it++)
+ {
+ aiMatrix4x4 tmat;
+ aiNode* t_node;
+ aiNode* found_node;
+
+ if((*it)->Type == CAMFImporter_NodeElement::ENET_Metadata) continue;
+ if((*it)->Type != CAMFImporter_NodeElement::ENET_Instance) throw DeadlyImportError("Only <instance> nodes can be in <constellation>.");
+
+ // create alias for conveniance
+ CAMFImporter_NodeElement_Instance& als = *((CAMFImporter_NodeElement_Instance*)(*it));
+ // find referenced object
+ if(!Find_ConvertedNode(als.ObjectID, pNodeList, &found_node)) Throw_ID_NotFound(als.ObjectID);
+
+ // create node for apllying transformation
+ t_node = new aiNode;
+ t_node->mParent = con_node;
+ // apply transformation
+ aiMatrix4x4::Translation(als.Delta, tmat), t_node->mTransformation *= tmat;
+ aiMatrix4x4::RotationX(als.Rotation.x, tmat), t_node->mTransformation *= tmat;
+ aiMatrix4x4::RotationY(als.Rotation.y, tmat), t_node->mTransformation *= tmat;
+ aiMatrix4x4::RotationZ(als.Rotation.z, tmat), t_node->mTransformation *= tmat;
+ // create array for one child node
+ t_node->mNumChildren = 1;
+ t_node->mChildren = new aiNode*[t_node->mNumChildren];
+ SceneCombiner::Copy(&t_node->mChildren[0], found_node);
+ t_node->mChildren[0]->mParent = t_node;
+ ch_node.push_back(t_node);
+ }// for(std::list<CAMFImporter_NodeElement*>::const_iterator it = mNodeElement_List.begin(); it != mNodeElement_List.end(); it++)
+
+ // copy found aiNode's as children
+ if(ch_node.size() == 0) throw DeadlyImportError("<constellation> must have at least one <instance>.");
+
+ size_t ch_idx = 0;
+
+ con_node->mNumChildren = ch_node.size();
+ con_node->mChildren = new aiNode*[con_node->mNumChildren];
+ for(std::list<aiNode*>::const_iterator it = ch_node.begin(); it != ch_node.end(); it++) con_node->mChildren[ch_idx++] = *it;
+
+ // and place "root" of <constellation> node to node list
+ pNodeList.push_back(con_node);
+}
+
+void AMFImporter::Postprocess_BuildScene(aiScene* pScene)
+{
+std::list<aiNode*> node_list;
+std::list<aiMesh*> mesh_list;
+std::list<CAMFImporter_NodeElement_Metadata*> meta_list;
+
+ //
+ // Because for AMF "material" is just complex colors mixing so aiMaterial will not be used.
+ // For building aiScene we are must to do few steps:
+ // at first creating root node for aiScene.
+ pScene->mRootNode = new aiNode;
+ pScene->mRootNode->mParent = NULL;
+ pScene->mFlags |= AI_SCENE_FLAGS_ALLOW_SHARED;
+ // search for root(<amf>) element
+ CAMFImporter_NodeElement* root_el = NULL;
+ for(std::list<CAMFImporter_NodeElement*>::const_iterator it = mNodeElement_List.begin(); it != mNodeElement_List.end(); it++)
+ {
+ if((*it)->Type != CAMFImporter_NodeElement::ENET_Root) continue;
+
+ root_el = *it;
+
+ break;
+ }// for(std::list<CAMFImporter_NodeElement*>::const_iterator it = mNodeElement_List.begin(); it != mNodeElement_List.end(); it++)
+
+ // Check if root element are found.
+ if(root_el == NULL) throw DeadlyImportError("Root(<amf>) element not found.");
+
+ // after that walk thru children of root and collect data. Five types of nodes can be placed at top level - in <amf>: <object>, <material>, <texture>,
+ // <constellation> and <metadata>. But at first we must read <material> and <texture> because they will be used in <object>. <metadata> can be read
+ // at any moment.
+ //
+ // 1. <material>
+ // 2. <texture> will be converted later when processing triangles list. \sa Postprocess_BuildMeshSet
+ for(std::list<CAMFImporter_NodeElement*>::const_iterator it = root_el->Child.begin(), it_end = root_el->Child.end(); it != it_end; it++)
+ {
+ if((*it)->Type == CAMFImporter_NodeElement::ENET_Material) Postprocess_BuildMaterial(*((CAMFImporter_NodeElement_Material*)*it));
+ }
+
+ // After "appearance" nodes we must read <object> because it will be used in <constellation> -> <instance>.
+ //
+ // 3. <object>
+ for(std::list<CAMFImporter_NodeElement*>::const_iterator it = root_el->Child.begin(), it_end = root_el->Child.end(); it != it_end; it++)
+ {
+ if((*it)->Type == CAMFImporter_NodeElement::ENET_Object)
+ {
+ aiNode* tnode = NULL;
+
+ // for <object> mesh and node must be built: object ID assigned to aiNode name and will be used in future for <instance>
+ Postprocess_BuildNodeAndObject(*((CAMFImporter_NodeElement_Object*)*it), mesh_list, &tnode);
+ if(tnode != NULL) node_list.push_back(tnode);
+
+ }// if(it->Type == CAMFImporter_NodeElement::ENET_Object)
+ }// for(std::list<CAMFImporter_NodeElement*>::const_iterator it = root_el->Child.begin(), it_end = root_el->Child.end(); it != it_end; it++)
+
+ // And finally read rest of nodes.
+ //
+ for(std::list<CAMFImporter_NodeElement*>::const_iterator it = root_el->Child.begin(), it_end = root_el->Child.end(); it != it_end; it++)
+ {
+ // 4. <constellation>
+ if((*it)->Type == CAMFImporter_NodeElement::ENET_Constellation)
+ {
+ // <object> and <constellation> at top of self abstraction use aiNode. So we can use only aiNode list for creating new aiNode's.
+ Postprocess_BuildConstellation(*((CAMFImporter_NodeElement_Constellation*)*it), node_list);
+ }
+
+ // 5, <metadata>
+ if((*it)->Type == CAMFImporter_NodeElement::ENET_Metadata) meta_list.push_back((CAMFImporter_NodeElement_Metadata*)*it);
+ }// for(std::list<CAMFImporter_NodeElement*>::const_iterator it = root_el->Child.begin(), it_end = root_el->Child.end(); it != it_end; it++)
+
+ // at now we can add collected metadata to root node
+ Postprocess_AddMetadata(meta_list, *pScene->mRootNode);
+ //
+ // Check constellation children
+ //
+ // As said in specification:
+ // "When multiple objects and constellations are defined in a single file, only the top level objects and constellations are available for printing."
+ // What that means? For example: if some object is used in constellation then you must show only constellation but not original object.
+ // And at this step we are checking that relations.
+nl_clean_loop:
+
+ if(node_list.size() > 1)
+ {
+ // walk thru all nodes
+ for(std::list<aiNode*>::iterator nl_it = node_list.begin(); nl_it != node_list.end(); nl_it++)
+ {
+ // and try to find them in another top nodes.
+ std::list<aiNode*>::const_iterator next_it = nl_it;
+
+ next_it++;
+ for(; next_it != node_list.end(); next_it++)
+ {
+ if((*next_it)->FindNode((*nl_it)->mName) != NULL)
+ {
+ // if current top node(nl_it) found in another top node then erase it from node_list and restart search loop.
+ node_list.erase(nl_it);
+
+ goto nl_clean_loop;
+ }
+ }// for(; next_it != node_list.end(); next_it++)
+ }// for(std::list<aiNode*>::const_iterator nl_it = node_list.begin(); nl_it != node_list.end(); nl_it++)
+ }
+
+ //
+ // move created objects to aiScene
+ //
+ //
+ // Nodes
+ if(node_list.size() > 0)
+ {
+ std::list<aiNode*>::const_iterator nl_it = node_list.begin();
+
+ pScene->mRootNode->mNumChildren = node_list.size();
+ pScene->mRootNode->mChildren = new aiNode*[pScene->mRootNode->mNumChildren];
+ for(size_t i = 0; i < pScene->mRootNode->mNumChildren; i++)
+ {
+ // Objects and constellation that must be showed placed at top of hierarchy in <amf> node. So all aiNode's in node_list must have
+ // mRootNode only as parent.
+ (*nl_it)->mParent = pScene->mRootNode;
+ pScene->mRootNode->mChildren[i] = *nl_it++;
+ }
+ }// if(node_list.size() > 0)
+
+ //
+ // Meshes
+ if(mesh_list.size() > 0)
+ {
+ std::list<aiMesh*>::const_iterator ml_it = mesh_list.begin();
+
+ pScene->mNumMeshes = mesh_list.size();
+ pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
+ for(size_t i = 0; i < pScene->mNumMeshes; i++) pScene->mMeshes[i] = *ml_it++;
+ }// if(mesh_list.size() > 0)
+
+ //
+ // Textures
+ pScene->mNumTextures = mTexture_Converted.size();
+ if(pScene->mNumTextures > 0)
+ {
+ size_t idx;
+
+ idx = 0;
+ pScene->mTextures = new aiTexture*[pScene->mNumTextures];
+ for(const SPP_Texture& tex_convd: mTexture_Converted)
+ {
+ pScene->mTextures[idx] = new aiTexture;
+ pScene->mTextures[idx]->mWidth = tex_convd.Width;
+ pScene->mTextures[idx]->mHeight = tex_convd.Height;
+ pScene->mTextures[idx]->pcData = (aiTexel*)tex_convd.Data;
+ // texture format description.
+ strcpy(pScene->mTextures[idx]->achFormatHint, tex_convd.FormatHint);
+ idx++;
+ }// for(const SPP_Texture& tex_convd: mTexture_Converted)
+
+ // Create materials for embedded textures.
+ idx = 0;
+ pScene->mNumMaterials = mTexture_Converted.size();
+ pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials];
+ for(const SPP_Texture& tex_convd: mTexture_Converted)
+ {
+ const aiString texture_id(AI_EMBEDDED_TEXNAME_PREFIX + std::to_string(idx));
+ const int mode = aiTextureOp_Multiply;
+ const int repeat = tex_convd.Tiled ? 1 : 0;
+
+ pScene->mMaterials[idx] = new aiMaterial;
+ pScene->mMaterials[idx]->AddProperty(&texture_id, AI_MATKEY_TEXTURE_DIFFUSE(0));
+ pScene->mMaterials[idx]->AddProperty(&mode, 1, AI_MATKEY_TEXOP_DIFFUSE(0));
+ pScene->mMaterials[idx]->AddProperty(&repeat, 1, AI_MATKEY_MAPPINGMODE_U_DIFFUSE(0));
+ pScene->mMaterials[idx]->AddProperty(&repeat, 1, AI_MATKEY_MAPPINGMODE_V_DIFFUSE(0));
+ idx++;
+ }
+ }// if(pScene->mNumTextures > 0)
+}// END: after that walk thru children of root and collect data
+
+}// namespace Assimp
+
+#endif // !ASSIMP_BUILD_NO_AMF_IMPORTER