assimp/code/AssetLib/AMF/AMFImporter.cpp

533 lines
19 KiB
C++
Raw Normal View History

/*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2020, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
/// \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 <assimp/DefaultIOSystem.h>
#include <assimp/fast_atof.h>
// Header files, stdlib.
#include <memory>
namespace Assimp {
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 = nullptr;
mUnit.clear();
mMaterial_Converted.clear();
mTexture_Converted.clear();
// Delete all elements
if (!mNodeElement_List.empty()) {
2020-06-27 13:57:06 +00:00
for (AMFNodeElementBase *ne : mNodeElement_List) {
delete ne;
}
mNodeElement_List.clear();
}
}
2020-07-04 07:04:06 +00:00
AMFImporter::AMFImporter() AI_NO_EXCEPT : mNodeElement_Cur(nullptr),
mXmlParser(nullptr) {
2020-06-27 13:57:06 +00:00
// empty
}
AMFImporter::~AMFImporter() {
2020-06-27 13:57:06 +00:00
delete mXmlParser;
// Clear() is accounting if data already is deleted. So, just check again if all data is deleted.
Clear();
}
/*********************************************************************************************************************************************/
/************************************************************ Functions: find set ************************************************************/
/*********************************************************************************************************************************************/
2020-06-27 13:57:06 +00:00
bool AMFImporter::Find_NodeElement(const std::string &pID, const AMFNodeElementBase::EType pType, AMFNodeElementBase **pNodeElement) const {
for (AMFNodeElementBase *ne : mNodeElement_List) {
if ((ne->ID == pID) && (ne->Type == pType)) {
2020-06-27 13:57:06 +00:00
if (pNodeElement != nullptr) {
*pNodeElement = ne;
}
return true;
}
} // for(CAMFImporter_NodeElement* ne: mNodeElement_List)
return false;
}
bool AMFImporter::Find_ConvertedNode(const std::string &pID, std::list<aiNode *> &pNodeList, aiNode **pNode) const {
aiString node_name(pID.c_str());
for (aiNode *node : pNodeList) {
if (node->mName == node_name) {
2020-06-27 13:57:06 +00:00
if (pNode != nullptr) {
*pNode = node;
}
return true;
}
} // for(aiNode* node: pNodeList)
return false;
}
bool AMFImporter::Find_ConvertedMaterial(const std::string &pID, const SPP_Material **pConvertedMaterial) const {
for (const SPP_Material &mat : mMaterial_Converted) {
if (mat.ID == pID) {
2020-06-27 13:57:06 +00:00
if (pConvertedMaterial != nullptr) {
*pConvertedMaterial = &mat;
}
return true;
}
} // for(const SPP_Material& mat: mMaterial_Converted)
return false;
}
/*********************************************************************************************************************************************/
/************************************************************ Functions: throw set ***********************************************************/
/*********************************************************************************************************************************************/
2020-06-27 13:57:06 +00:00
void AMFImporter::Throw_CloseNotFound(const std::string &nodeName) {
throw DeadlyImportError("Close tag for node <" + nodeName + "> not found. Seems file is corrupt.");
}
2020-06-27 13:57:06 +00:00
void AMFImporter::Throw_IncorrectAttr(const std::string &nodeName, const std::string &attrName) {
throw DeadlyImportError("Node <" + nodeName + "> has incorrect attribute \"" + attrName + "\".");
}
2020-06-27 13:57:06 +00:00
void AMFImporter::Throw_IncorrectAttrValue(const std::string &nodeName, const std::string &attrName) {
throw DeadlyImportError("Attribute \"" + attrName + "\" in node <" + nodeName + "> has incorrect value.");
}
2020-06-27 13:57:06 +00:00
void AMFImporter::Throw_MoreThanOnceDefined(const std::string &nodeName, const std::string &pNodeType, const std::string &pDescription) {
throw DeadlyImportError("\"" + pNodeType + "\" node can be used only once in " + nodeName + ". Description: " + pDescription);
}
void AMFImporter::Throw_ID_NotFound(const std::string &pID) const {
throw DeadlyImportError("Not found node with name \"" + pID + "\".");
}
/*********************************************************************************************************************************************/
/************************************************************* Functions: XML set ************************************************************/
/*********************************************************************************************************************************************/
2020-06-27 13:57:06 +00:00
void AMFImporter::XML_CheckNode_MustHaveChildren(pugi::xml_node &node) {
if (node.children().begin() == node.children().end()) {
throw DeadlyImportError(std::string("Node <") + node.name() + "> must have children.");
}
}
2020-06-27 13:57:06 +00:00
bool AMFImporter::XML_SearchNode(const std::string &nodeName) {
2020-07-04 07:04:06 +00:00
return nullptr != mXmlParser->findNode(nodeName);
}
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) {
std::unique_ptr<IOStream> file(pIOHandler->Open(pFile, "rb"));
// Check whether we can read from the file
2020-06-27 13:57:06 +00:00
if (file.get() == nullptr) {
throw DeadlyImportError("Failed to open AMF file " + pFile + ".");
}
mXmlParser = new XmlParser();
2020-07-04 07:04:06 +00:00
if (!mXmlParser->parse( file.get() )) {
2020-06-27 13:57:06 +00:00
delete mXmlParser;
throw DeadlyImportError("Failed to create XML reader for file" + pFile + ".");
}
// Start reading, search for root tag <amf>
if (!mXmlParser->hasNode("amf")) {
throw DeadlyImportError("Root node \"amf\" not found.");
2020-06-27 13:57:06 +00:00
}
ParseNode_Root();
2020-07-04 07:04:06 +00:00
} // namespace Assimp
// <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;
2020-07-04 07:04:06 +00:00
AMFNodeElementBase *ne(nullptr);
2020-08-30 19:10:04 +00:00
XmlNode *root = mXmlParser->findNode("amf");
if (nullptr == root) {
throw DeadlyImportError("Root node \"amf\" not found.");
}
XmlNode node = *root;
unit = node.attribute("unit").as_string();
version = node.attribute("version").as_string();
// Read attributes for node <amf>.
// Check attributes
if (!mUnit.empty()) {
2020-07-04 07:04:06 +00:00
if ((mUnit != "inch") && (mUnit != "millimeter") && (mUnit != "meter") && (mUnit != "feet") && (mUnit != "micron")) {
Throw_IncorrectAttrValue("unit", mUnit);
}
}
// create root node element.
2020-07-04 07:04:06 +00:00
ne = new AMFRoot(nullptr);
mNodeElement_Cur = ne; // set first "current" element
// and assign attribute's values
2020-07-04 07:04:06 +00:00
((AMFRoot *)ne)->Unit = unit;
((AMFRoot *)ne)->Version = version;
2020-07-10 20:25:38 +00:00
// Check for child nodes
2020-08-30 19:10:04 +00:00
for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
2020-07-04 07:04:06 +00:00
const std::string currentName = currentNode.name();
if (currentName == "object") {
ParseNode_Object(currentNode);
} else if (currentName == "material") {
ParseNode_Material(currentNode);
} else if (currentName == "texture") {
ParseNode_Texture(currentNode);
} else if (currentName == "constellation") {
ParseNode_Constellation(currentNode);
} else if (currentName == "metadata") {
ParseNode_Metadata(currentNode);
}
mNodeElement_Cur = ne; // force restore "current" element
}
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>.
2020-07-04 07:04:06 +00:00
void AMFImporter::ParseNode_Constellation(XmlNode &node) {
std::string id;
2020-07-04 07:04:06 +00:00
id = node.attribute("id").as_string();
// create and if needed - define new grouping object.
2020-07-04 07:04:06 +00:00
AMFNodeElementBase *ne = new AMFConstellation(mNodeElement_Cur);
2020-07-04 07:04:06 +00:00
AMFConstellation &als = *((AMFConstellation *)ne); // alias for convenience
2020-07-04 07:04:06 +00:00
if (!id.empty()) {
als.ID = id;
}
2020-07-10 20:25:38 +00:00
// Check for child nodes
2020-08-30 19:10:04 +00:00
for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
2020-07-04 07:04:06 +00:00
std::string name = currentNode.name();
if (name == "instance") {
ParseNode_Instance(currentNode);
} else if (name == "metadata") {
ParseNode_Metadata(currentNode);
}
}
if (node.empty()) {
mNodeElement_Cur->Child.push_back(ne);
}
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>.
2020-07-04 07:04:06 +00:00
void AMFImporter::ParseNode_Instance(XmlNode &node) {
AMFNodeElementBase *ne(nullptr);
// Read attributes for node <constellation>.
2020-07-04 07:04:06 +00:00
std::string objectid = node.attribute("objectid").as_string();
// used object id must be defined, check that.
2020-07-04 07:04:06 +00:00
if (objectid.empty()) {
throw DeadlyImportError("\"objectid\" in <instance> must be defined.");
}
// create and define new grouping object.
2020-07-04 07:04:06 +00:00
ne = new AMFInstance(mNodeElement_Cur);
AMFInstance &als = *((AMFInstance *)ne);
als.ObjectID = objectid;
2020-07-04 07:04:06 +00:00
if (node.empty()) {
mNodeElement_Cur->Child.push_back(ne);
}
2020-08-30 19:10:04 +00:00
for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
bool read_flag[6] = { false, false, false, false, false, false };
2020-07-04 07:04:06 +00:00
std::string currentName = currentNode.name();
if (currentName == "deltax") {
read_flag[0] = true;
als.Delta.x = (ai_real) std::atof(currentNode.value());
} else if (currentName == "deltay") {
read_flag[1] = true;
als.Delta.y = (ai_real)std::atof(currentNode.value());
} else if (currentName == "deltaz") {
read_flag[2] = true;
als.Delta.z = (ai_real)std::atof(currentNode.value());
} else if (currentName == "rx") {
read_flag[3] = true;
als.Delta.x = (ai_real)std::atof(currentNode.value());
} else if (currentName == "ry") {
read_flag[4] = true;
als.Delta.y = (ai_real)std::atof(currentNode.value());
} else if (currentName == "rz") {
read_flag[5] = true;
als.Delta.z = (ai_real)std::atof(currentNode.value());
}
}
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>.
2020-07-04 07:04:06 +00:00
void AMFImporter::ParseNode_Object(XmlNode &node) {
AMFNodeElementBase *ne(nullptr);
// Read attributes for node <object>.
2020-07-04 07:04:06 +00:00
std::string id = node.attribute("id").as_string();
2020-07-10 20:25:38 +00:00
// create and if needed - define new geometry object.
2020-07-04 07:04:06 +00:00
ne = new AMFObject(mNodeElement_Cur);
AMFObject &als = *((AMFObject *)ne); // alias for convenience
2020-07-04 07:04:06 +00:00
if (!id.empty()) {
als.ID = id;
}
// Check for child nodes
2020-07-04 07:04:06 +00:00
bool col_read = false;
if (node.empty()) {
mNodeElement_Cur->Child.push_back(ne); // Add element to child list of current element
}
2020-08-30 19:10:04 +00:00
for (XmlNode currentNode = node.first_child(); currentNode; currentNode = currentNode.next_sibling()) {
2020-07-04 07:04:06 +00:00
const std::string currentName = currentNode.name();
if (currentName == "color") {
ParseNode_Color(currentNode);
col_read = true;
} else if (currentName == "mesh") {
ParseNode_Mesh(currentNode);
} else if (currentName == "metadata") {
ParseNode_Metadata(currentNode);
}
}
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)
2020-07-04 07:04:06 +00:00
void AMFImporter::ParseNode_Metadata(XmlNode &node) {
std::string type, value;
2020-07-04 07:04:06 +00:00
AMFNodeElementBase *ne(nullptr);
type = node.attribute("type").as_string();
value = node.value();
// read attribute
2020-07-04 07:04:06 +00:00
ne = new AMFMetadata(mNodeElement_Cur);
((AMFMetadata *)ne)->Type = type;
((AMFMetadata *)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.
}
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[] = { "<amf" };
return SearchFileHeaderForToken(pIOHandler, pFile, tokens, 1);
}
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