Commit c6fcf2f0 authored by TheNumbat's avatar TheNumbat
Browse files

initial codebase

parent f746c7c1
/*
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.
----------------------------------------------------------------------
*/
#ifndef ASSIMP_BUILD_NO_3MF_IMPORTER
#include "D3MFImporter.h"
#include <assimp/StringComparison.h>
#include <assimp/StringUtils.h>
#include <assimp/ZipArchiveIOSystem.h>
#include <assimp/importerdesc.h>
#include <assimp/scene.h>
#include <assimp/DefaultLogger.hpp>
#include <assimp/IOSystem.hpp>
#include <cassert>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "3MFXmlTags.h"
#include "D3MFOpcPackage.h"
#include <assimp/fast_atof.h>
#include <assimp/irrXMLWrapper.h>
#include <iomanip>
namespace Assimp {
namespace D3MF {
class XmlSerializer {
public:
using MatArray = std::vector<aiMaterial *>;
using MatId2MatArray = std::map<unsigned int, std::vector<unsigned int>>;
XmlSerializer(XmlReader *xmlReader) :
mMeshes(),
mMatArray(),
mActiveMatGroup(99999999),
mMatId2MatArray(),
xmlReader(xmlReader) {
// empty
}
~XmlSerializer() {
// empty
}
void ImportXml(aiScene *scene) {
if (nullptr == scene) {
return;
}
scene->mRootNode = new aiNode();
std::vector<aiNode *> children;
std::string nodeName;
while (ReadToEndElement(D3MF::XmlTag::model)) {
nodeName = xmlReader->getNodeName();
if (nodeName == D3MF::XmlTag::object) {
children.push_back(ReadObject(scene));
} else if (nodeName == D3MF::XmlTag::build) {
//
} else if (nodeName == D3MF::XmlTag::basematerials) {
ReadBaseMaterials();
} else if (nodeName == D3MF::XmlTag::meta) {
ReadMetadata();
}
}
if (scene->mRootNode->mName.length == 0) {
scene->mRootNode->mName.Set("3MF");
}
// import the metadata
if (!mMetaData.empty()) {
const size_t numMeta(mMetaData.size());
scene->mMetaData = aiMetadata::Alloc(static_cast<unsigned int>(numMeta));
for (size_t i = 0; i < numMeta; ++i) {
aiString val(mMetaData[i].value);
scene->mMetaData->Set(static_cast<unsigned int>(i), mMetaData[i].name, val);
}
}
// import the meshes
scene->mNumMeshes = static_cast<unsigned int>(mMeshes.size());
scene->mMeshes = new aiMesh *[scene->mNumMeshes]();
std::copy(mMeshes.begin(), mMeshes.end(), scene->mMeshes);
// import the materials
scene->mNumMaterials = static_cast<unsigned int>(mMatArray.size());
if (0 != scene->mNumMaterials) {
scene->mMaterials = new aiMaterial *[scene->mNumMaterials];
std::copy(mMatArray.begin(), mMatArray.end(), scene->mMaterials);
}
// create the scenegraph
scene->mRootNode->mNumChildren = static_cast<unsigned int>(children.size());
scene->mRootNode->mChildren = new aiNode *[scene->mRootNode->mNumChildren]();
std::copy(children.begin(), children.end(), scene->mRootNode->mChildren);
}
private:
aiNode *ReadObject(aiScene *scene) {
std::unique_ptr<aiNode> node(new aiNode());
std::vector<unsigned long> meshIds;
const char *attrib(nullptr);
std::string name, type;
attrib = xmlReader->getAttributeValue(D3MF::XmlTag::id.c_str());
if (nullptr != attrib) {
name = attrib;
}
attrib = xmlReader->getAttributeValue(D3MF::XmlTag::type.c_str());
if (nullptr != attrib) {
type = attrib;
}
node->mParent = scene->mRootNode;
node->mName.Set(name);
size_t meshIdx = mMeshes.size();
while (ReadToEndElement(D3MF::XmlTag::object)) {
if (xmlReader->getNodeName() == D3MF::XmlTag::mesh) {
auto mesh = ReadMesh();
mesh->mName.Set(name);
mMeshes.push_back(mesh);
meshIds.push_back(static_cast<unsigned long>(meshIdx));
++meshIdx;
}
}
node->mNumMeshes = static_cast<unsigned int>(meshIds.size());
node->mMeshes = new unsigned int[node->mNumMeshes];
std::copy(meshIds.begin(), meshIds.end(), node->mMeshes);
return node.release();
}
aiMesh *ReadMesh() {
aiMesh *mesh = new aiMesh();
while (ReadToEndElement(D3MF::XmlTag::mesh)) {
if (xmlReader->getNodeName() == D3MF::XmlTag::vertices) {
ImportVertices(mesh);
} else if (xmlReader->getNodeName() == D3MF::XmlTag::triangles) {
ImportTriangles(mesh);
}
}
return mesh;
}
void ReadMetadata() {
const std::string name = xmlReader->getAttributeValue(D3MF::XmlTag::meta_name.c_str());
xmlReader->read();
const std::string value = xmlReader->getNodeData();
if (name.empty()) {
return;
}
MetaEntry entry;
entry.name = name;
entry.value = value;
mMetaData.push_back(entry);
}
void ImportVertices(aiMesh *mesh) {
std::vector<aiVector3D> vertices;
while (ReadToEndElement(D3MF::XmlTag::vertices)) {
if (xmlReader->getNodeName() == D3MF::XmlTag::vertex) {
vertices.push_back(ReadVertex());
}
}
mesh->mNumVertices = static_cast<unsigned int>(vertices.size());
mesh->mVertices = new aiVector3D[mesh->mNumVertices];
std::copy(vertices.begin(), vertices.end(), mesh->mVertices);
}
aiVector3D ReadVertex() {
aiVector3D vertex;
vertex.x = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::x.c_str()), nullptr);
vertex.y = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::y.c_str()), nullptr);
vertex.z = ai_strtof(xmlReader->getAttributeValue(D3MF::XmlTag::z.c_str()), nullptr);
return vertex;
}
void ImportTriangles(aiMesh *mesh) {
std::vector<aiFace> faces;
while (ReadToEndElement(D3MF::XmlTag::triangles)) {
const std::string nodeName(xmlReader->getNodeName());
if (xmlReader->getNodeName() == D3MF::XmlTag::triangle) {
faces.push_back(ReadTriangle());
const char *pidToken(xmlReader->getAttributeValue(D3MF::XmlTag::p1.c_str()));
if (nullptr != pidToken) {
int matIdx(std::atoi(pidToken));
mesh->mMaterialIndex = matIdx;
}
}
}
mesh->mNumFaces = static_cast<unsigned int>(faces.size());
mesh->mFaces = new aiFace[mesh->mNumFaces];
mesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
std::copy(faces.begin(), faces.end(), mesh->mFaces);
}
aiFace ReadTriangle() {
aiFace face;
face.mNumIndices = 3;
face.mIndices = new unsigned int[face.mNumIndices];
face.mIndices[0] = static_cast<unsigned int>(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v1.c_str())));
face.mIndices[1] = static_cast<unsigned int>(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v2.c_str())));
face.mIndices[2] = static_cast<unsigned int>(std::atoi(xmlReader->getAttributeValue(D3MF::XmlTag::v3.c_str())));
return face;
}
void ReadBaseMaterials() {
std::vector<unsigned int> MatIdArray;
const char *baseMaterialId(xmlReader->getAttributeValue(D3MF::XmlTag::basematerials_id.c_str()));
if (nullptr != baseMaterialId) {
unsigned int id = std::atoi(baseMaterialId);
const size_t newMatIdx(mMatArray.size());
if (id != mActiveMatGroup) {
mActiveMatGroup = id;
MatId2MatArray::const_iterator it(mMatId2MatArray.find(id));
if (mMatId2MatArray.end() == it) {
MatIdArray.clear();
mMatId2MatArray[id] = MatIdArray;
} else {
MatIdArray = it->second;
}
}
MatIdArray.push_back(static_cast<unsigned int>(newMatIdx));
mMatId2MatArray[mActiveMatGroup] = MatIdArray;
}
while (ReadToEndElement(D3MF::XmlTag::basematerials)) {
mMatArray.push_back(readMaterialDef());
}
}
bool parseColor(const char *color, aiColor4D &diffuse) {
if (nullptr == color) {
return false;
}
//format of the color string: #RRGGBBAA or #RRGGBB (3MF Core chapter 5.1.1)
const size_t len(strlen(color));
if (9 != len && 7 != len) {
return false;
}
const char *buf(color);
if ('#' != *buf) {
return false;
}
++buf;
char comp[3] = { 0, 0, '\0' };
comp[0] = *buf;
++buf;
comp[1] = *buf;
++buf;
diffuse.r = static_cast<ai_real>(strtol(comp, NULL, 16)) / ai_real(255.0);
comp[0] = *buf;
++buf;
comp[1] = *buf;
++buf;
diffuse.g = static_cast<ai_real>(strtol(comp, NULL, 16)) / ai_real(255.0);
comp[0] = *buf;
++buf;
comp[1] = *buf;
++buf;
diffuse.b = static_cast<ai_real>(strtol(comp, NULL, 16)) / ai_real(255.0);
if (7 == len)
return true;
comp[0] = *buf;
++buf;
comp[1] = *buf;
++buf;
diffuse.a = static_cast<ai_real>(strtol(comp, NULL, 16)) / ai_real(255.0);
return true;
}
void assignDiffuseColor(aiMaterial *mat) {
const char *color = xmlReader->getAttributeValue(D3MF::XmlTag::basematerials_displaycolor.c_str());
aiColor4D diffuse;
if (parseColor(color, diffuse)) {
mat->AddProperty<aiColor4D>(&diffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
}
}
aiMaterial *readMaterialDef() {
aiMaterial *mat(nullptr);
const char *name(nullptr);
const std::string nodeName(xmlReader->getNodeName());
if (nodeName == D3MF::XmlTag::basematerials_base) {
name = xmlReader->getAttributeValue(D3MF::XmlTag::basematerials_name.c_str());
std::string stdMatName;
aiString matName;
std::string strId(to_string(mActiveMatGroup));
stdMatName += "id";
stdMatName += strId;
stdMatName += "_";
if (nullptr != name) {
stdMatName += std::string(name);
} else {
stdMatName += "basemat";
}
matName.Set(stdMatName);
mat = new aiMaterial;
mat->AddProperty(&matName, AI_MATKEY_NAME);
assignDiffuseColor(mat);
}
return mat;
}
private:
bool ReadToStartElement(const std::string &startTag) {
while (xmlReader->read()) {
const std::string &nodeName(xmlReader->getNodeName());
if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT && nodeName == startTag) {
return true;
} else if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT_END && nodeName == startTag) {
return false;
}
}
return false;
}
bool ReadToEndElement(const std::string &closeTag) {
while (xmlReader->read()) {
const std::string &nodeName(xmlReader->getNodeName());
if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT) {
return true;
} else if (xmlReader->getNodeType() == irr::io::EXN_ELEMENT_END && nodeName == closeTag) {
return false;
}
}
ASSIMP_LOG_ERROR("unexpected EOF, expected closing <" + closeTag + "> tag");
return false;
}
private:
struct MetaEntry {
std::string name;
std::string value;
};
std::vector<MetaEntry> mMetaData;
std::vector<aiMesh *> mMeshes;
MatArray mMatArray;
unsigned int mActiveMatGroup;
MatId2MatArray mMatId2MatArray;
XmlReader *xmlReader;
};
} //namespace D3MF
static const aiImporterDesc desc = {
"3mf Importer",
"",
"",
"http://3mf.io/",
aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_SupportCompressedFlavour,
0,
0,
0,
0,
"3mf"
};
D3MFImporter::D3MFImporter() :
BaseImporter() {
// empty
}
D3MFImporter::~D3MFImporter() {
// empty
}
bool D3MFImporter::CanRead(const std::string &filename, IOSystem *pIOHandler, bool checkSig) const {
const std::string extension(GetExtension(filename));
if (extension == desc.mFileExtensions) {
return true;
} else if (!extension.length() || checkSig) {
if (nullptr == pIOHandler) {
return false;
}
if (!ZipArchiveIOSystem::isZipArchive(pIOHandler, filename)) {
return false;
}
D3MF::D3MFOpcPackage opcPackage(pIOHandler, filename);
return opcPackage.validate();
}
return false;
}
void D3MFImporter::SetupProperties(const Importer * /*pImp*/) {
// empty
}
const aiImporterDesc *D3MFImporter::GetInfo() const {
return &desc;
}
void D3MFImporter::InternReadFile(const std::string &filename, aiScene *pScene, IOSystem *pIOHandler) {
D3MF::D3MFOpcPackage opcPackage(pIOHandler, filename);
std::unique_ptr<CIrrXML_IOStreamReader> xmlStream(new CIrrXML_IOStreamReader(opcPackage.RootStream()));
std::unique_ptr<D3MF::XmlReader> xmlReader(irr::io::createIrrXMLReader(xmlStream.get()));
D3MF::XmlSerializer xmlSerializer(xmlReader.get());
xmlSerializer.ImportXml(pScene);
}
} // Namespace Assimp
#endif // ASSIMP_BUILD_NO_3MF_IMPORTER
/*
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.
----------------------------------------------------------------------
*/
#ifndef AI_D3MFLOADER_H_INCLUDED
#define AI_D3MFLOADER_H_INCLUDED
#include <assimp/BaseImporter.h>
namespace Assimp {
class D3MFImporter : public BaseImporter {
public:
// BaseImporter interface
D3MFImporter();
~D3MFImporter();
bool CanRead(const std::string &pFile, IOSystem *pIOHandler, bool checkSig) const;
void SetupProperties(const Importer *pImp);
const aiImporterDesc *GetInfo() const;
protected:
void InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler);
};
} // Namespace Assimp
#endif // AI_D3MFLOADER_H_INCLUDED
/*
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.
----------------------------------------------------------------------
*/
#ifndef ASSIMP_BUILD_NO_3MF_IMPORTER
#include "D3MFOpcPackage.h"
#include <assimp/Exceptional.h>
#include <assimp/IOStream.hpp>
#include <assimp/IOSystem.hpp>
#include <assimp/DefaultLogger.hpp>
#include <assimp/ai_assert.h>
#include <assimp/ZipArchiveIOSystem.h>
#include <cstdlib>
#include <memory>
#include <vector>
#include <map>
#include <algorithm>
#include <cassert>
#include "3MFXmlTags.h"
namespace Assimp {
namespace D3MF {
// ------------------------------------------------------------------------------------------------
typedef std::shared_ptr<OpcPackageRelationship> OpcPackageRelationshipPtr;
class OpcPackageRelationshipReader {
public:
OpcPackageRelationshipReader(XmlReader* xmlReader) {
while(xmlReader->read()) {
if(xmlReader->getNodeType() == irr::io::EXN_ELEMENT &&
xmlReader->getNodeName() == XmlTag::RELS_RELATIONSHIP_CONTAINER)
{
ParseRootNode(xmlReader);
}
}
}
void ParseRootNode(XmlReader* xmlReader)
{
ParseAttributes(xmlReader);
while(xmlReader->read())
{
if(xmlReader->getNodeType() == irr::io::EXN_ELEMENT &&
xmlReader->getNodeName() == XmlTag::RELS_RELATIONSHIP_NODE)
{
ParseChildNode(xmlReader);
}
}
}
void ParseAttributes(XmlReader*) {
// empty
}
bool validateRels( OpcPackageRelationshipPtr &relPtr ) {
if ( relPtr->id.empty() || relPtr->type.empty() || relPtr->target.empty() ) {
return false;
}
return true;
}
void ParseChildNode(XmlReader* xmlReader) {
OpcPackageRelationshipPtr relPtr(new OpcPackageRelationship());
relPtr->id = xmlReader->getAttributeValueSafe(XmlTag::RELS_ATTRIB_ID.c_str());
relPtr->type = xmlReader->getAttributeValueSafe(XmlTag::RELS_ATTRIB_TYPE.c_str());
relPtr->target = xmlReader->getAttributeValueSafe(XmlTag::RELS_ATTRIB_TARGET.c_str());
if ( validateRels( relPtr ) ) {
m_relationShips.push_back( relPtr );
}
}
std::vector<OpcPackageRelationshipPtr> m_relationShips;
};
// ------------------------------------------------------------------------------------------------
D3MFOpcPackage::D3MFOpcPackage(IOSystem* pIOHandler, const std::string& rFile)
: mRootStream(nullptr)
, mZipArchive() {
mZipArchive.reset( new ZipArchiveIOSystem( pIOHandler, rFile ) );
if(!mZipArchive->isOpen()) {
throw DeadlyImportError("Failed to open file " + rFile+ ".");
}
std::vector<std::string> fileList;
mZipArchive->getFileList(fileList);
for (auto& file: fileList) {
if(file == D3MF::XmlTag::ROOT_RELATIONSHIPS_ARCHIVE) {
//PkgRelationshipReader pkgRelReader(file, archive);
ai_assert(mZipArchive->Exists(file.c_str()));
IOStream *fileStream = mZipArchive->Open(file.c_str());
ai_assert(fileStream != nullptr);
std::string rootFile = ReadPackageRootRelationship(fileStream);
if ( rootFile.size() > 0 && rootFile[ 0 ] == '/' ) {
rootFile = rootFile.substr( 1 );
if ( rootFile[ 0 ] == '/' ) {
// deal with zip-bug
rootFile = rootFile.substr( 1 );
}
}
ASSIMP_LOG_DEBUG(rootFile);
mZipArchive->Close(fileStream);
mRootStream = mZipArchive->Open(rootFile.c_str());
ai_assert( mRootStream != nullptr );
if ( nullptr == mRootStream ) {
throw DeadlyExportError( "Cannot open root-file in archive : " + rootFile );
}
} else if( file == D3MF::XmlTag::CONTENT_TYPES_ARCHIVE) {
ASSIMP_LOG_WARN_F("Ignored file of unsupported type CONTENT_TYPES_ARCHIVES",file);
} else {
ASSIMP_LOG_WARN_F("Ignored file of unknown type: ",file);
}
}
}
D3MFOpcPackage::~D3MFOpcPackage() {
mZipArchive->Close(mRootStream);
}
IOStream* D3MFOpcPackage::RootStream() const {
return mRootStream;
}
static const std::string ModelRef = "3D/3dmodel.model";
bool D3MFOpcPackage::validate() {
if ( nullptr == mRootStream || nullptr == mZipArchive ) {
return false;
}
return mZipArchive->Exists( ModelRef.c_str() );
}
std::string D3MFOpcPackage::ReadPackageRootRelationship(IOStream* stream) {
std::unique_ptr<CIrrXML_IOStreamReader> xmlStream(new CIrrXML_IOStreamReader(stream));
std::unique_ptr<XmlReader> xml(irr::io::createIrrXMLReader(xmlStream.get()));
OpcPackageRelationshipReader reader(xml.get());
auto itr = std::find_if(reader.m_relationShips.begin(), reader.m_relationShips.end(), [](const OpcPackageRelationshipPtr& rel){
return rel->type == XmlTag::PACKAGE_START_PART_RELATIONSHIP_TYPE;
});
if ( itr == reader.m_relationShips.end() ) {
throw DeadlyImportError( "Cannot find " + XmlTag::PACKAGE_START_PART_RELATIONSHIP_TYPE );
}
return (*itr)->target;
}
} // Namespace D3MF
} // Namespace Assimp
#endif //ASSIMP_BUILD_NO_3MF_IMPORTER
/*
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.
----------------------------------------------------------------------
*/
#ifndef D3MFOPCPACKAGE_H
#define D3MFOPCPACKAGE_H
#include <memory>
#include <assimp/IOSystem.hpp>
#include <assimp/irrXMLWrapper.h>
namespace Assimp {
class ZipArchiveIOSystem;
namespace D3MF {
using XmlReader = irr::io::IrrXMLReader ;
using XmlReaderPtr = std::shared_ptr<XmlReader> ;
struct OpcPackageRelationship {
std::string id;
std::string type;
std::string target;
};
class D3MFOpcPackage {
public:
D3MFOpcPackage( IOSystem* pIOHandler, const std::string& rFile );
~D3MFOpcPackage();
IOStream* RootStream() const;
bool validate();
protected:
std::string ReadPackageRootRelationship(IOStream* stream);
private:
IOStream* mRootStream;
std::unique_ptr<ZipArchiveIOSystem> mZipArchive;
};
} // Namespace D3MF
} // Namespace Assimp
#endif // D3MFOPCPACKAGE_H
/*
---------------------------------------------------------------------------
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 Implementation of the AC3D importer class */
#ifndef ASSIMP_BUILD_NO_AC_IMPORTER
// internal headers
#include "ACLoader.h"
#include "Common/Importer.h"
#include <assimp/BaseImporter.h>
#include <assimp/ParsingUtils.h>
#include <assimp/Subdivision.h>
#include <assimp/config.h>
#include <assimp/fast_atof.h>
#include <assimp/importerdesc.h>
#include <assimp/light.h>
#include <assimp/material.h>
#include <assimp/scene.h>
#include <assimp/DefaultLogger.hpp>
#include <assimp/IOSystem.hpp>
#include <assimp/Importer.hpp>
#include <memory>
using namespace Assimp;
static const aiImporterDesc desc = {
"AC3D Importer",
"",
"",
"",
aiImporterFlags_SupportTextFlavour,
0,
0,
0,
0,
"ac acc ac3d"
};
// ------------------------------------------------------------------------------------------------
// skip to the next token
inline const char *AcSkipToNextToken(const char *buffer) {
if (!SkipSpaces(&buffer)) {
ASSIMP_LOG_ERROR("AC3D: Unexpected EOF/EOL");
}
return buffer;
}
// ------------------------------------------------------------------------------------------------
// read a string (may be enclosed in double quotation marks). buffer must point to "
inline const char *AcGetString(const char *buffer, std::string &out) {
if (*buffer == '\0') {
throw DeadlyImportError("AC3D: Unexpected EOF in string");
}
++buffer;
const char *sz = buffer;
while ('\"' != *buffer) {
if (IsLineEnd(*buffer)) {
ASSIMP_LOG_ERROR("AC3D: Unexpected EOF/EOL in string");
out = "ERROR";
break;
}
++buffer;
}
if (IsLineEnd(*buffer)) {
return buffer;
}
out = std::string(sz, (unsigned int)(buffer - sz));
++buffer;
return buffer;
}
// ------------------------------------------------------------------------------------------------
// read 1 to n floats prefixed with an optional predefined identifier
template <class T>
inline const char *TAcCheckedLoadFloatArray(const char *buffer, const char *name, size_t name_length, size_t num, T *out) {
buffer = AcSkipToNextToken(buffer);
if (0 != name_length) {
if (0 != strncmp(buffer, name, name_length) || !IsSpace(buffer[name_length])) {
ASSIMP_LOG_ERROR("AC3D: Unexpexted token. " + std::string(name) + " was expected.");
return buffer;
}
buffer += name_length + 1;
}
for (unsigned int _i = 0; _i < num; ++_i) {
buffer = AcSkipToNextToken(buffer);
buffer = fast_atoreal_move<float>(buffer, ((float *)out)[_i]);
}
return buffer;
}
// ------------------------------------------------------------------------------------------------
// Constructor to be privately used by Importer
AC3DImporter::AC3DImporter() :
buffer(),
configSplitBFCull(),
configEvalSubdivision(),
mNumMeshes(),
mLights(),
mLightsCounter(0),
mGroupsCounter(0),
mPolysCounter(0),
mWorldsCounter(0) {
// nothing to be done here
}
// ------------------------------------------------------------------------------------------------
// Destructor, private as well
AC3DImporter::~AC3DImporter() {
// nothing to be done here
}
// ------------------------------------------------------------------------------------------------
// Returns whether the class can handle the format of the given file.
bool AC3DImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool checkSig) const {
std::string extension = GetExtension(pFile);
// fixme: are acc and ac3d *really* used? Some sources say they are
if (extension == "ac" || extension == "ac3d" || extension == "acc") {
return true;
}
if (!extension.length() || checkSig) {
uint32_t token = AI_MAKE_MAGIC("AC3D");
return CheckMagicToken(pIOHandler, pFile, &token, 1, 0);
}
return false;
}
// ------------------------------------------------------------------------------------------------
// Loader meta information
const aiImporterDesc *AC3DImporter::GetInfo() const {
return &desc;
}
// ------------------------------------------------------------------------------------------------
// Get a pointer to the next line from the file
bool AC3DImporter::GetNextLine() {
SkipLine(&buffer);
return SkipSpaces(&buffer);
}
// ------------------------------------------------------------------------------------------------
// Parse an object section in an AC file
void AC3DImporter::LoadObjectSection(std::vector<Object> &objects) {
if (!TokenMatch(buffer, "OBJECT", 6))
return;
SkipSpaces(&buffer);
++mNumMeshes;
objects.push_back(Object());
Object &obj = objects.back();
aiLight *light = nullptr;
if (!ASSIMP_strincmp(buffer, "light", 5)) {
// This is a light source. Add it to the list
mLights->push_back(light = new aiLight());
// Return a point light with no attenuation
light->mType = aiLightSource_POINT;
light->mColorDiffuse = light->mColorSpecular = aiColor3D(1.f, 1.f, 1.f);
light->mAttenuationConstant = 1.f;
// Generate a default name for both the light source and the node
// FIXME - what's the right way to print a size_t? Is 'zu' universally available? stick with the safe version.
light->mName.length = ::ai_snprintf(light->mName.data, MAXLEN, "ACLight_%i", static_cast<unsigned int>(mLights->size()) - 1);
obj.name = std::string(light->mName.data);
ASSIMP_LOG_DEBUG("AC3D: Light source encountered");
obj.type = Object::Light;
} else if (!ASSIMP_strincmp(buffer, "group", 5)) {
obj.type = Object::Group;
} else if (!ASSIMP_strincmp(buffer, "world", 5)) {
obj.type = Object::World;
} else
obj.type = Object::Poly;
while (GetNextLine()) {
if (TokenMatch(buffer, "kids", 4)) {
SkipSpaces(&buffer);
unsigned int num = strtoul10(buffer, &buffer);
GetNextLine();
if (num) {
// load the children of this object recursively
obj.children.reserve(num);
for (unsigned int i = 0; i < num; ++i)
LoadObjectSection(obj.children);
}
return;
} else if (TokenMatch(buffer, "name", 4)) {
SkipSpaces(&buffer);
buffer = AcGetString(buffer, obj.name);
// If this is a light source, we'll also need to store
// the name of the node in it.
if (light) {
light->mName.Set(obj.name);
}
} else if (TokenMatch(buffer, "texture", 7)) {
SkipSpaces(&buffer);
buffer = AcGetString(buffer, obj.texture);
} else if (TokenMatch(buffer, "texrep", 6)) {
SkipSpaces(&buffer);
buffer = TAcCheckedLoadFloatArray(buffer, "", 0, 2, &obj.texRepeat);
if (!obj.texRepeat.x || !obj.texRepeat.y)
obj.texRepeat = aiVector2D(1.f, 1.f);
} else if (TokenMatch(buffer, "texoff", 6)) {
SkipSpaces(&buffer);
buffer = TAcCheckedLoadFloatArray(buffer, "", 0, 2, &obj.texOffset);
} else if (TokenMatch(buffer, "rot", 3)) {
SkipSpaces(&buffer);
buffer = TAcCheckedLoadFloatArray(buffer, "", 0, 9, &obj.rotation);
} else if (TokenMatch(buffer, "loc", 3)) {
SkipSpaces(&buffer);
buffer = TAcCheckedLoadFloatArray(buffer, "", 0, 3, &obj.translation);
} else if (TokenMatch(buffer, "subdiv", 6)) {
SkipSpaces(&buffer);
obj.subDiv = strtoul10(buffer, &buffer);
} else if (TokenMatch(buffer, "crease", 6)) {
SkipSpaces(&buffer);
obj.crease = fast_atof(buffer);
} else if (TokenMatch(buffer, "numvert", 7)) {
SkipSpaces(&buffer);
unsigned int t = strtoul10(buffer, &buffer);
if (t >= AI_MAX_ALLOC(aiVector3D)) {
throw DeadlyImportError("AC3D: Too many vertices, would run out of memory");
}
obj.vertices.reserve(t);
for (unsigned int i = 0; i < t; ++i) {
if (!GetNextLine()) {
ASSIMP_LOG_ERROR("AC3D: Unexpected EOF: not all vertices have been parsed yet");
break;
} else if (!IsNumeric(*buffer)) {
ASSIMP_LOG_ERROR("AC3D: Unexpected token: not all vertices have been parsed yet");
--buffer; // make sure the line is processed a second time
break;
}
obj.vertices.push_back(aiVector3D());
aiVector3D &v = obj.vertices.back();
buffer = TAcCheckedLoadFloatArray(buffer, "", 0, 3, &v.x);
}
} else if (TokenMatch(buffer, "numsurf", 7)) {
SkipSpaces(&buffer);
bool Q3DWorkAround = false;
const unsigned int t = strtoul10(buffer, &buffer);
obj.surfaces.reserve(t);
for (unsigned int i = 0; i < t; ++i) {
GetNextLine();
if (!TokenMatch(buffer, "SURF", 4)) {
// FIX: this can occur for some files - Quick 3D for
// example writes no surf chunks
if (!Q3DWorkAround) {
ASSIMP_LOG_WARN("AC3D: SURF token was expected");
ASSIMP_LOG_DEBUG("Continuing with Quick3D Workaround enabled");
}
--buffer; // make sure the line is processed a second time
// break; --- see fix notes above
Q3DWorkAround = true;
}
SkipSpaces(&buffer);
obj.surfaces.push_back(Surface());
Surface &surf = obj.surfaces.back();
surf.flags = strtoul_cppstyle(buffer);
while (1) {
if (!GetNextLine()) {
throw DeadlyImportError("AC3D: Unexpected EOF: surface is incomplete");
}
if (TokenMatch(buffer, "mat", 3)) {
SkipSpaces(&buffer);
surf.mat = strtoul10(buffer);
} else if (TokenMatch(buffer, "refs", 4)) {
// --- see fix notes above
if (Q3DWorkAround) {
if (!surf.entries.empty()) {
buffer -= 6;
break;
}
}
SkipSpaces(&buffer);
const unsigned int m = strtoul10(buffer);
surf.entries.reserve(m);
obj.numRefs += m;
for (unsigned int k = 0; k < m; ++k) {
if (!GetNextLine()) {
ASSIMP_LOG_ERROR("AC3D: Unexpected EOF: surface references are incomplete");
break;
}
surf.entries.push_back(Surface::SurfaceEntry());
Surface::SurfaceEntry &entry = surf.entries.back();
entry.first = strtoul10(buffer, &buffer);
SkipSpaces(&buffer);
buffer = TAcCheckedLoadFloatArray(buffer, "", 0, 2, &entry.second);
}
} else {
--buffer; // make sure the line is processed a second time
break;
}
}
}
}
}
ASSIMP_LOG_ERROR("AC3D: Unexpected EOF: \'kids\' line was expected");
}
// ------------------------------------------------------------------------------------------------
// Convert a material from AC3DImporter::Material to aiMaterial
void AC3DImporter::ConvertMaterial(const Object &object,
const Material &matSrc,
aiMaterial &matDest) {
aiString s;
if (matSrc.name.length()) {
s.Set(matSrc.name);
matDest.AddProperty(&s, AI_MATKEY_NAME);
}
if (object.texture.length()) {
s.Set(object.texture);
matDest.AddProperty(&s, AI_MATKEY_TEXTURE_DIFFUSE(0));
// UV transformation
if (1.f != object.texRepeat.x || 1.f != object.texRepeat.y ||
object.texOffset.x || object.texOffset.y) {
aiUVTransform transform;
transform.mScaling = object.texRepeat;
transform.mTranslation = object.texOffset;
matDest.AddProperty(&transform, 1, AI_MATKEY_UVTRANSFORM_DIFFUSE(0));
}
}
matDest.AddProperty<aiColor3D>(&matSrc.rgb, 1, AI_MATKEY_COLOR_DIFFUSE);
matDest.AddProperty<aiColor3D>(&matSrc.amb, 1, AI_MATKEY_COLOR_AMBIENT);
matDest.AddProperty<aiColor3D>(&matSrc.emis, 1, AI_MATKEY_COLOR_EMISSIVE);
matDest.AddProperty<aiColor3D>(&matSrc.spec, 1, AI_MATKEY_COLOR_SPECULAR);
int n = -1;
if (matSrc.shin) {
n = aiShadingMode_Phong;
matDest.AddProperty<float>(&matSrc.shin, 1, AI_MATKEY_SHININESS);
} else {
n = aiShadingMode_Gouraud;
}
matDest.AddProperty<int>(&n, 1, AI_MATKEY_SHADING_MODEL);
float f = 1.f - matSrc.trans;
matDest.AddProperty<float>(&f, 1, AI_MATKEY_OPACITY);
}
// ------------------------------------------------------------------------------------------------
// Converts the loaded data to the internal verbose representation
aiNode *AC3DImporter::ConvertObjectSection(Object &object,
std::vector<aiMesh *> &meshes,
std::vector<aiMaterial *> &outMaterials,
const std::vector<Material> &materials,
aiNode *parent) {
aiNode *node = new aiNode();
node->mParent = parent;
if (object.vertices.size()) {
if (!object.surfaces.size() || !object.numRefs) {
/* " An object with 7 vertices (no surfaces, no materials defined).
This is a good way of getting point data into AC3D.
The Vertex->create convex-surface/object can be used on these
vertices to 'wrap' a 3d shape around them "
(http://www.opencity.info/html/ac3dfileformat.html)
therefore: if no surfaces are defined return point data only
*/
ASSIMP_LOG_INFO("AC3D: No surfaces defined in object definition, "
"a point list is returned");
meshes.push_back(new aiMesh());
aiMesh *mesh = meshes.back();
mesh->mNumFaces = mesh->mNumVertices = (unsigned int)object.vertices.size();
aiFace *faces = mesh->mFaces = new aiFace[mesh->mNumFaces];
aiVector3D *verts = mesh->mVertices = new aiVector3D[mesh->mNumVertices];
for (unsigned int i = 0; i < mesh->mNumVertices; ++i, ++faces, ++verts) {
*verts = object.vertices[i];
faces->mNumIndices = 1;
faces->mIndices = new unsigned int[1];
faces->mIndices[0] = i;
}
// use the primary material in this case. this should be the
// default material if all objects of the file contain points
// and no faces.
mesh->mMaterialIndex = 0;
outMaterials.push_back(new aiMaterial());
ConvertMaterial(object, materials[0], *outMaterials.back());
} else {
// need to generate one or more meshes for this object.
// find out how many different materials we have
typedef std::pair<unsigned int, unsigned int> IntPair;
typedef std::vector<IntPair> MatTable;
MatTable needMat(materials.size(), IntPair(0, 0));
std::vector<Surface>::iterator it, end = object.surfaces.end();
std::vector<Surface::SurfaceEntry>::iterator it2, end2;
for (it = object.surfaces.begin(); it != end; ++it) {
unsigned int idx = (*it).mat;
if (idx >= needMat.size()) {
ASSIMP_LOG_ERROR("AC3D: material index is out of range");
idx = 0;
}
if ((*it).entries.empty()) {
ASSIMP_LOG_WARN("AC3D: surface her zero vertex references");
}
// validate all vertex indices to make sure we won't crash here
for (it2 = (*it).entries.begin(),
end2 = (*it).entries.end();
it2 != end2; ++it2) {
if ((*it2).first >= object.vertices.size()) {
ASSIMP_LOG_WARN("AC3D: Invalid vertex reference");
(*it2).first = 0;
}
}
if (!needMat[idx].first) {
++node->mNumMeshes;
}
switch ((*it).flags & 0xf) {
// closed line
case 0x1:
needMat[idx].first += (unsigned int)(*it).entries.size();
needMat[idx].second += (unsigned int)(*it).entries.size() << 1u;
break;
// unclosed line
case 0x2:
needMat[idx].first += (unsigned int)(*it).entries.size() - 1;
needMat[idx].second += ((unsigned int)(*it).entries.size() - 1) << 1u;
break;
// 0 == polygon, else unknown
default:
if ((*it).flags & 0xf) {
ASSIMP_LOG_WARN("AC3D: The type flag of a surface is unknown");
(*it).flags &= ~(0xf);
}
// the number of faces increments by one, the number
// of vertices by surface.numref.
needMat[idx].first++;
needMat[idx].second += (unsigned int)(*it).entries.size();
};
}
unsigned int *pip = node->mMeshes = new unsigned int[node->mNumMeshes];
unsigned int mat = 0;
const size_t oldm = meshes.size();
for (MatTable::const_iterator cit = needMat.begin(), cend = needMat.end();
cit != cend; ++cit, ++mat) {
if (!(*cit).first) {
continue;
}
// allocate a new aiMesh object
*pip++ = (unsigned int)meshes.size();
aiMesh *mesh = new aiMesh();
meshes.push_back(mesh);
mesh->mMaterialIndex = static_cast<unsigned int>(outMaterials.size());
outMaterials.push_back(new aiMaterial());
ConvertMaterial(object, materials[mat], *outMaterials.back());
// allocate storage for vertices and normals
mesh->mNumFaces = (*cit).first;
if (mesh->mNumFaces == 0) {
throw DeadlyImportError("AC3D: No faces");
} else if (mesh->mNumFaces > AI_MAX_ALLOC(aiFace)) {
throw DeadlyImportError("AC3D: Too many faces, would run out of memory");
}
aiFace *faces = mesh->mFaces = new aiFace[mesh->mNumFaces];
mesh->mNumVertices = (*cit).second;
if (mesh->mNumVertices == 0) {
throw DeadlyImportError("AC3D: No vertices");
} else if (mesh->mNumVertices > AI_MAX_ALLOC(aiVector3D)) {
throw DeadlyImportError("AC3D: Too many vertices, would run out of memory");
}
aiVector3D *vertices = mesh->mVertices = new aiVector3D[mesh->mNumVertices];
unsigned int cur = 0;
// allocate UV coordinates, but only if the texture name for the
// surface is not empty
aiVector3D *uv = nullptr;
if (object.texture.length()) {
uv = mesh->mTextureCoords[0] = new aiVector3D[mesh->mNumVertices];
mesh->mNumUVComponents[0] = 2;
}
for (it = object.surfaces.begin(); it != end; ++it) {
if (mat == (*it).mat) {
const Surface &src = *it;
// closed polygon
unsigned int type = (*it).flags & 0xf;
if (!type) {
aiFace &face = *faces++;
face.mNumIndices = (unsigned int)src.entries.size();
if (0 != face.mNumIndices) {
face.mIndices = new unsigned int[face.mNumIndices];
for (unsigned int i = 0; i < face.mNumIndices; ++i, ++vertices) {
const Surface::SurfaceEntry &entry = src.entries[i];
face.mIndices[i] = cur++;
// copy vertex positions
if (static_cast<unsigned>(vertices - mesh->mVertices) >= mesh->mNumVertices) {
throw DeadlyImportError("AC3D: Invalid number of vertices");
}
*vertices = object.vertices[entry.first] + object.translation;
// copy texture coordinates
if (uv) {
uv->x = entry.second.x;
uv->y = entry.second.y;
++uv;
}
}
}
} else {
it2 = (*it).entries.begin();
// either a closed or an unclosed line
unsigned int tmp = (unsigned int)(*it).entries.size();
if (0x2 == type) --tmp;
for (unsigned int m = 0; m < tmp; ++m) {
aiFace &face = *faces++;
face.mNumIndices = 2;
face.mIndices = new unsigned int[2];
face.mIndices[0] = cur++;
face.mIndices[1] = cur++;
// copy vertex positions
if (it2 == (*it).entries.end()) {
throw DeadlyImportError("AC3D: Bad line");
}
ai_assert((*it2).first < object.vertices.size());
*vertices++ = object.vertices[(*it2).first];
// copy texture coordinates
if (uv) {
uv->x = (*it2).second.x;
uv->y = (*it2).second.y;
++uv;
}
if (0x1 == type && tmp - 1 == m) {
// if this is a closed line repeat its beginning now
it2 = (*it).entries.begin();
} else
++it2;
// second point
*vertices++ = object.vertices[(*it2).first];
if (uv) {
uv->x = (*it2).second.x;
uv->y = (*it2).second.y;
++uv;
}
}
}
}
}
}
// Now apply catmull clark subdivision if necessary. We split meshes into
// materials which is not done by AC3D during smoothing, so we need to
// collect all meshes using the same material group.
if (object.subDiv) {
if (configEvalSubdivision) {
std::unique_ptr<Subdivider> div(Subdivider::Create(Subdivider::CATMULL_CLARKE));
ASSIMP_LOG_INFO("AC3D: Evaluating subdivision surface: " + object.name);
std::vector<aiMesh *> cpy(meshes.size() - oldm, NULL);
div->Subdivide(&meshes[oldm], cpy.size(), &cpy.front(), object.subDiv, true);
std::copy(cpy.begin(), cpy.end(), meshes.begin() + oldm);
// previous meshes are deleted vy Subdivide().
} else {
ASSIMP_LOG_INFO("AC3D: Letting the subdivision surface untouched due to my configuration: " + object.name);
}
}
}
}
if (object.name.length())
node->mName.Set(object.name);
else {
// generate a name depending on the type of the node
switch (object.type) {
case Object::Group:
node->mName.length = ::ai_snprintf(node->mName.data, MAXLEN, "ACGroup_%i", mGroupsCounter++);
break;
case Object::Poly:
node->mName.length = ::ai_snprintf(node->mName.data, MAXLEN, "ACPoly_%i", mPolysCounter++);
break;
case Object::Light:
node->mName.length = ::ai_snprintf(node->mName.data, MAXLEN, "ACLight_%i", mLightsCounter++);
break;
// there shouldn't be more than one world, but we don't care
case Object::World:
node->mName.length = ::ai_snprintf(node->mName.data, MAXLEN, "ACWorld_%i", mWorldsCounter++);
break;
}
}
// setup the local transformation matrix of the object
// compute the transformation offset to the parent node
node->mTransformation = aiMatrix4x4(object.rotation);
if (object.type == Object::Group || !object.numRefs) {
node->mTransformation.a4 = object.translation.x;
node->mTransformation.b4 = object.translation.y;
node->mTransformation.c4 = object.translation.z;
}
// add children to the object
if (object.children.size()) {
node->mNumChildren = (unsigned int)object.children.size();
node->mChildren = new aiNode *[node->mNumChildren];
for (unsigned int i = 0; i < node->mNumChildren; ++i) {
node->mChildren[i] = ConvertObjectSection(object.children[i], meshes, outMaterials, materials, node);
}
}
return node;
}
// ------------------------------------------------------------------------------------------------
void AC3DImporter::SetupProperties(const Importer *pImp) {
configSplitBFCull = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_AC_SEPARATE_BFCULL, 1) ? true : false;
configEvalSubdivision = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_AC_EVAL_SUBDIVISION, 1) ? true : false;
}
// ------------------------------------------------------------------------------------------------
// Imports the given file into the given scene structure.
void AC3DImporter::InternReadFile(const std::string &pFile,
aiScene *pScene, IOSystem *pIOHandler) {
std::unique_ptr<IOStream> file(pIOHandler->Open(pFile, "rb"));
// Check whether we can read from the file
if (file.get() == nullptr) {
throw DeadlyImportError("Failed to open AC3D file " + pFile + ".");
}
// allocate storage and copy the contents of the file to a memory buffer
std::vector<char> mBuffer2;
TextFileToBuffer(file.get(), mBuffer2);
buffer = &mBuffer2[0];
mNumMeshes = 0;
mLightsCounter = mPolysCounter = mWorldsCounter = mGroupsCounter = 0;
if (::strncmp(buffer, "AC3D", 4)) {
throw DeadlyImportError("AC3D: No valid AC3D file, magic sequence not found");
}
// print the file format version to the console
unsigned int version = HexDigitToDecimal(buffer[4]);
char msg[3];
ASSIMP_itoa10(msg, 3, version);
ASSIMP_LOG_INFO_F("AC3D file format version: ", msg);
std::vector<Material> materials;
materials.reserve(5);
std::vector<Object> rootObjects;
rootObjects.reserve(5);
std::vector<aiLight *> lights;
mLights = &lights;
while (GetNextLine()) {
if (TokenMatch(buffer, "MATERIAL", 8)) {
materials.push_back(Material());
Material &mat = materials.back();
// manually parse the material ... sscanf would use the buldin atof ...
// Format: (name) rgb %f %f %f amb %f %f %f emis %f %f %f spec %f %f %f shi %d trans %f
buffer = AcSkipToNextToken(buffer);
if ('\"' == *buffer) {
buffer = AcGetString(buffer, mat.name);
buffer = AcSkipToNextToken(buffer);
}
buffer = TAcCheckedLoadFloatArray(buffer, "rgb", 3, 3, &mat.rgb);
buffer = TAcCheckedLoadFloatArray(buffer, "amb", 3, 3, &mat.amb);
buffer = TAcCheckedLoadFloatArray(buffer, "emis", 4, 3, &mat.emis);
buffer = TAcCheckedLoadFloatArray(buffer, "spec", 4, 3, &mat.spec);
buffer = TAcCheckedLoadFloatArray(buffer, "shi", 3, 1, &mat.shin);
buffer = TAcCheckedLoadFloatArray(buffer, "trans", 5, 1, &mat.trans);
}
LoadObjectSection(rootObjects);
}
if (rootObjects.empty() || !mNumMeshes) {
throw DeadlyImportError("AC3D: No meshes have been loaded");
}
if (materials.empty()) {
ASSIMP_LOG_WARN("AC3D: No material has been found");
materials.push_back(Material());
}
mNumMeshes += (mNumMeshes >> 2u) + 1;
std::vector<aiMesh *> meshes;
meshes.reserve(mNumMeshes);
std::vector<aiMaterial *> omaterials;
materials.reserve(mNumMeshes);
// generate a dummy root if there are multiple objects on the top layer
Object *root;
if (1 == rootObjects.size())
root = &rootObjects[0];
else {
root = new Object();
}
// now convert the imported stuff to our output data structure
pScene->mRootNode = ConvertObjectSection(*root, meshes, omaterials, materials);
if (1 != rootObjects.size()) {
delete root;
}
if (!::strncmp(pScene->mRootNode->mName.data, "Node", 4)) {
pScene->mRootNode->mName.Set("<AC3DWorld>");
}
// copy meshes
if (meshes.empty()) {
throw DeadlyImportError("An unknown error occurred during converting");
}
pScene->mNumMeshes = (unsigned int)meshes.size();
pScene->mMeshes = new aiMesh *[pScene->mNumMeshes];
::memcpy(pScene->mMeshes, &meshes[0], pScene->mNumMeshes * sizeof(void *));
// copy materials
pScene->mNumMaterials = (unsigned int)omaterials.size();
pScene->mMaterials = new aiMaterial *[pScene->mNumMaterials];
::memcpy(pScene->mMaterials, &omaterials[0], pScene->mNumMaterials * sizeof(void *));
// copy lights
pScene->mNumLights = (unsigned int)lights.size();
if (lights.size()) {
pScene->mLights = new aiLight *[lights.size()];
::memcpy(pScene->mLights, &lights[0], lights.size() * sizeof(void *));
}
}
#endif //!defined ASSIMP_BUILD_NO_AC_IMPORTER
/*
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 ACLoader.h
* @brief Declaration of the .ac importer class.
*/
#ifndef AI_AC3DLOADER_H_INCLUDED
#define AI_AC3DLOADER_H_INCLUDED
#include <vector>
#include <assimp/BaseImporter.h>
#include <assimp/types.h>
struct aiNode;
struct aiMesh;
struct aiMaterial;
struct aiLight;
namespace Assimp {
// ---------------------------------------------------------------------------
/** AC3D (*.ac) importer class
*/
class AC3DImporter : public BaseImporter {
public:
AC3DImporter();
~AC3DImporter();
// Represents an AC3D material
struct Material {
Material() :
rgb(0.6f, 0.6f, 0.6f), spec(1.f, 1.f, 1.f), shin(0.f), trans(0.f) {}
// base color of the material
aiColor3D rgb;
// ambient color of the material
aiColor3D amb;
// emissive color of the material
aiColor3D emis;
// specular color of the material
aiColor3D spec;
// shininess exponent
float shin;
// transparency. 0 == opaque
float trans;
// name of the material. optional.
std::string name;
};
// Represents an AC3D surface
struct Surface {
Surface() :
mat(0), flags(0) {}
unsigned int mat, flags;
typedef std::pair<unsigned int, aiVector2D> SurfaceEntry;
std::vector<SurfaceEntry> entries;
};
// Represents an AC3D object
struct Object {
Object() :
type(World), name(""), children(), texture(""), texRepeat(1.f, 1.f), texOffset(0.0f, 0.0f), rotation(), translation(), vertices(), surfaces(), numRefs(0), subDiv(0), crease() {}
// Type description
enum Type {
World = 0x0,
Poly = 0x1,
Group = 0x2,
Light = 0x4
} type;
// name of the object
std::string name;
// object children
std::vector<Object> children;
// texture to be assigned to all surfaces of the object
std::string texture;
// texture repat factors (scaling for all coordinates)
aiVector2D texRepeat, texOffset;
// rotation matrix
aiMatrix3x3 rotation;
// translation vector
aiVector3D translation;
// vertices
std::vector<aiVector3D> vertices;
// surfaces
std::vector<Surface> surfaces;
// number of indices (= num verts in verbose format)
unsigned int numRefs;
// number of subdivisions to be performed on the
// imported data
unsigned int subDiv;
// max angle limit for smoothing
float crease;
};
public:
// -------------------------------------------------------------------
/** Returns whether the class can handle the format of the given file.
* See BaseImporter::CanRead() for details.
*/
bool CanRead(const std::string &pFile, IOSystem *pIOHandler,
bool checkSig) const;
protected:
// -------------------------------------------------------------------
/** Return importer meta information.
* See #BaseImporter::GetInfo for the details */
const aiImporterDesc *GetInfo() const;
// -------------------------------------------------------------------
/** Imports the given file into the given scene structure.
* See BaseImporter::InternReadFile() for details*/
void InternReadFile(const std::string &pFile, aiScene *pScene,
IOSystem *pIOHandler);
// -------------------------------------------------------------------
/** Called prior to ReadFile().
* The function is a request to the importer to update its configuration
* basing on the Importer's configuration property list.*/
void SetupProperties(const Importer *pImp);
private:
// -------------------------------------------------------------------
/** Get the next line from the file.
* @return false if the end of the file was reached*/
bool GetNextLine();
// -------------------------------------------------------------------
/** Load the object section. This method is called recursively to
* load subobjects, the method returns after a 'kids 0' was
* encountered.
* @objects List of output objects*/
void LoadObjectSection(std::vector<Object> &objects);
// -------------------------------------------------------------------
/** Convert all objects into meshes and nodes.
* @param object Current object to work on
* @param meshes Pointer to the list of output meshes
* @param outMaterials List of output materials
* @param materials Material list
* @param Scenegraph node for the object */
aiNode *ConvertObjectSection(Object &object,
std::vector<aiMesh *> &meshes,
std::vector<aiMaterial *> &outMaterials,
const std::vector<Material> &materials,
aiNode *parent = nullptr);
// -------------------------------------------------------------------
/** Convert a material
* @param object Current object
* @param matSrc Source material description
* @param matDest Destination material to be filled */
void ConvertMaterial(const Object &object,
const Material &matSrc,
aiMaterial &matDest);
private:
// points to the next data line
const char *buffer;
// Configuration option: if enabled, up to two meshes
// are generated per material: those faces who have
// their bf cull flags set are separated.
bool configSplitBFCull;
// Configuration switch: subdivision surfaces are only
// evaluated if the value is true.
bool configEvalSubdivision;
// counts how many objects we have in the tree.
// basing on this information we can find a
// good estimate how many meshes we'll have in the final scene.
unsigned int mNumMeshes;
// current list of light sources
std::vector<aiLight *> *mLights;
// name counters
unsigned int mLightsCounter, mGroupsCounter, mPolysCounter, mWorldsCounter;
};
} // end of namespace Assimp
#endif // AI_AC3DIMPORTER_H_INC
/*
---------------------------------------------------------------------------
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 {
/// \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 = nullptr;
mUnit.clear();
mMaterial_Converted.clear();
mTexture_Converted.clear();
// Delete all elements
if (!mNodeElement_List.empty()) {
for (CAMFImporter_NodeElement *ne : mNodeElement_List) {
delete ne;
}
mNodeElement_List.clear();
}
}
AMFImporter::~AMFImporter() {
if (mReader != nullptr) 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 (CAMFImporter_NodeElement *ne : mNodeElement_List) {
if ((ne->ID == pID) && (ne->Type == pType)) {
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) {
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) {
if (pConvertedMaterial != nullptr) *pConvertedMaterial = &mat;
return true;
}
} // for(const SPP_Material& mat: mMaterial_Converted)
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("Node <" + std::string(mReader->getNodeName()) + "> has incorrect attribute \"" + pAttrName + "\".");
}
void AMFImporter::Throw_IncorrectAttrValue(const std::string &pAttrName) {
throw DeadlyImportError("Attribute \"" + pAttrName + "\" in node <" + std::string(mReader->getNodeName()) + "> has incorrect value.");
}
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("Not found node with name \"" + 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) {
static 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("Unknown node \"" + nn + "\" in " + pParentNodeName + ".");
if (!close_found) Throw_CloseNotFound(nn);
if (!skipped_before[sk_idx]) {
skipped_before[sk_idx] = true;
ASSIMP_LOG_WARN_F("Skipping node \"", nn, "\" in ", 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 != nullptr) 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.
std::unique_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
std::unique_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(nullptr);
// 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(nullptr);
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(nullptr);
// 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(nullptr);
// 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(nullptr);
// 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(nullptr);
// 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[] = { "<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
/*
---------------------------------------------------------------------------
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.hpp
/// \brief AMF-format files importer for Assimp.
/// \date 2016
/// \author smal.root@gmail.com
// Thanks to acorn89 for support.
#pragma once
#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/types.h"
#include <assimp/BaseImporter.h>
#include <assimp/irrXMLWrapper.h>
// Header files, stdlib.
#include <set>
namespace Assimp {
/// \class AMFImporter
/// Class that holding scene graph which include: geometry, metadata, materials etc.
///
/// Implementing features.
///
/// Limitations.
///
/// 1. When for texture mapping 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.
///
/// 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. 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 {
private:
struct SPP_Material;// forward declaration
/// \struct SPP_Composite
/// Data type for post-processing 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 post-processing 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.
/// 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;
};
/// Data type for post-processing step. More suitable container for texture.
struct SPP_Texture {
std::string ID;
size_t Width, Height, Depth;
bool Tiled;
char FormatHint[9];// 8 for string + 1 for terminator.
uint8_t *Data;
};
/// Data type for post-processing 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.
};
/// Clear all temporary data.
void Clear();
/***********************************************/
/************* Functions: find set *************/
/***********************************************/
/// 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;
/// 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;
/// 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;
/// 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 nullptr 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 = nullptr) 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 nullptr.
void PostprocessHelper_CreateMeshDataArray(const CAMFImporter_NodeElement_Mesh& pNodeElement, std::vector<aiVector3D>& pVertexCoordinateArray,
std::vector<CAMFImporter_NodeElement_Color*>& pVertexColorArray) const;
/// 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. Conversion: 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);
/// 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);
/// 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;
/// 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);
/// 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 nullptr.
/// \param [in] pObjectColor - pointer to colors for <object>. If color is not set then argument contain nullptr.
/// \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);
/// 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);
/// 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;
/// 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);
/// 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);
/// 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);
/// 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);
/// 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);
/// 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;
/// Check if current node have children: <node>...</node>. If not then exception will throwed.
void XML_CheckNode_MustHaveChildren();
/// Check 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; }
/// 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);
/// 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);
/// Read attribute value.
/// \param [in] pAttrIdx - attribute index (\ref mReader->getAttribute* set).
/// \return read data.
bool XML_ReadNode_GetAttrVal_AsBool(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);
/// Read attribute value.
/// \param [in] pAttrIdx - attribute index (\ref mReader->getAttribute* set).
/// \return read data.
uint32_t XML_ReadNode_GetAttrVal_AsU32(const int pAttrIdx);
/// Read node value.
/// \return read data.
float XML_ReadNode_GetVal_AsFloat();
/// Read node value.
/// \return read data.
uint32_t XML_ReadNode_GetVal_AsU32();
/// Read node value.
/// \return read data.
void XML_ReadNode_GetVal_AsString(std::string& pValue);
/// 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);
/// This function must be called when exiting from grouping node. \ref ParseHelper_Group_Begin.
void ParseHelper_Node_Exit();
/// 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);
/// 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;
/// Parse <AMF> node of the file.
void ParseNode_Root();
/// Parse <constellation> node of the file.
void ParseNode_Constellation();
/// Parse <instance> node of the file.
void ParseNode_Instance();
/// Parse <material> node of the file.
void ParseNode_Material();
/// Parse <metadata> node.
void ParseNode_Metadata();
/// Parse <object> node of the file.
void ParseNode_Object();
/// Parse <texture> node of the file.
void ParseNode_Texture();
/// Parse <coordinates> node of the file.
void ParseNode_Coordinates();
/// Parse <edge> node of the file.
void ParseNode_Edge();
/// Parse <mesh> node of the file.
void ParseNode_Mesh();
/// Parse <triangle> node of the file.
void ParseNode_Triangle();
/// Parse <vertex> node of the file.
void ParseNode_Vertex();
/// Parse <vertices> node of the file.
void ParseNode_Vertices();
/// Parse <volume> node of the file.
void ParseNode_Volume();
/// Parse <color> node of the file.
void ParseNode_Color();
/// 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:
/// Default constructor.
AMFImporter() AI_NO_EXCEPT
: mNodeElement_Cur(nullptr)
, mReader(nullptr) {
// empty
}
/// Default destructor.
~AMFImporter();
/// 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 thrown 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);
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;
AMFImporter(const AMFImporter& pScene) = delete;
AMFImporter& operator=(const AMFImporter& pScene) = delete;
private:
static const aiImporterDesc Description;
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.
};
}// namespace Assimp
#endif // INCLUDED_AI_AMF_IMPORTER_H
/*
---------------------------------------------------------------------------
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_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
/*
---------------------------------------------------------------------------
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_Macro.hpp
/// \brief Useful macrodefines.
/// \date 2016
/// \author smal.root@gmail.com
#pragma once
#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 current 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 current 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 current 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 current 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
/*
---------------------------------------------------------------------------
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_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 manually add "a == 1".
if (!read_flag[3]) {
als.Color.a = 1;
}
}
else
{
mNodeElement_Cur->Child.push_back(ne);// Add element to child list of current element
}
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();
}
else
{
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.
}
// <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;
// 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.
CAMFImporter_NodeElement *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;
// 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.
CAMFImporter_NodeElement *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
/*
---------------------------------------------------------------------------
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_Node.hpp
/// \brief Elements of scene graph.
/// \date 2016
/// \author smal.root@gmail.com
#pragma once
#ifndef INCLUDED_AI_AMF_IMPORTER_NODE_H
#define INCLUDED_AI_AMF_IMPORTER_NODE_H
// Header files, stdlib.
#include <list>
#include <string>
#include <vector>
// Header files, Assimp.
#include "assimp/types.h"
#include "assimp/scene.h"
/// \class CAMFImporter_NodeElement
/// Base class for elements of nodes.
class CAMFImporter_NodeElement {
public:
/// 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.
};
const EType Type;///< Type of element.
std::string ID;///< ID of element.
CAMFImporter_NodeElement* Parent;///< Parent element. If nullptr then this node is root.
std::list<CAMFImporter_NodeElement*> Child;///< Child elements.
public: /// Destructor, virtual..
virtual ~CAMFImporter_NodeElement() {
// empty
}
/// Disabled copy constructor and co.
CAMFImporter_NodeElement(const CAMFImporter_NodeElement& pNodeElement) = delete;
CAMFImporter_NodeElement(CAMFImporter_NodeElement&&) = delete;
CAMFImporter_NodeElement& operator=(const CAMFImporter_NodeElement& pNodeElement) = delete;
CAMFImporter_NodeElement() = delete;
protected:
/// 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)
, ID()
, Parent(pParent)
, Child() {
// empty
}
};// class IAMFImporter_NodeElement
/// \struct CAMFImporter_NodeElement_Constellation
/// A collection of objects or constellations with specific relative locations.
struct CAMFImporter_NodeElement_Constellation : public CAMFImporter_NodeElement {
/// 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 {
std::string ObjectID;///< ID of object for instantiation.
/// \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;
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Instance(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Instance, pParent)
{}
};
/// \struct CAMFImporter_NodeElement_Metadata
/// Structure that define metadata node.
struct CAMFImporter_NodeElement_Metadata : public CAMFImporter_NodeElement {
std::string Type;///< Type of "Value".
std::string Value;///< Value.
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Metadata(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Metadata, pParent)
{}
};
/// \struct CAMFImporter_NodeElement_Root
/// Structure that define root node.
struct CAMFImporter_NodeElement_Root : public CAMFImporter_NodeElement {
std::string Unit;///< The units to be used. May be "inch", "millimeter", "meter", "feet", or "micron".
std::string Version;///< Version of format.
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Root(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Root, pParent)
{}
};
/// \struct CAMFImporter_NodeElement_Color
/// Structure that define object node.
struct CAMFImporter_NodeElement_Color : public CAMFImporter_NodeElement {
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..
/// @brief Constructor.
/// @param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Color(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Color, pParent)
, Composed( false )
, Color()
, Profile() {
// empty
}
};
/// \struct CAMFImporter_NodeElement_Material
/// Structure that define material node.
struct CAMFImporter_NodeElement_Material : public CAMFImporter_NodeElement {
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Material(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Material, pParent)
{}
};
/// \struct CAMFImporter_NodeElement_Object
/// Structure that define object node.
struct CAMFImporter_NodeElement_Object : public CAMFImporter_NodeElement {
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Object(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Object, pParent)
{}
};
/// \struct CAMFImporter_NodeElement_Mesh
/// Structure that define mesh node.
struct CAMFImporter_NodeElement_Mesh : public CAMFImporter_NodeElement {
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Mesh(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Mesh, pParent)
{}
};
/// \struct CAMFImporter_NodeElement_Vertex
/// Structure that define vertex node.
struct CAMFImporter_NodeElement_Vertex : public CAMFImporter_NodeElement {
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Vertex(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Vertex, pParent)
{}
};
/// \struct CAMFImporter_NodeElement_Edge
/// Structure that define edge node.
struct CAMFImporter_NodeElement_Edge : public CAMFImporter_NodeElement {
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Edge(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Edge, pParent)
{}
};
/// \struct CAMFImporter_NodeElement_Vertices
/// Structure that define vertices node.
struct CAMFImporter_NodeElement_Vertices : public CAMFImporter_NodeElement {
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Vertices(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Vertices, pParent)
{}
};
/// \struct CAMFImporter_NodeElement_Volume
/// Structure that define volume node.
struct CAMFImporter_NodeElement_Volume : public CAMFImporter_NodeElement {
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.
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Volume(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Volume, pParent)
{}
};
/// \struct CAMFImporter_NodeElement_Coordinates
/// Structure that define coordinates node.
struct CAMFImporter_NodeElement_Coordinates : public CAMFImporter_NodeElement
{
aiVector3D Coordinate;///< Coordinate.
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Coordinates(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Coordinates, pParent)
{}
};
/// \struct CAMFImporter_NodeElement_TexMap
/// Structure that define texture coordinates node.
struct CAMFImporter_NodeElement_TexMap : public CAMFImporter_NodeElement {
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.
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_TexMap(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_TexMap, pParent)
, TextureCoordinate{}
, TextureID_R()
, TextureID_G()
, TextureID_B()
, TextureID_A() {
// empty
}
};
/// \struct CAMFImporter_NodeElement_Triangle
/// Structure that define triangle node.
struct CAMFImporter_NodeElement_Triangle : public CAMFImporter_NodeElement {
size_t V[3];///< Triangle vertices.
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Triangle(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Triangle, pParent) {
// empty
}
};
/// Structure that define texture node.
struct CAMFImporter_NodeElement_Texture : public CAMFImporter_NodeElement {
size_t Width, Height, Depth;///< Size of the texture.
std::vector<uint8_t> Data;///< Data of the texture.
bool Tiled;
/// Constructor.
/// \param [in] pParent - pointer to parent node.
CAMFImporter_NodeElement_Texture(CAMFImporter_NodeElement* pParent)
: CAMFImporter_NodeElement(ENET_Texture, pParent)
, Width( 0 )
, Height( 0 )
, Depth( 0 )
, Data()
, Tiled( false ){
// empty
}
};
#endif // INCLUDED_AI_AMF_IMPORTER_NODE_H
/*
---------------------------------------------------------------------------
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_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 <assimp/SceneCombiner.h>
#include <assimp/StandardShapes.h>
#include <assimp/StringUtils.h>
// Header files, stdlib.
#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.empty()) {
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 = nullptr;
size_t col_idx;
// All data stored in "vertices", search for it.
for (CAMFImporter_NodeElement *ne_child : pNodeElement.Child) {
if (ne_child->Type == CAMFImporter_NodeElement::ENET_Vertices) vn = (CAMFImporter_NodeElement_Vertices *)ne_child;
}
// If "vertices" not found then no work for us.
if (vn == nullptr) 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 (CAMFImporter_NodeElement *vn_child : vn->Child) {
// vertices, colors
if (vn_child->Type == CAMFImporter_NodeElement::ENET_Vertex) {
// by default clear color for current vertex
pVertexColorArray[col_idx] = nullptr;
for (CAMFImporter_NodeElement *vtx : vn_child->Child) {
if (vtx->Type == CAMFImporter_NodeElement::ENET_Coordinates) {
pVertexCoordinateArray.push_back(((CAMFImporter_NodeElement_Coordinates *)vtx)->Coordinate);
continue;
}
if (vtx->Type == CAMFImporter_NodeElement::ENET_Color) {
pVertexColorArray[col_idx] = (CAMFImporter_NodeElement_Color *)vtx;
continue;
}
} // for(CAMFImporter_NodeElement* vtx: vn_child->Child)
col_idx++;
} // if(vn_child->Type == CAMFImporter_NodeElement::ENET_Vertex)
} // for(CAMFImporter_NodeElement* vn_child: vn->Child)
}
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) {
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.
//
CAMFImporter_NodeElement_Texture *src_texture[4]{ nullptr };
std::vector<CAMFImporter_NodeElement_Texture *> src_texture_4check;
SPP_Texture converted_texture;
{ // find all specified source textures
CAMFImporter_NodeElement *t_tex;
// R
if (!pID_R.empty()) {
if (!Find_NodeElement(pID_R, CAMFImporter_NodeElement::ENET_Texture, &t_tex)) Throw_ID_NotFound(pID_R);
src_texture[0] = (CAMFImporter_NodeElement_Texture *)t_tex;
src_texture_4check.push_back((CAMFImporter_NodeElement_Texture *)t_tex);
} else {
src_texture[0] = nullptr;
}
// G
if (!pID_G.empty()) {
if (!Find_NodeElement(pID_G, CAMFImporter_NodeElement::ENET_Texture, &t_tex)) Throw_ID_NotFound(pID_G);
src_texture[1] = (CAMFImporter_NodeElement_Texture *)t_tex;
src_texture_4check.push_back((CAMFImporter_NodeElement_Texture *)t_tex);
} else {
src_texture[1] = nullptr;
}
// B
if (!pID_B.empty()) {
if (!Find_NodeElement(pID_B, CAMFImporter_NodeElement::ENET_Texture, &t_tex)) Throw_ID_NotFound(pID_B);
src_texture[2] = (CAMFImporter_NodeElement_Texture *)t_tex;
src_texture_4check.push_back((CAMFImporter_NodeElement_Texture *)t_tex);
} else {
src_texture[2] = nullptr;
}
// A
if (!pID_A.empty()) {
if (!Find_NodeElement(pID_A, CAMFImporter_NodeElement::ENET_Texture, &t_tex)) Throw_ID_NotFound(pID_A);
src_texture[3] = (CAMFImporter_NodeElement_Texture *)t_tex;
src_texture_4check.push_back((CAMFImporter_NodeElement_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 (size_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[5] = '8';
if (!pID_B.empty()) converted_texture.FormatHint[6] = '8';
if (!pID_A.empty()) converted_texture.FormatHint[7] = '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() && nullptr != src_texture[0]) {
tex_size += src_texture[0]->Data.size();
step++, off_g++, off_b++;
}
if (!pID_G.empty() && nullptr != src_texture[1]) {
tex_size += src_texture[1]->Data.size();
step++, off_b++;
}
if (!pID_B.empty() && nullptr != src_texture[2]) {
tex_size += src_texture[2]->Data.size();
step++;
}
if (!pID_A.empty() && nullptr != src_texture[3]) {
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++) {
CAMFImporter_NodeElement_Texture *tex = src_texture[pSrcTexNum];
ai_assert(tex);
converted_texture.Data[idx_target] = tex->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.empty()) return;
do {
SComplexFace face_start = pInputList.front();
std::list<SComplexFace> face_list_cur;
for (std::list<SComplexFace>::iterator it = pInputList.begin(), it_end = pInputList.end(); 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.empty()) pOutputList_Separated.push_back(face_list_cur);
} while (!pInputList.empty());
}
void AMFImporter::Postprocess_AddMetadata(const std::list<CAMFImporter_NodeElement_Metadata *> &metadataList, aiNode &sceneNode) const {
if (!metadataList.empty()) {
if (sceneNode.mMetaData != nullptr) throw DeadlyImportError("Postprocess. MetaData member in node are not nullptr. Something went wrong.");
// copy collected metadata to output node.
sceneNode.mMetaData = aiMetadata::Alloc(static_cast<unsigned int>(metadataList.size()));
size_t meta_idx(0);
for (const CAMFImporter_NodeElement_Metadata &metadata : metadataList) {
sceneNode.mMetaData->Set(static_cast<unsigned int>(meta_idx++), metadata.Type, aiString(metadata.Value));
}
} // if(!metadataList.empty())
}
void AMFImporter::Postprocess_BuildNodeAndObject(const CAMFImporter_NodeElement_Object &pNodeElement, std::list<aiMesh *> &pMeshList, aiNode **pSceneNode) {
CAMFImporter_NodeElement_Color *object_color = nullptr;
// create new aiNode and set name as <object> has.
*pSceneNode = new aiNode;
(*pSceneNode)->mName = pNodeElement.ID;
// read mesh and color
for (const CAMFImporter_NodeElement *ne_child : pNodeElement.Child) {
std::vector<aiVector3D> vertex_arr;
std::vector<CAMFImporter_NodeElement_Color *> color_arr;
// color for object
if (ne_child->Type == CAMFImporter_NodeElement::ENET_Color) object_color = (CAMFImporter_NodeElement_Color *)ne_child;
if (ne_child->Type == CAMFImporter_NodeElement::ENET_Mesh) {
// Create arrays from children of mesh: vertices.
PostprocessHelper_CreateMeshDataArray(*((CAMFImporter_NodeElement_Mesh *)ne_child), vertex_arr, color_arr);
// Use this arrays as a source when creating every aiMesh
Postprocess_BuildMeshSet(*((CAMFImporter_NodeElement_Mesh *)ne_child), vertex_arr, color_arr, object_color, pMeshList, **pSceneNode);
}
} // for(const CAMFImporter_NodeElement* ne_child: pNodeElement)
}
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) {
std::list<unsigned int> mesh_idx;
// all data stored in "volume", search for it.
for (const CAMFImporter_NodeElement *ne_child : pNodeElement.Child) {
const CAMFImporter_NodeElement_Color *ne_volume_color = nullptr;
const SPP_Material *cur_mat = nullptr;
if (ne_child->Type == CAMFImporter_NodeElement::ENET_Volume) {
/******************* Get faces *******************/
const CAMFImporter_NodeElement_Volume *ne_volume = reinterpret_cast<const CAMFImporter_NodeElement_Volume *>(ne_child);
std::list<SComplexFace> complex_faces_list; // List of the faces of the volume.
std::list<std::list<SComplexFace>> 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 CAMFImporter_NodeElement *ne_volume_child : ne_volume->Child) {
// color for volume
if (ne_volume_child->Type == CAMFImporter_NodeElement::ENET_Color) {
ne_volume_color = reinterpret_cast<const CAMFImporter_NodeElement_Color *>(ne_volume_child);
} else if (ne_volume_child->Type == CAMFImporter_NodeElement::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 CAMFImporter_NodeElement *ne_triangle_child : tri_al.Child) {
if (ne_triangle_child->Type == CAMFImporter_NodeElement::ENET_Color)
complex_face.Color = reinterpret_cast<const CAMFImporter_NodeElement_Color *>(ne_triangle_child);
else if (ne_triangle_child->Type == CAMFImporter_NodeElement::ENET_TexMap)
complex_face.TexMap = reinterpret_cast<const CAMFImporter_NodeElement_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] = static_cast<unsigned int>(tri_al.V[0]);
complex_face.Face.mIndices[1] = static_cast<unsigned int>(tri_al.V[1]);
complex_face.Face.mIndices[2] = static_cast<unsigned int>(tri_al.V[2]);
complex_faces_list.push_back(complex_face);
}
} // for(const CAMFImporter_NodeElement* 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 (std::list<SComplexFace> &face_list_cur : complex_faces_toplist) {
auto VertexIndex_GetMinimal = [](const std::list<SComplexFace> &pFaceList, const size_t *pBiggerThan) -> size_t {
size_t rv = 0;
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 std::list<SComplexFace>& pFaceList, const size_t* pBiggerThan) -> size_t
auto VertexIndex_Replace = [](std::list<SComplexFace> &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] = static_cast<unsigned int>(pIdx_To);
}
}
}; // auto VertexIndex_Replace = [](std::list<SComplexFace>& 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] != nullptr)) 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 = static_cast<unsigned int>(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.
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 transferred,
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] = static_cast<unsigned int>(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;
idx_vert_used = new bool[VertexCount_Max * 2];
for (size_t i = 0, i_e = VertexCount_Max * 2; i < i_e; i++)
idx_vert_used[i] = false;
// This ID's will be used when set materials ID in scene.
tmesh->mMaterialIndex = static_cast<unsigned int>(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] = static_cast<unsigned int>(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)
delete[] idx_vert_used;
// shrink array
texcoord_arr.resize(idx_vert_new);
} // if(face_list_cur.front().TexMap != nullptr)
//
// copy collected data to mesh
//
tmesh->mNumVertices = static_cast<unsigned int>(vert_arr.size());
tmesh->mVertices = new aiVector3D[tmesh->mNumVertices];
tmesh->mColors[0] = new aiColor4D[tmesh->mNumVertices];
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(static_cast<unsigned int>(pMeshList.size()));
pMeshList.push_back(tmesh);
} // for(const std::list<SComplexFace>& face_list_cur: complex_faces_toplist)
} // if(ne_child->Type == CAMFImporter_NodeElement::ENET_Volume)
} // for(const CAMFImporter_NodeElement* ne_child: pNodeElement.Child)
// if meshes was created then assign new indices with current aiNode
if (!mesh_idx.empty()) {
std::list<unsigned int>::const_iterator mit = mesh_idx.begin();
pSceneNode.mNumMeshes = static_cast<unsigned int>(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 (const CAMFImporter_NodeElement *mat_child : pMaterial.Child) {
if (mat_child->Type == CAMFImporter_NodeElement::ENET_Color) {
new_mat.Color = (CAMFImporter_NodeElement_Color *)mat_child;
} else if (mat_child->Type == CAMFImporter_NodeElement::ENET_Metadata) {
new_mat.Metadata.push_back((CAMFImporter_NodeElement_Metadata *)mat_child);
}
} // for(const CAMFImporter_NodeElement* mat_child; pMaterial.Child)
// 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 through children and search for instances of another objects, constellations.
for (const CAMFImporter_NodeElement *ne : pConstellation.Child) {
aiMatrix4x4 tmat;
aiNode *t_node;
aiNode *found_node;
if (ne->Type == CAMFImporter_NodeElement::ENET_Metadata) continue;
if (ne->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 *)ne);
// find referenced object
if (!Find_ConvertedNode(als.ObjectID, pNodeList, &found_node)) Throw_ID_NotFound(als.ObjectID);
// create node for applying 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(const CAMFImporter_NodeElement* ne: pConstellation.Child)
// copy found aiNode's as children
if (ch_node.empty()) throw DeadlyImportError("<constellation> must have at least one <instance>.");
size_t ch_idx = 0;
con_node->mNumChildren = static_cast<unsigned int>(ch_node.size());
con_node->mChildren = new aiNode *[con_node->mNumChildren];
for (aiNode *node : ch_node)
con_node->mChildren[ch_idx++] = node;
// 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 = nullptr;
pScene->mFlags |= AI_SCENE_FLAGS_ALLOW_SHARED;
// search for root(<amf>) element
CAMFImporter_NodeElement *root_el = nullptr;
for (CAMFImporter_NodeElement *ne : mNodeElement_List) {
if (ne->Type != CAMFImporter_NodeElement::ENET_Root) continue;
root_el = ne;
break;
} // for(const CAMFImporter_NodeElement* ne: mNodeElement_List)
// Check if root element are found.
if (root_el == nullptr) throw DeadlyImportError("Root(<amf>) element not found.");
// after that walk through 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 (const CAMFImporter_NodeElement *root_child : root_el->Child) {
if (root_child->Type == CAMFImporter_NodeElement::ENET_Material) Postprocess_BuildMaterial(*((CAMFImporter_NodeElement_Material *)root_child));
}
// After "appearance" nodes we must read <object> because it will be used in <constellation> -> <instance>.
//
// 3. <object>
for (const CAMFImporter_NodeElement *root_child : root_el->Child) {
if (root_child->Type == CAMFImporter_NodeElement::ENET_Object) {
aiNode *tnode = nullptr;
// 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 *)root_child), mesh_list, &tnode);
if (tnode != nullptr) node_list.push_back(tnode);
}
} // for(const CAMFImporter_NodeElement* root_child: root_el->Child)
// And finally read rest of nodes.
//
for (const CAMFImporter_NodeElement *root_child : root_el->Child) {
// 4. <constellation>
if (root_child->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 *)root_child), node_list);
}
// 5, <metadata>
if (root_child->Type == CAMFImporter_NodeElement::ENET_Metadata) meta_list.push_back((CAMFImporter_NodeElement_Metadata *)root_child);
} // for(const CAMFImporter_NodeElement* root_child: root_el->Child)
// 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 through 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) != nullptr) {
// 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.empty()) {
std::list<aiNode *>::const_iterator nl_it = node_list.begin();
pScene->mRootNode->mNumChildren = static_cast<unsigned int>(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.empty()) {
std::list<aiMesh *>::const_iterator ml_it = mesh_list.begin();
pScene->mNumMeshes = static_cast<unsigned int>(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 = static_cast<unsigned int>(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 = static_cast<unsigned int>(tex_convd.Width);
pScene->mTextures[idx]->mHeight = static_cast<unsigned int>(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 = static_cast<unsigned int>(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 + 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 through children of root and collect data
} // namespace Assimp
#endif // !ASSIMP_BUILD_NO_AMF_IMPORTER
/*
---------------------------------------------------------------------------
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 ASELoader.cpp
* @brief Implementation of the ASE importer class
*/
#ifndef ASSIMP_BUILD_NO_ASE_IMPORTER
#ifndef ASSIMP_BUILD_NO_3DS_IMPORTER
// internal headers
#include "ASELoader.h"
#include "Common/TargetAnimation.h"
#include <assimp/SkeletonMeshBuilder.h>
#include <assimp/StringComparison.h>
#include <assimp/importerdesc.h>
#include <assimp/scene.h>
#include <assimp/DefaultLogger.hpp>
#include <assimp/IOSystem.hpp>
#include <assimp/Importer.hpp>
#include <memory>
// utilities
#include <assimp/fast_atof.h>
using namespace Assimp;
using namespace Assimp::ASE;
static const aiImporterDesc desc = {
"ASE Importer",
"",
"",
"Similar to 3DS but text-encoded",
aiImporterFlags_SupportTextFlavour,
0,
0,
0,
0,
"ase ask"
};
// ------------------------------------------------------------------------------------------------
// Constructor to be privately used by Importer
ASEImporter::ASEImporter() :
mParser(), mBuffer(), pcScene(), configRecomputeNormals(), noSkeletonMesh() {
// empty
}
// ------------------------------------------------------------------------------------------------
// Destructor, private as well
ASEImporter::~ASEImporter() {
// empty
}
// ------------------------------------------------------------------------------------------------
// Returns whether the class can handle the format of the given file.
bool ASEImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool cs) const {
// check file extension
const std::string extension = GetExtension(pFile);
if (extension == "ase" || extension == "ask") {
return true;
}
if ((!extension.length() || cs) && pIOHandler) {
const char *tokens[] = { "*3dsmax_asciiexport" };
return SearchFileHeaderForToken(pIOHandler, pFile, tokens, 1);
}
return false;
}
// ------------------------------------------------------------------------------------------------
// Loader meta information
const aiImporterDesc *ASEImporter::GetInfo() const {
return &desc;
}
// ------------------------------------------------------------------------------------------------
// Setup configuration options
void ASEImporter::SetupProperties(const Importer *pImp) {
configRecomputeNormals = (pImp->GetPropertyInteger(
AI_CONFIG_IMPORT_ASE_RECONSTRUCT_NORMALS, 1) ?
true :
false);
noSkeletonMesh = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_NO_SKELETON_MESHES, 0) != 0;
}
// ------------------------------------------------------------------------------------------------
// Imports the given file into the given scene structure.
void ASEImporter::InternReadFile(const std::string &pFile,
aiScene *pScene, IOSystem *pIOHandler) {
std::unique_ptr<IOStream> file(pIOHandler->Open(pFile, "rb"));
// Check whether we can read from the file
if (file.get() == nullptr) {
throw DeadlyImportError("Failed to open ASE file " + pFile + ".");
}
// Allocate storage and copy the contents of the file to a memory buffer
std::vector<char> mBuffer2;
TextFileToBuffer(file.get(), mBuffer2);
this->mBuffer = &mBuffer2[0];
this->pcScene = pScene;
// ------------------------------------------------------------------
// Guess the file format by looking at the extension
// ASC is considered to be the older format 110,
// ASE is the actual version 200 (that is currently written by max)
// ------------------------------------------------------------------
unsigned int defaultFormat;
std::string::size_type s = pFile.length() - 1;
switch (pFile.c_str()[s]) {
case 'C':
case 'c':
defaultFormat = AI_ASE_OLD_FILE_FORMAT;
break;
default:
defaultFormat = AI_ASE_NEW_FILE_FORMAT;
};
// Construct an ASE parser and parse the file
ASE::Parser parser(mBuffer, defaultFormat);
mParser = &parser;
mParser->Parse();
//------------------------------------------------------------------
// Check whether we god at least one mesh. If we did - generate
// materials and copy meshes.
// ------------------------------------------------------------------
if (!mParser->m_vMeshes.empty()) {
// If absolutely no material has been loaded from the file
// we need to generate a default material
GenerateDefaultMaterial();
// process all meshes
bool tookNormals = false;
std::vector<aiMesh *> avOutMeshes;
avOutMeshes.reserve(mParser->m_vMeshes.size() * 2);
for (std::vector<ASE::Mesh>::iterator i = mParser->m_vMeshes.begin(); i != mParser->m_vMeshes.end(); ++i) {
if ((*i).bSkip) {
continue;
}
BuildUniqueRepresentation(*i);
// Need to generate proper vertex normals if necessary
if (GenerateNormals(*i)) {
tookNormals = true;
}
// Convert all meshes to aiMesh objects
ConvertMeshes(*i, avOutMeshes);
}
if (tookNormals) {
ASSIMP_LOG_DEBUG("ASE: Taking normals from the file. Use "
"the AI_CONFIG_IMPORT_ASE_RECONSTRUCT_NORMALS setting if you "
"experience problems");
}
// Now build the output mesh list. Remove dummies
pScene->mNumMeshes = (unsigned int)avOutMeshes.size();
aiMesh **pp = pScene->mMeshes = new aiMesh *[pScene->mNumMeshes];
for (std::vector<aiMesh *>::const_iterator i = avOutMeshes.begin(); i != avOutMeshes.end(); ++i) {
if (!(*i)->mNumFaces) {
continue;
}
*pp++ = *i;
}
pScene->mNumMeshes = (unsigned int)(pp - pScene->mMeshes);
// Build final material indices (remove submaterials and setup
// the final list)
BuildMaterialIndices();
}
// ------------------------------------------------------------------
// Copy all scene graph nodes - lights, cameras, dummies and meshes
// into one huge list.
//------------------------------------------------------------------
std::vector<BaseNode *> nodes;
nodes.reserve(mParser->m_vMeshes.size() + mParser->m_vLights.size() + mParser->m_vCameras.size() + mParser->m_vDummies.size());
// Lights
for (auto &light : mParser->m_vLights)
nodes.push_back(&light);
// Cameras
for (auto &camera : mParser->m_vCameras)
nodes.push_back(&camera);
// Meshes
for (auto &mesh : mParser->m_vMeshes)
nodes.push_back(&mesh);
// Dummies
for (auto &dummy : mParser->m_vDummies)
nodes.push_back(&dummy);
// build the final node graph
BuildNodes(nodes);
// build output animations
BuildAnimations(nodes);
// build output cameras
BuildCameras();
// build output lights
BuildLights();
// ------------------------------------------------------------------
// If we have no meshes use the SkeletonMeshBuilder helper class
// to build a mesh for the animation skeleton
// FIXME: very strange results
// ------------------------------------------------------------------
if (!pScene->mNumMeshes) {
pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
if (!noSkeletonMesh) {
SkeletonMeshBuilder skeleton(pScene);
}
}
}
// ------------------------------------------------------------------------------------------------
void ASEImporter::GenerateDefaultMaterial() {
ai_assert(nullptr != mParser);
bool bHas = false;
for (std::vector<ASE::Mesh>::iterator i = mParser->m_vMeshes.begin(); i != mParser->m_vMeshes.end(); ++i) {
if ((*i).bSkip) continue;
if (ASE::Face::DEFAULT_MATINDEX == (*i).iMaterialIndex) {
(*i).iMaterialIndex = (unsigned int)mParser->m_vMaterials.size();
bHas = true;
}
}
if (bHas || mParser->m_vMaterials.empty()) {
// add a simple material without submaterials to the parser's list
mParser->m_vMaterials.push_back(ASE::Material(AI_DEFAULT_MATERIAL_NAME));
ASE::Material &mat = mParser->m_vMaterials.back();
mat.mDiffuse = aiColor3D(0.6f, 0.6f, 0.6f);
mat.mSpecular = aiColor3D(1.0f, 1.0f, 1.0f);
mat.mAmbient = aiColor3D(0.05f, 0.05f, 0.05f);
mat.mShading = Discreet3DS::Gouraud;
}
}
// ------------------------------------------------------------------------------------------------
void ASEImporter::BuildAnimations(const std::vector<BaseNode *> &nodes) {
// check whether we have at least one mesh which has animations
std::vector<ASE::BaseNode *>::const_iterator i = nodes.begin();
unsigned int iNum = 0;
for (; i != nodes.end(); ++i) {
// TODO: Implement Bezier & TCB support
if ((*i)->mAnim.mPositionType != ASE::Animation::TRACK) {
ASSIMP_LOG_WARN("ASE: Position controller uses Bezier/TCB keys. "
"This is not supported.");
}
if ((*i)->mAnim.mRotationType != ASE::Animation::TRACK) {
ASSIMP_LOG_WARN("ASE: Rotation controller uses Bezier/TCB keys. "
"This is not supported.");
}
if ((*i)->mAnim.mScalingType != ASE::Animation::TRACK) {
ASSIMP_LOG_WARN("ASE: Position controller uses Bezier/TCB keys. "
"This is not supported.");
}
// We compare against 1 here - firstly one key is not
// really an animation and secondly MAX writes dummies
// that represent the node transformation.
if ((*i)->mAnim.akeyPositions.size() > 1 || (*i)->mAnim.akeyRotations.size() > 1 || (*i)->mAnim.akeyScaling.size() > 1) {
++iNum;
}
if ((*i)->mTargetAnim.akeyPositions.size() > 1 && is_not_qnan((*i)->mTargetPosition.x)) {
++iNum;
}
}
if (iNum) {
// Generate a new animation channel and setup everything for it
pcScene->mNumAnimations = 1;
pcScene->mAnimations = new aiAnimation *[1];
aiAnimation *pcAnim = pcScene->mAnimations[0] = new aiAnimation();
pcAnim->mNumChannels = iNum;
pcAnim->mChannels = new aiNodeAnim *[iNum];
pcAnim->mTicksPerSecond = mParser->iFrameSpeed * mParser->iTicksPerFrame;
iNum = 0;
// Now iterate through all meshes and collect all data we can find
for (i = nodes.begin(); i != nodes.end(); ++i) {
ASE::BaseNode *me = *i;
if (me->mTargetAnim.akeyPositions.size() > 1 && is_not_qnan(me->mTargetPosition.x)) {
// Generate an extra channel for the camera/light target.
// BuildNodes() does also generate an extra node, named
// <baseName>.Target.
aiNodeAnim *nd = pcAnim->mChannels[iNum++] = new aiNodeAnim();
nd->mNodeName.Set(me->mName + ".Target");
// If there is no input position channel we will need
// to supply the default position from the node's
// local transformation matrix.
/*TargetAnimationHelper helper;
if (me->mAnim.akeyPositions.empty())
{
aiMatrix4x4& mat = (*i)->mTransform;
helper.SetFixedMainAnimationChannel(aiVector3D(
mat.a4, mat.b4, mat.c4));
}
else helper.SetMainAnimationChannel (&me->mAnim.akeyPositions);
helper.SetTargetAnimationChannel (&me->mTargetAnim.akeyPositions);
helper.Process(&me->mTargetAnim.akeyPositions);*/
// Allocate the key array and fill it
nd->mNumPositionKeys = (unsigned int)me->mTargetAnim.akeyPositions.size();
nd->mPositionKeys = new aiVectorKey[nd->mNumPositionKeys];
::memcpy(nd->mPositionKeys, &me->mTargetAnim.akeyPositions[0],
nd->mNumPositionKeys * sizeof(aiVectorKey));
}
if (me->mAnim.akeyPositions.size() > 1 || me->mAnim.akeyRotations.size() > 1 || me->mAnim.akeyScaling.size() > 1) {
// Begin a new node animation channel for this node
aiNodeAnim *nd = pcAnim->mChannels[iNum++] = new aiNodeAnim();
nd->mNodeName.Set(me->mName);
// copy position keys
if (me->mAnim.akeyPositions.size() > 1) {
// Allocate the key array and fill it
nd->mNumPositionKeys = (unsigned int)me->mAnim.akeyPositions.size();
nd->mPositionKeys = new aiVectorKey[nd->mNumPositionKeys];
::memcpy(nd->mPositionKeys, &me->mAnim.akeyPositions[0],
nd->mNumPositionKeys * sizeof(aiVectorKey));
}
// copy rotation keys
if (me->mAnim.akeyRotations.size() > 1) {
// Allocate the key array and fill it
nd->mNumRotationKeys = (unsigned int)me->mAnim.akeyRotations.size();
nd->mRotationKeys = new aiQuatKey[nd->mNumRotationKeys];
// --------------------------------------------------------------------
// Rotation keys are offsets to the previous keys.
// We have the quaternion representations of all
// of them, so we just need to concatenate all
// (unit-length) quaternions to get the absolute
// rotations.
// Rotation keys are ABSOLUTE for older files
// --------------------------------------------------------------------
aiQuaternion cur;
for (unsigned int a = 0; a < nd->mNumRotationKeys; ++a) {
aiQuatKey q = me->mAnim.akeyRotations[a];
if (mParser->iFileFormat > 110) {
cur = (a ? cur * q.mValue : q.mValue);
q.mValue = cur.Normalize();
}
nd->mRotationKeys[a] = q;
// need this to get to Assimp quaternion conventions
nd->mRotationKeys[a].mValue.w *= -1.f;
}
}
// copy scaling keys
if (me->mAnim.akeyScaling.size() > 1) {
// Allocate the key array and fill it
nd->mNumScalingKeys = (unsigned int)me->mAnim.akeyScaling.size();
nd->mScalingKeys = new aiVectorKey[nd->mNumScalingKeys];
::memcpy(nd->mScalingKeys, &me->mAnim.akeyScaling[0],
nd->mNumScalingKeys * sizeof(aiVectorKey));
}
}
}
}
}
// ------------------------------------------------------------------------------------------------
// Build output cameras
void ASEImporter::BuildCameras() {
if (!mParser->m_vCameras.empty()) {
pcScene->mNumCameras = (unsigned int)mParser->m_vCameras.size();
pcScene->mCameras = new aiCamera *[pcScene->mNumCameras];
for (unsigned int i = 0; i < pcScene->mNumCameras; ++i) {
aiCamera *out = pcScene->mCameras[i] = new aiCamera();
ASE::Camera &in = mParser->m_vCameras[i];
// copy members
out->mClipPlaneFar = in.mFar;
out->mClipPlaneNear = (in.mNear ? in.mNear : 0.1f);
out->mHorizontalFOV = in.mFOV;
out->mName.Set(in.mName);
}
}
}
// ------------------------------------------------------------------------------------------------
// Build output lights
void ASEImporter::BuildLights() {
if (!mParser->m_vLights.empty()) {
pcScene->mNumLights = (unsigned int)mParser->m_vLights.size();
pcScene->mLights = new aiLight *[pcScene->mNumLights];
for (unsigned int i = 0; i < pcScene->mNumLights; ++i) {
aiLight *out = pcScene->mLights[i] = new aiLight();
ASE::Light &in = mParser->m_vLights[i];
// The direction is encoded in the transformation matrix of the node.
// In 3DS MAX the light source points into negative Z direction if
// the node transformation is the identity.
out->mDirection = aiVector3D(0.f, 0.f, -1.f);
out->mName.Set(in.mName);
switch (in.mLightType) {
case ASE::Light::TARGET:
out->mType = aiLightSource_SPOT;
out->mAngleInnerCone = AI_DEG_TO_RAD(in.mAngle);
out->mAngleOuterCone = (in.mFalloff ? AI_DEG_TO_RAD(in.mFalloff) : out->mAngleInnerCone);
break;
case ASE::Light::DIRECTIONAL:
out->mType = aiLightSource_DIRECTIONAL;
break;
default:
//case ASE::Light::OMNI:
out->mType = aiLightSource_POINT;
break;
};
out->mColorDiffuse = out->mColorSpecular = in.mColor * in.mIntensity;
}
}
}
// ------------------------------------------------------------------------------------------------
void ASEImporter::AddNodes(const std::vector<BaseNode *> &nodes,
aiNode *pcParent, const char *szName) {
aiMatrix4x4 m;
AddNodes(nodes, pcParent, szName, m);
}
// ------------------------------------------------------------------------------------------------
// Add meshes to a given node
void ASEImporter::AddMeshes(const ASE::BaseNode *snode, aiNode *node) {
for (unsigned int i = 0; i < pcScene->mNumMeshes; ++i) {
// Get the name of the mesh (the mesh instance has been temporarily stored in the third vertex color)
const aiMesh *pcMesh = pcScene->mMeshes[i];
const ASE::Mesh *mesh = (const ASE::Mesh *)pcMesh->mColors[2];
if (mesh == snode) {
++node->mNumMeshes;
}
}
if (node->mNumMeshes) {
node->mMeshes = new unsigned int[node->mNumMeshes];
for (unsigned int i = 0, p = 0; i < pcScene->mNumMeshes; ++i) {
const aiMesh *pcMesh = pcScene->mMeshes[i];
const ASE::Mesh *mesh = (const ASE::Mesh *)pcMesh->mColors[2];
if (mesh == snode) {
node->mMeshes[p++] = i;
// Transform all vertices of the mesh back into their local space ->
// at the moment they are pretransformed
aiMatrix4x4 m = mesh->mTransform;
m.Inverse();
aiVector3D *pvCurPtr = pcMesh->mVertices;
const aiVector3D *pvEndPtr = pvCurPtr + pcMesh->mNumVertices;
while (pvCurPtr != pvEndPtr) {
*pvCurPtr = m * (*pvCurPtr);
pvCurPtr++;
}
// Do the same for the normal vectors, if we have them.
// As always, inverse transpose.
if (pcMesh->mNormals) {
aiMatrix3x3 m3 = aiMatrix3x3(mesh->mTransform);
m3.Transpose();
pvCurPtr = pcMesh->mNormals;
pvEndPtr = pvCurPtr + pcMesh->mNumVertices;
while (pvCurPtr != pvEndPtr) {
*pvCurPtr = m3 * (*pvCurPtr);
pvCurPtr++;
}
}
}
}
}
}
// ------------------------------------------------------------------------------------------------
// Add child nodes to a given parent node
void ASEImporter::AddNodes(const std::vector<BaseNode *> &nodes,
aiNode *pcParent, const char *szName,
const aiMatrix4x4 &mat) {
const size_t len = szName ? ::strlen(szName) : 0;
ai_assert(4 <= AI_MAX_NUMBER_OF_COLOR_SETS);
// Receives child nodes for the pcParent node
std::vector<aiNode *> apcNodes;
// Now iterate through all nodes in the scene and search for one
// which has *us* as parent.
for (std::vector<BaseNode *>::const_iterator it = nodes.begin(), end = nodes.end(); it != end; ++it) {
const BaseNode *snode = *it;
if (szName) {
if (len != snode->mParent.length() || ::strcmp(szName, snode->mParent.c_str()))
continue;
} else if (snode->mParent.length())
continue;
(*it)->mProcessed = true;
// Allocate a new node and add it to the output data structure
apcNodes.push_back(new aiNode());
aiNode *node = apcNodes.back();
node->mName.Set((snode->mName.length() ? snode->mName.c_str() : "Unnamed_Node"));
node->mParent = pcParent;
// Setup the transformation matrix of the node
aiMatrix4x4 mParentAdjust = mat;
mParentAdjust.Inverse();
node->mTransformation = mParentAdjust * snode->mTransform;
// Add sub nodes - prevent stack overflow due to recursive parenting
if (node->mName != node->mParent->mName && node->mName != node->mParent->mParent->mName) {
AddNodes(nodes, node, node->mName.data, snode->mTransform);
}
// Further processing depends on the type of the node
if (snode->mType == ASE::BaseNode::Mesh) {
// If the type of this node is "Mesh" we need to search
// the list of output meshes in the data structure for
// all those that belonged to this node once. This is
// slightly inconvinient here and a better solution should
// be used when this code is refactored next.
AddMeshes(snode, node);
} else if (is_not_qnan(snode->mTargetPosition.x)) {
// If this is a target camera or light we generate a small
// child node which marks the position of the camera
// target (the direction information is contained in *this*
// node's animation track but the exact target position
// would be lost otherwise)
if (!node->mNumChildren) {
node->mChildren = new aiNode *[1];
}
aiNode *nd = new aiNode();
nd->mName.Set(snode->mName + ".Target");
nd->mTransformation.a4 = snode->mTargetPosition.x - snode->mTransform.a4;
nd->mTransformation.b4 = snode->mTargetPosition.y - snode->mTransform.b4;
nd->mTransformation.c4 = snode->mTargetPosition.z - snode->mTransform.c4;
nd->mParent = node;
// The .Target node is always the first child node
for (unsigned int m = 0; m < node->mNumChildren; ++m)
node->mChildren[m + 1] = node->mChildren[m];
node->mChildren[0] = nd;
node->mNumChildren++;
// What we did is so great, it is at least worth a debug message
ASSIMP_LOG_DEBUG("ASE: Generating separate target node (" + snode->mName + ")");
}
}
// Allocate enough space for the child nodes
// We allocate one slot more in case this is a target camera/light
pcParent->mNumChildren = (unsigned int)apcNodes.size();
if (pcParent->mNumChildren) {
pcParent->mChildren = new aiNode *[apcNodes.size() + 1 /* PLUS ONE !!! */];
// now build all nodes for our nice new children
for (unsigned int p = 0; p < apcNodes.size(); ++p)
pcParent->mChildren[p] = apcNodes[p];
}
return;
}
// ------------------------------------------------------------------------------------------------
// Build the output node graph
void ASEImporter::BuildNodes(std::vector<BaseNode *> &nodes) {
ai_assert(nullptr != pcScene);
// allocate the one and only root node
aiNode *root = pcScene->mRootNode = new aiNode();
root->mName.Set("<ASERoot>");
// Setup the coordinate system transformation
pcScene->mRootNode->mNumChildren = 1;
pcScene->mRootNode->mChildren = new aiNode *[1];
aiNode *ch = pcScene->mRootNode->mChildren[0] = new aiNode();
ch->mParent = root;
// Change the transformation matrix of all nodes
for (BaseNode *node : nodes) {
aiMatrix4x4 &m = node->mTransform;
m.Transpose(); // row-order vs column-order
}
// add all nodes
AddNodes(nodes, ch, nullptr);
// now iterate through al nodes and find those that have not yet
// been added to the nodegraph (= their parent could not be recognized)
std::vector<const BaseNode *> aiList;
for (std::vector<BaseNode *>::iterator it = nodes.begin(), end = nodes.end(); it != end; ++it) {
if ((*it)->mProcessed) {
continue;
}
// check whether our parent is known
bool bKnowParent = false;
// search the list another time, starting *here* and try to find out whether
// there is a node that references *us* as a parent
for (std::vector<BaseNode *>::const_iterator it2 = nodes.begin(); it2 != end; ++it2) {
if (it2 == it) {
continue;
}
if ((*it2)->mName == (*it)->mParent) {
bKnowParent = true;
break;
}
}
if (!bKnowParent) {
aiList.push_back(*it);
}
}
// Are there ane orphaned nodes?
if (!aiList.empty()) {
std::vector<aiNode *> apcNodes;
apcNodes.reserve(aiList.size() + pcScene->mRootNode->mNumChildren);
for (unsigned int i = 0; i < pcScene->mRootNode->mNumChildren; ++i)
apcNodes.push_back(pcScene->mRootNode->mChildren[i]);
delete[] pcScene->mRootNode->mChildren;
for (std::vector<const BaseNode *>::/*const_*/ iterator i = aiList.begin(); i != aiList.end(); ++i) {
const ASE::BaseNode *src = *i;
// The parent is not known, so we can assume that we must add
// this node to the root node of the whole scene
aiNode *pcNode = new aiNode();
pcNode->mParent = pcScene->mRootNode;
pcNode->mName.Set(src->mName);
AddMeshes(src, pcNode);
AddNodes(nodes, pcNode, pcNode->mName.data);
apcNodes.push_back(pcNode);
}
// Regenerate our output array
pcScene->mRootNode->mChildren = new aiNode *[apcNodes.size()];
for (unsigned int i = 0; i < apcNodes.size(); ++i)
pcScene->mRootNode->mChildren[i] = apcNodes[i];
pcScene->mRootNode->mNumChildren = (unsigned int)apcNodes.size();
}
// Reset the third color set to nullptr - we used this field to store a temporary pointer
for (unsigned int i = 0; i < pcScene->mNumMeshes; ++i)
pcScene->mMeshes[i]->mColors[2] = nullptr;
// The root node should not have at least one child or the file is valid
if (!pcScene->mRootNode->mNumChildren) {
throw DeadlyImportError("ASE: No nodes loaded. The file is either empty or corrupt");
}
// Now rotate the whole scene 90 degrees around the x axis to convert to internal coordinate system
pcScene->mRootNode->mTransformation = aiMatrix4x4(1.f, 0.f, 0.f, 0.f,
0.f, 0.f, 1.f, 0.f, 0.f, -1.f, 0.f, 0.f, 0.f, 0.f, 0.f, 1.f);
}
// ------------------------------------------------------------------------------------------------
// Convert the imported data to the internal verbose representation
void ASEImporter::BuildUniqueRepresentation(ASE::Mesh &mesh) {
// allocate output storage
std::vector<aiVector3D> mPositions;
std::vector<aiVector3D> amTexCoords[AI_MAX_NUMBER_OF_TEXTURECOORDS];
std::vector<aiColor4D> mVertexColors;
std::vector<aiVector3D> mNormals;
std::vector<BoneVertex> mBoneVertices;
unsigned int iSize = (unsigned int)mesh.mFaces.size() * 3;
mPositions.resize(iSize);
// optional texture coordinates
for (unsigned int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
if (!mesh.amTexCoords[i].empty()) {
amTexCoords[i].resize(iSize);
}
}
// optional vertex colors
if (!mesh.mVertexColors.empty()) {
mVertexColors.resize(iSize);
}
// optional vertex normals (vertex normals can simply be copied)
if (!mesh.mNormals.empty()) {
mNormals.resize(iSize);
}
// bone vertices. There is no need to change the bone list
if (!mesh.mBoneVertices.empty()) {
mBoneVertices.resize(iSize);
}
// iterate through all faces in the mesh
unsigned int iCurrent = 0, fi = 0;
for (std::vector<ASE::Face>::iterator i = mesh.mFaces.begin(); i != mesh.mFaces.end(); ++i, ++fi) {
for (unsigned int n = 0; n < 3; ++n, ++iCurrent) {
mPositions[iCurrent] = mesh.mPositions[(*i).mIndices[n]];
// add texture coordinates
for (unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++c) {
if (mesh.amTexCoords[c].empty()) break;
amTexCoords[c][iCurrent] = mesh.amTexCoords[c][(*i).amUVIndices[c][n]];
}
// add vertex colors
if (!mesh.mVertexColors.empty()) {
mVertexColors[iCurrent] = mesh.mVertexColors[(*i).mColorIndices[n]];
}
// add normal vectors
if (!mesh.mNormals.empty()) {
mNormals[iCurrent] = mesh.mNormals[fi * 3 + n];
mNormals[iCurrent].Normalize();
}
// handle bone vertices
if ((*i).mIndices[n] < mesh.mBoneVertices.size()) {
// (sometimes this will cause bone verts to be duplicated
// however, I' quite sure Schrompf' JoinVerticesStep
// will fix that again ...)
mBoneVertices[iCurrent] = mesh.mBoneVertices[(*i).mIndices[n]];
}
(*i).mIndices[n] = iCurrent;
}
}
// replace the old arrays
mesh.mNormals = mNormals;
mesh.mPositions = mPositions;
mesh.mVertexColors = mVertexColors;
for (unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++c)
mesh.amTexCoords[c] = amTexCoords[c];
}
// ------------------------------------------------------------------------------------------------
// Copy a texture from the ASE structs to the output material
void CopyASETexture(aiMaterial &mat, ASE::Texture &texture, aiTextureType type) {
// Setup the texture name
aiString tex;
tex.Set(texture.mMapName);
mat.AddProperty(&tex, AI_MATKEY_TEXTURE(type, 0));
// Setup the texture blend factor
if (is_not_qnan(texture.mTextureBlend))
mat.AddProperty<ai_real>(&texture.mTextureBlend, 1, AI_MATKEY_TEXBLEND(type, 0));
// Setup texture UV transformations
mat.AddProperty<ai_real>(&texture.mOffsetU, 5, AI_MATKEY_UVTRANSFORM(type, 0));
}
// ------------------------------------------------------------------------------------------------
// Convert from ASE material to output material
void ASEImporter::ConvertMaterial(ASE::Material &mat) {
// LARGE TODO: Much code her is copied from 3DS ... join them maybe?
// Allocate the output material
mat.pcInstance = new aiMaterial();
// At first add the base ambient color of the
// scene to the material
mat.mAmbient.r += mParser->m_clrAmbient.r;
mat.mAmbient.g += mParser->m_clrAmbient.g;
mat.mAmbient.b += mParser->m_clrAmbient.b;
aiString name;
name.Set(mat.mName);
mat.pcInstance->AddProperty(&name, AI_MATKEY_NAME);
// material colors
mat.pcInstance->AddProperty(&mat.mAmbient, 1, AI_MATKEY_COLOR_AMBIENT);
mat.pcInstance->AddProperty(&mat.mDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
mat.pcInstance->AddProperty(&mat.mSpecular, 1, AI_MATKEY_COLOR_SPECULAR);
mat.pcInstance->AddProperty(&mat.mEmissive, 1, AI_MATKEY_COLOR_EMISSIVE);
// shininess
if (0.0f != mat.mSpecularExponent && 0.0f != mat.mShininessStrength) {
mat.pcInstance->AddProperty(&mat.mSpecularExponent, 1, AI_MATKEY_SHININESS);
mat.pcInstance->AddProperty(&mat.mShininessStrength, 1, AI_MATKEY_SHININESS_STRENGTH);
}
// If there is no shininess, we can disable phong lighting
else if (D3DS::Discreet3DS::Metal == mat.mShading ||
D3DS::Discreet3DS::Phong == mat.mShading ||
D3DS::Discreet3DS::Blinn == mat.mShading) {
mat.mShading = D3DS::Discreet3DS::Gouraud;
}
// opacity
mat.pcInstance->AddProperty<ai_real>(&mat.mTransparency, 1, AI_MATKEY_OPACITY);
// Two sided rendering?
if (mat.mTwoSided) {
int i = 1;
mat.pcInstance->AddProperty<int>(&i, 1, AI_MATKEY_TWOSIDED);
}
// shading mode
aiShadingMode eShading = aiShadingMode_NoShading;
switch (mat.mShading) {
case D3DS::Discreet3DS::Flat:
eShading = aiShadingMode_Flat;
break;
case D3DS::Discreet3DS::Phong:
eShading = aiShadingMode_Phong;
break;
case D3DS::Discreet3DS::Blinn:
eShading = aiShadingMode_Blinn;
break;
// I don't know what "Wire" shading should be,
// assume it is simple lambertian diffuse (L dot N) shading
case D3DS::Discreet3DS::Wire: {
// set the wireframe flag
unsigned int iWire = 1;
mat.pcInstance->AddProperty<int>((int *)&iWire, 1, AI_MATKEY_ENABLE_WIREFRAME);
}
case D3DS::Discreet3DS::Gouraud:
eShading = aiShadingMode_Gouraud;
break;
case D3DS::Discreet3DS::Metal:
eShading = aiShadingMode_CookTorrance;
break;
}
mat.pcInstance->AddProperty<int>((int *)&eShading, 1, AI_MATKEY_SHADING_MODEL);
// DIFFUSE texture
if (mat.sTexDiffuse.mMapName.length() > 0)
CopyASETexture(*mat.pcInstance, mat.sTexDiffuse, aiTextureType_DIFFUSE);
// SPECULAR texture
if (mat.sTexSpecular.mMapName.length() > 0)
CopyASETexture(*mat.pcInstance, mat.sTexSpecular, aiTextureType_SPECULAR);
// AMBIENT texture
if (mat.sTexAmbient.mMapName.length() > 0)
CopyASETexture(*mat.pcInstance, mat.sTexAmbient, aiTextureType_AMBIENT);
// OPACITY texture
if (mat.sTexOpacity.mMapName.length() > 0)
CopyASETexture(*mat.pcInstance, mat.sTexOpacity, aiTextureType_OPACITY);
// EMISSIVE texture
if (mat.sTexEmissive.mMapName.length() > 0)
CopyASETexture(*mat.pcInstance, mat.sTexEmissive, aiTextureType_EMISSIVE);
// BUMP texture
if (mat.sTexBump.mMapName.length() > 0)
CopyASETexture(*mat.pcInstance, mat.sTexBump, aiTextureType_HEIGHT);
// SHININESS texture
if (mat.sTexShininess.mMapName.length() > 0)
CopyASETexture(*mat.pcInstance, mat.sTexShininess, aiTextureType_SHININESS);
// store the name of the material itself, too
if (mat.mName.length() > 0) {
aiString tex;
tex.Set(mat.mName);
mat.pcInstance->AddProperty(&tex, AI_MATKEY_NAME);
}
return;
}
// ------------------------------------------------------------------------------------------------
// Build output meshes
void ASEImporter::ConvertMeshes(ASE::Mesh &mesh, std::vector<aiMesh *> &avOutMeshes) {
// validate the material index of the mesh
if (mesh.iMaterialIndex >= mParser->m_vMaterials.size()) {
mesh.iMaterialIndex = (unsigned int)mParser->m_vMaterials.size() - 1;
ASSIMP_LOG_WARN("Material index is out of range");
}
// If the material the mesh is assigned to is consisting of submeshes, split it
if (!mParser->m_vMaterials[mesh.iMaterialIndex].avSubMaterials.empty()) {
std::vector<ASE::Material> vSubMaterials = mParser->m_vMaterials[mesh.iMaterialIndex].avSubMaterials;
std::vector<unsigned int> *aiSplit = new std::vector<unsigned int>[vSubMaterials.size()];
// build a list of all faces per sub-material
for (unsigned int i = 0; i < mesh.mFaces.size(); ++i) {
// check range
if (mesh.mFaces[i].iMaterial >= vSubMaterials.size()) {
ASSIMP_LOG_WARN("Submaterial index is out of range");
// use the last material instead
aiSplit[vSubMaterials.size() - 1].push_back(i);
} else
aiSplit[mesh.mFaces[i].iMaterial].push_back(i);
}
// now generate submeshes
for (unsigned int p = 0; p < vSubMaterials.size(); ++p) {
if (!aiSplit[p].empty()) {
aiMesh *p_pcOut = new aiMesh();
p_pcOut->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
// let the sub material index
p_pcOut->mMaterialIndex = p;
// we will need this material
mParser->m_vMaterials[mesh.iMaterialIndex].avSubMaterials[p].bNeed = true;
// store the real index here ... color channel 3
p_pcOut->mColors[3] = (aiColor4D *)(uintptr_t)mesh.iMaterialIndex;
// store a pointer to the mesh in color channel 2
p_pcOut->mColors[2] = (aiColor4D *)&mesh;
avOutMeshes.push_back(p_pcOut);
// convert vertices
p_pcOut->mNumVertices = (unsigned int)aiSplit[p].size() * 3;
p_pcOut->mNumFaces = (unsigned int)aiSplit[p].size();
// receive output vertex weights
std::vector<std::pair<unsigned int, float>> *avOutputBones = nullptr;
if (!mesh.mBones.empty()) {
avOutputBones = new std::vector<std::pair<unsigned int, float>>[mesh.mBones.size()];
}
// allocate enough storage for faces
p_pcOut->mFaces = new aiFace[p_pcOut->mNumFaces];
unsigned int iBase = 0, iIndex;
if (p_pcOut->mNumVertices) {
p_pcOut->mVertices = new aiVector3D[p_pcOut->mNumVertices];
p_pcOut->mNormals = new aiVector3D[p_pcOut->mNumVertices];
for (unsigned int q = 0; q < aiSplit[p].size(); ++q) {
iIndex = aiSplit[p][q];
p_pcOut->mFaces[q].mIndices = new unsigned int[3];
p_pcOut->mFaces[q].mNumIndices = 3;
for (unsigned int t = 0; t < 3; ++t, ++iBase) {
const uint32_t iIndex2 = mesh.mFaces[iIndex].mIndices[t];
p_pcOut->mVertices[iBase] = mesh.mPositions[iIndex2];
p_pcOut->mNormals[iBase] = mesh.mNormals[iIndex2];
// convert bones, if existing
if (!mesh.mBones.empty()) {
ai_assert(avOutputBones);
// check whether there is a vertex weight for this vertex index
if (iIndex2 < mesh.mBoneVertices.size()) {
for (std::vector<std::pair<int, float>>::const_iterator
blubb = mesh.mBoneVertices[iIndex2].mBoneWeights.begin();
blubb != mesh.mBoneVertices[iIndex2].mBoneWeights.end(); ++blubb) {
// NOTE: illegal cases have already been filtered out
avOutputBones[(*blubb).first].push_back(std::pair<unsigned int, float>(
iBase, (*blubb).second));
}
}
}
p_pcOut->mFaces[q].mIndices[t] = iBase;
}
}
}
// convert texture coordinates (up to AI_MAX_NUMBER_OF_TEXTURECOORDS sets supported)
for (unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++c) {
if (!mesh.amTexCoords[c].empty()) {
p_pcOut->mTextureCoords[c] = new aiVector3D[p_pcOut->mNumVertices];
iBase = 0;
for (unsigned int q = 0; q < aiSplit[p].size(); ++q) {
iIndex = aiSplit[p][q];
for (unsigned int t = 0; t < 3; ++t) {
p_pcOut->mTextureCoords[c][iBase++] = mesh.amTexCoords[c][mesh.mFaces[iIndex].mIndices[t]];
}
}
// Setup the number of valid vertex components
p_pcOut->mNumUVComponents[c] = mesh.mNumUVComponents[c];
}
}
// Convert vertex colors (only one set supported)
if (!mesh.mVertexColors.empty()) {
p_pcOut->mColors[0] = new aiColor4D[p_pcOut->mNumVertices];
iBase = 0;
for (unsigned int q = 0; q < aiSplit[p].size(); ++q) {
iIndex = aiSplit[p][q];
for (unsigned int t = 0; t < 3; ++t) {
p_pcOut->mColors[0][iBase++] = mesh.mVertexColors[mesh.mFaces[iIndex].mIndices[t]];
}
}
}
// Copy bones
if (!mesh.mBones.empty()) {
p_pcOut->mNumBones = 0;
for (unsigned int mrspock = 0; mrspock < mesh.mBones.size(); ++mrspock)
if (!avOutputBones[mrspock].empty()) p_pcOut->mNumBones++;
p_pcOut->mBones = new aiBone *[p_pcOut->mNumBones];
aiBone **pcBone = p_pcOut->mBones;
for (unsigned int mrspock = 0; mrspock < mesh.mBones.size(); ++mrspock) {
if (!avOutputBones[mrspock].empty()) {
// we will need this bone. add it to the output mesh and
// add all per-vertex weights
aiBone *pc = *pcBone = new aiBone();
pc->mName.Set(mesh.mBones[mrspock].mName);
pc->mNumWeights = (unsigned int)avOutputBones[mrspock].size();
pc->mWeights = new aiVertexWeight[pc->mNumWeights];
for (unsigned int captainkirk = 0; captainkirk < pc->mNumWeights; ++captainkirk) {
const std::pair<unsigned int, float> &ref = avOutputBones[mrspock][captainkirk];
pc->mWeights[captainkirk].mVertexId = ref.first;
pc->mWeights[captainkirk].mWeight = ref.second;
}
++pcBone;
}
}
// delete allocated storage
delete[] avOutputBones;
}
}
}
// delete storage
delete[] aiSplit;
} else {
// Otherwise we can simply copy the data to one output mesh
// This codepath needs less memory and uses fast memcpy()s
// to do the actual copying. So I think it is worth the
// effort here.
aiMesh *p_pcOut = new aiMesh();
p_pcOut->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
// set an empty sub material index
p_pcOut->mMaterialIndex = ASE::Face::DEFAULT_MATINDEX;
mParser->m_vMaterials[mesh.iMaterialIndex].bNeed = true;
// store the real index here ... in color channel 3
p_pcOut->mColors[3] = (aiColor4D *)(uintptr_t)mesh.iMaterialIndex;
// store a pointer to the mesh in color channel 2
p_pcOut->mColors[2] = (aiColor4D *)&mesh;
avOutMeshes.push_back(p_pcOut);
// If the mesh hasn't faces or vertices, there are two cases
// possible: 1. the model is invalid. 2. This is a dummy
// helper object which we are going to remove later ...
if (mesh.mFaces.empty() || mesh.mPositions.empty()) {
return;
}
// convert vertices
p_pcOut->mNumVertices = (unsigned int)mesh.mPositions.size();
p_pcOut->mNumFaces = (unsigned int)mesh.mFaces.size();
// allocate enough storage for faces
p_pcOut->mFaces = new aiFace[p_pcOut->mNumFaces];
// copy vertices
p_pcOut->mVertices = new aiVector3D[mesh.mPositions.size()];
memcpy(p_pcOut->mVertices, &mesh.mPositions[0],
mesh.mPositions.size() * sizeof(aiVector3D));
// copy normals
p_pcOut->mNormals = new aiVector3D[mesh.mNormals.size()];
memcpy(p_pcOut->mNormals, &mesh.mNormals[0],
mesh.mNormals.size() * sizeof(aiVector3D));
// copy texture coordinates
for (unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++c) {
if (!mesh.amTexCoords[c].empty()) {
p_pcOut->mTextureCoords[c] = new aiVector3D[mesh.amTexCoords[c].size()];
memcpy(p_pcOut->mTextureCoords[c], &mesh.amTexCoords[c][0],
mesh.amTexCoords[c].size() * sizeof(aiVector3D));
// setup the number of valid vertex components
p_pcOut->mNumUVComponents[c] = mesh.mNumUVComponents[c];
}
}
// copy vertex colors
if (!mesh.mVertexColors.empty()) {
p_pcOut->mColors[0] = new aiColor4D[mesh.mVertexColors.size()];
memcpy(p_pcOut->mColors[0], &mesh.mVertexColors[0],
mesh.mVertexColors.size() * sizeof(aiColor4D));
}
// copy faces
for (unsigned int iFace = 0; iFace < p_pcOut->mNumFaces; ++iFace) {
p_pcOut->mFaces[iFace].mNumIndices = 3;
p_pcOut->mFaces[iFace].mIndices = new unsigned int[3];
// copy indices
p_pcOut->mFaces[iFace].mIndices[0] = mesh.mFaces[iFace].mIndices[0];
p_pcOut->mFaces[iFace].mIndices[1] = mesh.mFaces[iFace].mIndices[1];
p_pcOut->mFaces[iFace].mIndices[2] = mesh.mFaces[iFace].mIndices[2];
}
// copy vertex bones
if (!mesh.mBones.empty() && !mesh.mBoneVertices.empty()) {
std::vector<std::vector<aiVertexWeight>> avBonesOut(mesh.mBones.size());
// find all vertex weights for this bone
unsigned int quak = 0;
for (std::vector<BoneVertex>::const_iterator harrypotter = mesh.mBoneVertices.begin();
harrypotter != mesh.mBoneVertices.end(); ++harrypotter, ++quak) {
for (std::vector<std::pair<int, float>>::const_iterator
ronaldweasley = (*harrypotter).mBoneWeights.begin();
ronaldweasley != (*harrypotter).mBoneWeights.end(); ++ronaldweasley) {
aiVertexWeight weight;
weight.mVertexId = quak;
weight.mWeight = (*ronaldweasley).second;
avBonesOut[(*ronaldweasley).first].push_back(weight);
}
}
// now build a final bone list
p_pcOut->mNumBones = 0;
for (unsigned int jfkennedy = 0; jfkennedy < mesh.mBones.size(); ++jfkennedy)
if (!avBonesOut[jfkennedy].empty()) p_pcOut->mNumBones++;
p_pcOut->mBones = new aiBone *[p_pcOut->mNumBones];
aiBone **pcBone = p_pcOut->mBones;
for (unsigned int jfkennedy = 0; jfkennedy < mesh.mBones.size(); ++jfkennedy) {
if (!avBonesOut[jfkennedy].empty()) {
aiBone *pc = *pcBone = new aiBone();
pc->mName.Set(mesh.mBones[jfkennedy].mName);
pc->mNumWeights = (unsigned int)avBonesOut[jfkennedy].size();
pc->mWeights = new aiVertexWeight[pc->mNumWeights];
::memcpy(pc->mWeights, &avBonesOut[jfkennedy][0],
sizeof(aiVertexWeight) * pc->mNumWeights);
++pcBone;
}
}
}
}
}
// ------------------------------------------------------------------------------------------------
// Setup proper material indices and build output materials
void ASEImporter::BuildMaterialIndices() {
ai_assert(nullptr != pcScene);
// iterate through all materials and check whether we need them
for (unsigned int iMat = 0; iMat < mParser->m_vMaterials.size(); ++iMat) {
ASE::Material &mat = mParser->m_vMaterials[iMat];
if (mat.bNeed) {
// Convert it to the aiMaterial layout
ConvertMaterial(mat);
++pcScene->mNumMaterials;
}
for (unsigned int iSubMat = 0; iSubMat < mat.avSubMaterials.size(); ++iSubMat) {
ASE::Material &submat = mat.avSubMaterials[iSubMat];
if (submat.bNeed) {
// Convert it to the aiMaterial layout
ConvertMaterial(submat);
++pcScene->mNumMaterials;
}
}
}
// allocate the output material array
pcScene->mMaterials = new aiMaterial *[pcScene->mNumMaterials];
D3DS::Material **pcIntMaterials = new D3DS::Material *[pcScene->mNumMaterials];
unsigned int iNum = 0;
for (unsigned int iMat = 0; iMat < mParser->m_vMaterials.size(); ++iMat) {
ASE::Material &mat = mParser->m_vMaterials[iMat];
if (mat.bNeed) {
ai_assert(nullptr != mat.pcInstance);
pcScene->mMaterials[iNum] = mat.pcInstance;
// Store the internal material, too
pcIntMaterials[iNum] = &mat;
// Iterate through all meshes and search for one which is using
// this top-level material index
for (unsigned int iMesh = 0; iMesh < pcScene->mNumMeshes; ++iMesh) {
aiMesh *mesh = pcScene->mMeshes[iMesh];
if (ASE::Face::DEFAULT_MATINDEX == mesh->mMaterialIndex &&
iMat == (uintptr_t)mesh->mColors[3]) {
mesh->mMaterialIndex = iNum;
mesh->mColors[3] = nullptr;
}
}
iNum++;
}
for (unsigned int iSubMat = 0; iSubMat < mat.avSubMaterials.size(); ++iSubMat) {
ASE::Material &submat = mat.avSubMaterials[iSubMat];
if (submat.bNeed) {
ai_assert(nullptr != submat.pcInstance);
pcScene->mMaterials[iNum] = submat.pcInstance;
// Store the internal material, too
pcIntMaterials[iNum] = &submat;
// Iterate through all meshes and search for one which is using
// this sub-level material index
for (unsigned int iMesh = 0; iMesh < pcScene->mNumMeshes; ++iMesh) {
aiMesh *mesh = pcScene->mMeshes[iMesh];
if (iSubMat == mesh->mMaterialIndex && iMat == (uintptr_t)mesh->mColors[3]) {
mesh->mMaterialIndex = iNum;
mesh->mColors[3] = nullptr;
}
}
iNum++;
}
}
}
// Delete our temporary array
delete[] pcIntMaterials;
}
// ------------------------------------------------------------------------------------------------
// Generate normal vectors basing on smoothing groups
bool ASEImporter::GenerateNormals(ASE::Mesh &mesh) {
if (!mesh.mNormals.empty() && !configRecomputeNormals) {
// Check whether there are only uninitialized normals. If there are
// some, skip all normals from the file and compute them on our own
for (std::vector<aiVector3D>::const_iterator qq = mesh.mNormals.begin(); qq != mesh.mNormals.end(); ++qq) {
if ((*qq).x || (*qq).y || (*qq).z) {
return true;
}
}
}
// The array is reused.
ComputeNormalsWithSmoothingsGroups<ASE::Face>(mesh);
return false;
}
#endif // ASSIMP_BUILD_NO_3DS_IMPORTER
#endif // !! ASSIMP_BUILD_NO_BASE_IMPORTER
/*
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 ASELoader.h
* @brief Definition of the .ASE importer class.
*/
#ifndef AI_ASELOADER_H_INCLUDED
#define AI_ASELOADER_H_INCLUDED
#include <assimp/BaseImporter.h>
#include <assimp/types.h>
#include "ASEParser.h"
struct aiNode;
namespace Assimp {
#ifndef ASSIMP_BUILD_NO_3DS_IMPORTER
// --------------------------------------------------------------------------------
/** Importer class for the 3DS ASE ASCII format.
*
*/
class ASEImporter : public BaseImporter {
public:
ASEImporter();
~ASEImporter();
// -------------------------------------------------------------------
/** Returns whether the class can handle the format of the given file.
* See BaseImporter::CanRead() for details.
*/
bool CanRead( const std::string& pFile, IOSystem* pIOHandler,
bool checkSig) const;
protected:
// -------------------------------------------------------------------
/** Return importer meta information.
* See #BaseImporter::GetInfo for the details
*/
const aiImporterDesc* GetInfo () const;
// -------------------------------------------------------------------
/** Imports the given file into the given scene structure.
* See BaseImporter::InternReadFile() for details
*/
void InternReadFile( const std::string& pFile, aiScene* pScene,
IOSystem* pIOHandler);
// -------------------------------------------------------------------
/** Called prior to ReadFile().
* The function is a request to the importer to update its configuration
* basing on the Importer's configuration property list.
*/
void SetupProperties(const Importer* pImp);
private:
// -------------------------------------------------------------------
/** Generate normal vectors basing on smoothing groups
* (in some cases the normal are already contained in the file)
* \param mesh Mesh to work on
* \return false if the normals have been recomputed
*/
bool GenerateNormals(ASE::Mesh& mesh);
// -------------------------------------------------------------------
/** Create valid vertex/normal/UV/color/face lists.
* All elements are unique, faces have only one set of indices
* after this step occurs.
* \param mesh Mesh to work on
*/
void BuildUniqueRepresentation(ASE::Mesh& mesh);
/** Create one-material-per-mesh meshes ;-)
* \param mesh Mesh to work with
* \param Receives the list of all created meshes
*/
void ConvertMeshes(ASE::Mesh& mesh, std::vector<aiMesh*>& avOut);
// -------------------------------------------------------------------
/** Convert a material to a aiMaterial object
* \param mat Input material
*/
void ConvertMaterial(ASE::Material& mat);
// -------------------------------------------------------------------
/** Setup the final material indices for each mesh
*/
void BuildMaterialIndices();
// -------------------------------------------------------------------
/** Build the node graph
*/
void BuildNodes(std::vector<ASE::BaseNode*>& nodes);
// -------------------------------------------------------------------
/** Build output cameras
*/
void BuildCameras();
// -------------------------------------------------------------------
/** Build output lights
*/
void BuildLights();
// -------------------------------------------------------------------
/** Build output animations
*/
void BuildAnimations(const std::vector<ASE::BaseNode*>& nodes);
// -------------------------------------------------------------------
/** Add sub nodes to a node
* \param pcParent parent node to be filled
* \param szName Name of the parent node
* \param matrix Current transform
*/
void AddNodes(const std::vector<ASE::BaseNode*>& nodes,
aiNode* pcParent,const char* szName);
void AddNodes(const std::vector<ASE::BaseNode*>& nodes,
aiNode* pcParent,const char* szName,
const aiMatrix4x4& matrix);
void AddMeshes(const ASE::BaseNode* snode,aiNode* node);
// -------------------------------------------------------------------
/** Generate a default material and add it to the parser's list
* Called if no material has been found in the file (rare for ASE,
* but not impossible)
*/
void GenerateDefaultMaterial();
protected:
/** Parser instance */
ASE::Parser* mParser;
/** Buffer to hold the loaded file */
char* mBuffer;
/** Scene to be filled */
aiScene* pcScene;
/** Config options: Recompute the normals in every case - WA
for 3DS Max broken ASE normal export */
bool configRecomputeNormals;
bool noSkeletonMesh;
};
#endif // ASSIMP_BUILD_NO_3DS_IMPORTER
} // end of namespace Assimp
#endif // AI_3DSIMPORTER_H_INC
/*
---------------------------------------------------------------------------
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 ASEParser.cpp
* @brief Implementation of the ASE parser class
*/
#ifndef ASSIMP_BUILD_NO_ASE_IMPORTER
#ifndef ASSIMP_BUILD_NO_3DS_IMPORTER
// internal headers
#include "ASELoader.h"
#include "PostProcessing/TextureTransform.h"
#include <assimp/fast_atof.h>
#include <assimp/DefaultLogger.hpp>
using namespace Assimp;
using namespace Assimp::ASE;
// ------------------------------------------------------------------------------------------------
// Begin an ASE parsing function
#define AI_ASE_PARSER_INIT() \
int iDepth = 0;
// ------------------------------------------------------------------------------------------------
// Handle a "top-level" section in the file. EOF is no error in this case.
#define AI_ASE_HANDLE_TOP_LEVEL_SECTION() \
else if ('{' == *filePtr) iDepth++; \
else if ('}' == *filePtr) { \
if (0 == --iDepth) { \
++filePtr; \
SkipToNextToken(); \
return; \
} \
} \
else if ('\0' == *filePtr) { \
return; \
} \
if (IsLineEnd(*filePtr) && !bLastWasEndLine) { \
++iLineNumber; \
bLastWasEndLine = true; \
} else \
bLastWasEndLine = false; \
++filePtr;
// ------------------------------------------------------------------------------------------------
// Handle a nested section in the file. EOF is an error in this case
// @param level "Depth" of the section
// @param msg Full name of the section (including the asterisk)
#define AI_ASE_HANDLE_SECTION(level, msg) \
if ('{' == *filePtr) \
iDepth++; \
else if ('}' == *filePtr) { \
if (0 == --iDepth) { \
++filePtr; \
SkipToNextToken(); \
return; \
} \
} else if ('\0' == *filePtr) { \
LogError("Encountered unexpected EOL while parsing a " msg \
" chunk (Level " level ")"); \
} \
if (IsLineEnd(*filePtr) && !bLastWasEndLine) { \
++iLineNumber; \
bLastWasEndLine = true; \
} else \
bLastWasEndLine = false; \
++filePtr;
// ------------------------------------------------------------------------------------------------
Parser::Parser(const char *szFile, unsigned int fileFormatDefault) {
ai_assert(nullptr != szFile);
filePtr = szFile;
iFileFormat = fileFormatDefault;
// make sure that the color values are invalid
m_clrBackground.r = get_qnan();
m_clrAmbient.r = get_qnan();
// setup some default values
iLineNumber = 0;
iFirstFrame = 0;
iLastFrame = 0;
iFrameSpeed = 30; // use 30 as default value for this property
iTicksPerFrame = 1; // use 1 as default value for this property
bLastWasEndLine = false; // need to handle \r\n seqs due to binary file mapping
}
// ------------------------------------------------------------------------------------------------
void Parser::LogWarning(const char *szWarn) {
ai_assert(nullptr != szWarn);
char szTemp[2048];
#if _MSC_VER >= 1400
sprintf_s(szTemp, "Line %u: %s", iLineNumber, szWarn);
#else
ai_snprintf(szTemp, sizeof(szTemp), "Line %u: %s", iLineNumber, szWarn);
#endif
// output the warning to the logger ...
ASSIMP_LOG_WARN(szTemp);
}
// ------------------------------------------------------------------------------------------------
void Parser::LogInfo(const char *szWarn) {
ai_assert(nullptr != szWarn);
char szTemp[1024];
#if _MSC_VER >= 1400
sprintf_s(szTemp, "Line %u: %s", iLineNumber, szWarn);
#else
ai_snprintf(szTemp, 1024, "Line %u: %s", iLineNumber, szWarn);
#endif
// output the information to the logger ...
ASSIMP_LOG_INFO(szTemp);
}
// ------------------------------------------------------------------------------------------------
AI_WONT_RETURN void Parser::LogError(const char *szWarn) {
ai_assert(nullptr != szWarn);
char szTemp[1024];
#if _MSC_VER >= 1400
sprintf_s(szTemp, "Line %u: %s", iLineNumber, szWarn);
#else
ai_snprintf(szTemp, 1024, "Line %u: %s", iLineNumber, szWarn);
#endif
// throw an exception
throw DeadlyImportError(szTemp);
}
// ------------------------------------------------------------------------------------------------
bool Parser::SkipToNextToken() {
while (true) {
char me = *filePtr;
// increase the line number counter if necessary
if (IsLineEnd(me) && !bLastWasEndLine) {
++iLineNumber;
bLastWasEndLine = true;
} else
bLastWasEndLine = false;
if ('*' == me || '}' == me || '{' == me) return true;
if ('\0' == me) return false;
++filePtr;
}
}
// ------------------------------------------------------------------------------------------------
bool Parser::SkipSection() {
// must handle subsections ...
int iCnt = 0;
while (true) {
if ('}' == *filePtr) {
--iCnt;
if (0 == iCnt) {
// go to the next valid token ...
++filePtr;
SkipToNextToken();
return true;
}
} else if ('{' == *filePtr) {
++iCnt;
} else if ('\0' == *filePtr) {
LogWarning("Unable to parse block: Unexpected EOF, closing bracket \'}\' was expected [#1]");
return false;
} else if (IsLineEnd(*filePtr))
++iLineNumber;
++filePtr;
}
}
// ------------------------------------------------------------------------------------------------
void Parser::Parse() {
AI_ASE_PARSER_INIT();
while (true) {
if ('*' == *filePtr) {
++filePtr;
// Version should be 200. Validate this ...
if (TokenMatch(filePtr, "3DSMAX_ASCIIEXPORT", 18)) {
unsigned int fmt;
ParseLV4MeshLong(fmt);
if (fmt > 200) {
LogWarning("Unknown file format version: *3DSMAX_ASCIIEXPORT should \
be <= 200");
}
// *************************************************************
// - fmt will be 0 if we're unable to read the version number
// there are some faulty files without a version number ...
// in this case we'll guess the exact file format by looking
// at the file extension (ASE, ASK, ASC)
// *************************************************************
if (fmt) {
iFileFormat = fmt;
}
continue;
}
// main scene information
if (TokenMatch(filePtr, "SCENE", 5)) {
ParseLV1SceneBlock();
continue;
}
// "group" - no implementation yet, in facte
// we're just ignoring them for the moment
if (TokenMatch(filePtr, "GROUP", 5)) {
Parse();
continue;
}
// material list
if (TokenMatch(filePtr, "MATERIAL_LIST", 13)) {
ParseLV1MaterialListBlock();
continue;
}
// geometric object (mesh)
if (TokenMatch(filePtr, "GEOMOBJECT", 10))
{
m_vMeshes.push_back(Mesh("UNNAMED"));
ParseLV1ObjectBlock(m_vMeshes.back());
continue;
}
// helper object = dummy in the hierarchy
if (TokenMatch(filePtr, "HELPEROBJECT", 12))
{
m_vDummies.push_back(Dummy());
ParseLV1ObjectBlock(m_vDummies.back());
continue;
}
// light object
if (TokenMatch(filePtr, "LIGHTOBJECT", 11))
{
m_vLights.push_back(Light("UNNAMED"));
ParseLV1ObjectBlock(m_vLights.back());
continue;
}
// camera object
if (TokenMatch(filePtr, "CAMERAOBJECT", 12)) {
m_vCameras.push_back(Camera("UNNAMED"));
ParseLV1ObjectBlock(m_vCameras.back());
continue;
}
// comment - print it on the console
if (TokenMatch(filePtr, "COMMENT", 7)) {
std::string out = "<unknown>";
ParseString(out, "*COMMENT");
LogInfo(("Comment: " + out).c_str());
continue;
}
// ASC bone weights
if (AI_ASE_IS_OLD_FILE_FORMAT() && TokenMatch(filePtr, "MESH_SOFTSKINVERTS", 18)) {
ParseLV1SoftSkinBlock();
}
}
AI_ASE_HANDLE_TOP_LEVEL_SECTION();
}
return;
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV1SoftSkinBlock() {
// TODO: fix line counting here
// **************************************************************
// The soft skin block is formatted differently. There are no
// nested sections supported and the single elements aren't
// marked by keywords starting with an asterisk.
/**
FORMAT BEGIN
*MESH_SOFTSKINVERTS {
<nodename>
<number of vertices>
[for <number of vertices> times:]
<number of weights> [for <number of weights> times:] <bone name> <weight>
}
FORMAT END
*/
// **************************************************************
while (true) {
if (*filePtr == '}') {
++filePtr;
return;
} else if (*filePtr == '\0')
return;
else if (*filePtr == '{')
++filePtr;
else // if (!IsSpace(*filePtr) && !IsLineEnd(*filePtr))
{
ASE::Mesh *curMesh = nullptr;
unsigned int numVerts = 0;
const char *sz = filePtr;
while (!IsSpaceOrNewLine(*filePtr))
++filePtr;
const unsigned int diff = (unsigned int)(filePtr - sz);
if (diff) {
std::string name = std::string(sz, diff);
for (std::vector<ASE::Mesh>::iterator it = m_vMeshes.begin();
it != m_vMeshes.end(); ++it) {
if ((*it).mName == name) {
curMesh = &(*it);
break;
}
}
if (!curMesh) {
LogWarning("Encountered unknown mesh in *MESH_SOFTSKINVERTS section");
// Skip the mesh data - until we find a new mesh
// or the end of the *MESH_SOFTSKINVERTS section
while (true) {
SkipSpacesAndLineEnd(&filePtr);
if (*filePtr == '}') {
++filePtr;
return;
} else if (!IsNumeric(*filePtr))
break;
SkipLine(&filePtr);
}
} else {
SkipSpacesAndLineEnd(&filePtr);
ParseLV4MeshLong(numVerts);
// Reserve enough storage
curMesh->mBoneVertices.reserve(numVerts);
for (unsigned int i = 0; i < numVerts; ++i) {
SkipSpacesAndLineEnd(&filePtr);
unsigned int numWeights;
ParseLV4MeshLong(numWeights);
curMesh->mBoneVertices.push_back(ASE::BoneVertex());
ASE::BoneVertex &vert = curMesh->mBoneVertices.back();
// Reserve enough storage
vert.mBoneWeights.reserve(numWeights);
std::string bone;
for (unsigned int w = 0; w < numWeights; ++w) {
bone.clear();
ParseString(bone, "*MESH_SOFTSKINVERTS.Bone");
// Find the bone in the mesh's list
std::pair<int, ai_real> me;
me.first = -1;
for (unsigned int n = 0; n < curMesh->mBones.size(); ++n) {
if (curMesh->mBones[n].mName == bone) {
me.first = n;
break;
}
}
if (-1 == me.first) {
// We don't have this bone yet, so add it to the list
me.first = static_cast<int>(curMesh->mBones.size());
curMesh->mBones.push_back(ASE::Bone(bone));
}
ParseLV4MeshFloat(me.second);
// Add the new bone weight to list
vert.mBoneWeights.push_back(me);
}
}
}
}
}
++filePtr;
SkipSpacesAndLineEnd(&filePtr);
}
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV1SceneBlock() {
AI_ASE_PARSER_INIT();
while (true) {
if ('*' == *filePtr) {
++filePtr;
if (TokenMatch(filePtr, "SCENE_BACKGROUND_STATIC", 23))
{
// parse a color triple and assume it is really the bg color
ParseLV4MeshFloatTriple(&m_clrBackground.r);
continue;
}
if (TokenMatch(filePtr, "SCENE_AMBIENT_STATIC", 20))
{
// parse a color triple and assume it is really the bg color
ParseLV4MeshFloatTriple(&m_clrAmbient.r);
continue;
}
if (TokenMatch(filePtr, "SCENE_FIRSTFRAME", 16)) {
ParseLV4MeshLong(iFirstFrame);
continue;
}
if (TokenMatch(filePtr, "SCENE_LASTFRAME", 15)) {
ParseLV4MeshLong(iLastFrame);
continue;
}
if (TokenMatch(filePtr, "SCENE_FRAMESPEED", 16)) {
ParseLV4MeshLong(iFrameSpeed);
continue;
}
if (TokenMatch(filePtr, "SCENE_TICKSPERFRAME", 19)) {
ParseLV4MeshLong(iTicksPerFrame);
continue;
}
}
AI_ASE_HANDLE_TOP_LEVEL_SECTION();
}
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV1MaterialListBlock() {
AI_ASE_PARSER_INIT();
unsigned int iMaterialCount = 0;
unsigned int iOldMaterialCount = (unsigned int)m_vMaterials.size();
while (true) {
if ('*' == *filePtr) {
++filePtr;
if (TokenMatch(filePtr, "MATERIAL_COUNT", 14)) {
ParseLV4MeshLong(iMaterialCount);
// now allocate enough storage to hold all materials
m_vMaterials.resize(iOldMaterialCount + iMaterialCount, Material("INVALID"));
continue;
}
if (TokenMatch(filePtr, "MATERIAL", 8)) {
unsigned int iIndex = 0;
ParseLV4MeshLong(iIndex);
if (iIndex >= iMaterialCount) {
LogWarning("Out of range: material index is too large");
iIndex = iMaterialCount - 1;
}
// get a reference to the material
Material &sMat = m_vMaterials[iIndex + iOldMaterialCount];
// parse the material block
ParseLV2MaterialBlock(sMat);
continue;
}
}
AI_ASE_HANDLE_TOP_LEVEL_SECTION();
}
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV2MaterialBlock(ASE::Material &mat) {
AI_ASE_PARSER_INIT();
unsigned int iNumSubMaterials = 0;
while (true) {
if ('*' == *filePtr) {
++filePtr;
if (TokenMatch(filePtr, "MATERIAL_NAME", 13)) {
if (!ParseString(mat.mName, "*MATERIAL_NAME"))
SkipToNextToken();
continue;
}
// ambient material color
if (TokenMatch(filePtr, "MATERIAL_AMBIENT", 16)) {
ParseLV4MeshFloatTriple(&mat.mAmbient.r);
continue;
}
// diffuse material color
if (TokenMatch(filePtr, "MATERIAL_DIFFUSE", 16)) {
ParseLV4MeshFloatTriple(&mat.mDiffuse.r);
continue;
}
// specular material color
if (TokenMatch(filePtr, "MATERIAL_SPECULAR", 17)) {
ParseLV4MeshFloatTriple(&mat.mSpecular.r);
continue;
}
// material shading type
if (TokenMatch(filePtr, "MATERIAL_SHADING", 16)) {
if (TokenMatch(filePtr, "Blinn", 5)) {
mat.mShading = Discreet3DS::Blinn;
} else if (TokenMatch(filePtr, "Phong", 5)) {
mat.mShading = Discreet3DS::Phong;
} else if (TokenMatch(filePtr, "Flat", 4)) {
mat.mShading = Discreet3DS::Flat;
} else if (TokenMatch(filePtr, "Wire", 4)) {
mat.mShading = Discreet3DS::Wire;
} else {
// assume gouraud shading
mat.mShading = Discreet3DS::Gouraud;
SkipToNextToken();
}
continue;
}
// material transparency
if (TokenMatch(filePtr, "MATERIAL_TRANSPARENCY", 21)) {
ParseLV4MeshFloat(mat.mTransparency);
mat.mTransparency = ai_real(1.0) - mat.mTransparency;
continue;
}
// material self illumination
if (TokenMatch(filePtr, "MATERIAL_SELFILLUM", 18)) {
ai_real f = 0.0;
ParseLV4MeshFloat(f);
mat.mEmissive.r = f;
mat.mEmissive.g = f;
mat.mEmissive.b = f;
continue;
}
// material shininess
if (TokenMatch(filePtr, "MATERIAL_SHINE", 14)) {
ParseLV4MeshFloat(mat.mSpecularExponent);
mat.mSpecularExponent *= 15;
continue;
}
// two-sided material
if (TokenMatch(filePtr, "MATERIAL_TWOSIDED", 17)) {
mat.mTwoSided = true;
continue;
}
// material shininess strength
if (TokenMatch(filePtr, "MATERIAL_SHINESTRENGTH", 22)) {
ParseLV4MeshFloat(mat.mShininessStrength);
continue;
}
// diffuse color map
if (TokenMatch(filePtr, "MAP_DIFFUSE", 11)) {
// parse the texture block
ParseLV3MapBlock(mat.sTexDiffuse);
continue;
}
// ambient color map
if (TokenMatch(filePtr, "MAP_AMBIENT", 11)) {
// parse the texture block
ParseLV3MapBlock(mat.sTexAmbient);
continue;
}
// specular color map
if (TokenMatch(filePtr, "MAP_SPECULAR", 12)) {
// parse the texture block
ParseLV3MapBlock(mat.sTexSpecular);
continue;
}
// opacity map
if (TokenMatch(filePtr, "MAP_OPACITY", 11)) {
// parse the texture block
ParseLV3MapBlock(mat.sTexOpacity);
continue;
}
// emissive map
if (TokenMatch(filePtr, "MAP_SELFILLUM", 13)) {
// parse the texture block
ParseLV3MapBlock(mat.sTexEmissive);
continue;
}
// bump map
if (TokenMatch(filePtr, "MAP_BUMP", 8)) {
// parse the texture block
ParseLV3MapBlock(mat.sTexBump);
}
// specular/shininess map
if (TokenMatch(filePtr, "MAP_SHINESTRENGTH", 17)) {
// parse the texture block
ParseLV3MapBlock(mat.sTexShininess);
continue;
}
// number of submaterials
if (TokenMatch(filePtr, "NUMSUBMTLS", 10)) {
ParseLV4MeshLong(iNumSubMaterials);
// allocate enough storage
mat.avSubMaterials.resize(iNumSubMaterials, Material("INVALID SUBMATERIAL"));
}
// submaterial chunks
if (TokenMatch(filePtr, "SUBMATERIAL", 11)) {
unsigned int iIndex = 0;
ParseLV4MeshLong(iIndex);
if (iIndex >= iNumSubMaterials) {
LogWarning("Out of range: submaterial index is too large");
iIndex = iNumSubMaterials - 1;
}
// get a reference to the material
Material &sMat = mat.avSubMaterials[iIndex];
// parse the material block
ParseLV2MaterialBlock(sMat);
continue;
}
}
AI_ASE_HANDLE_SECTION("2", "*MATERIAL");
}
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV3MapBlock(Texture &map) {
AI_ASE_PARSER_INIT();
// ***********************************************************
// *BITMAP should not be there if *MAP_CLASS is not BITMAP,
// but we need to expect that case ... if the path is
// empty the texture won't be used later.
// ***********************************************************
bool parsePath = true;
std::string temp;
while (true) {
if ('*' == *filePtr) {
++filePtr;
// type of map
if (TokenMatch(filePtr, "MAP_CLASS", 9)) {
temp.clear();
if (!ParseString(temp, "*MAP_CLASS"))
SkipToNextToken();
if (temp != "Bitmap" && temp != "Normal Bump") {
ASSIMP_LOG_WARN_F("ASE: Skipping unknown map type: ", temp);
parsePath = false;
}
continue;
}
// path to the texture
if (parsePath && TokenMatch(filePtr, "BITMAP", 6)) {
if (!ParseString(map.mMapName, "*BITMAP"))
SkipToNextToken();
if (map.mMapName == "None") {
// Files with 'None' as map name are produced by
// an Maja to ASE exporter which name I forgot ..
ASSIMP_LOG_WARN("ASE: Skipping invalid map entry");
map.mMapName = "";
}
continue;
}
// offset on the u axis
if (TokenMatch(filePtr, "UVW_U_OFFSET", 12)) {
ParseLV4MeshFloat(map.mOffsetU);
continue;
}
// offset on the v axis
if (TokenMatch(filePtr, "UVW_V_OFFSET", 12)) {
ParseLV4MeshFloat(map.mOffsetV);
continue;
}
// tiling on the u axis
if (TokenMatch(filePtr, "UVW_U_TILING", 12)) {
ParseLV4MeshFloat(map.mScaleU);
continue;
}
// tiling on the v axis
if (TokenMatch(filePtr, "UVW_V_TILING", 12)) {
ParseLV4MeshFloat(map.mScaleV);
continue;
}
// rotation around the z-axis
if (TokenMatch(filePtr, "UVW_ANGLE", 9)) {
ParseLV4MeshFloat(map.mRotation);
continue;
}
// map blending factor
if (TokenMatch(filePtr, "MAP_AMOUNT", 10)) {
ParseLV4MeshFloat(map.mTextureBlend);
continue;
}
}
AI_ASE_HANDLE_SECTION("3", "*MAP_XXXXXX");
}
return;
}
// ------------------------------------------------------------------------------------------------
bool Parser::ParseString(std::string &out, const char *szName) {
char szBuffer[1024];
if (!SkipSpaces(&filePtr)) {
ai_snprintf(szBuffer, 1024, "Unable to parse %s block: Unexpected EOL", szName);
LogWarning(szBuffer);
return false;
}
// there must be '"'
if ('\"' != *filePtr) {
ai_snprintf(szBuffer, 1024, "Unable to parse %s block: Strings are expected "
"to be enclosed in double quotation marks",
szName);
LogWarning(szBuffer);
return false;
}
++filePtr;
const char *sz = filePtr;
while (true) {
if ('\"' == *sz)
break;
else if ('\0' == *sz) {
ai_snprintf(szBuffer, 1024, "Unable to parse %s block: Strings are expected to "
"be enclosed in double quotation marks but EOF was reached before "
"a closing quotation mark was encountered",
szName);
LogWarning(szBuffer);
return false;
}
sz++;
}
out = std::string(filePtr, (uintptr_t)sz - (uintptr_t)filePtr);
filePtr = sz + 1;
return true;
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV1ObjectBlock(ASE::BaseNode &node) {
AI_ASE_PARSER_INIT();
while (true) {
if ('*' == *filePtr) {
++filePtr;
// first process common tokens such as node name and transform
// name of the mesh/node
if (TokenMatch(filePtr, "NODE_NAME", 9)) {
if (!ParseString(node.mName, "*NODE_NAME"))
SkipToNextToken();
continue;
}
// name of the parent of the node
if (TokenMatch(filePtr, "NODE_PARENT", 11)) {
if (!ParseString(node.mParent, "*NODE_PARENT"))
SkipToNextToken();
continue;
}
// transformation matrix of the node
if (TokenMatch(filePtr, "NODE_TM", 7)) {
ParseLV2NodeTransformBlock(node);
continue;
}
// animation data of the node
if (TokenMatch(filePtr, "TM_ANIMATION", 12)) {
ParseLV2AnimationBlock(node);
continue;
}
if (node.mType == BaseNode::Light) {
// light settings
if (TokenMatch(filePtr, "LIGHT_SETTINGS", 14)) {
ParseLV2LightSettingsBlock((ASE::Light &)node);
continue;
}
// type of the light source
if (TokenMatch(filePtr, "LIGHT_TYPE", 10)) {
if (!ASSIMP_strincmp("omni", filePtr, 4)) {
((ASE::Light &)node).mLightType = ASE::Light::OMNI;
} else if (!ASSIMP_strincmp("target", filePtr, 6)) {
((ASE::Light &)node).mLightType = ASE::Light::TARGET;
} else if (!ASSIMP_strincmp("free", filePtr, 4)) {
((ASE::Light &)node).mLightType = ASE::Light::FREE;
} else if (!ASSIMP_strincmp("directional", filePtr, 11)) {
((ASE::Light &)node).mLightType = ASE::Light::DIRECTIONAL;
} else {
LogWarning("Unknown kind of light source");
}
continue;
}
} else if (node.mType == BaseNode::Camera) {
// Camera settings
if (TokenMatch(filePtr, "CAMERA_SETTINGS", 15)) {
ParseLV2CameraSettingsBlock((ASE::Camera &)node);
continue;
} else if (TokenMatch(filePtr, "CAMERA_TYPE", 11)) {
if (!ASSIMP_strincmp("target", filePtr, 6)) {
((ASE::Camera &)node).mCameraType = ASE::Camera::TARGET;
} else if (!ASSIMP_strincmp("free", filePtr, 4)) {
((ASE::Camera &)node).mCameraType = ASE::Camera::FREE;
} else {
LogWarning("Unknown kind of camera");
}
continue;
}
} else if (node.mType == BaseNode::Mesh) {
// mesh data
// FIX: Older files use MESH_SOFTSKIN
if (TokenMatch(filePtr, "MESH", 4) ||
TokenMatch(filePtr, "MESH_SOFTSKIN", 13)) {
ParseLV2MeshBlock((ASE::Mesh &)node);
continue;
}
// mesh material index
if (TokenMatch(filePtr, "MATERIAL_REF", 12)) {
ParseLV4MeshLong(((ASE::Mesh &)node).iMaterialIndex);
continue;
}
}
}
AI_ASE_HANDLE_TOP_LEVEL_SECTION();
}
return;
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV2CameraSettingsBlock(ASE::Camera &camera) {
AI_ASE_PARSER_INIT();
while (true) {
if ('*' == *filePtr) {
++filePtr;
if (TokenMatch(filePtr, "CAMERA_NEAR", 11)) {
ParseLV4MeshFloat(camera.mNear);
continue;
}
if (TokenMatch(filePtr, "CAMERA_FAR", 10)) {
ParseLV4MeshFloat(camera.mFar);
continue;
}
if (TokenMatch(filePtr, "CAMERA_FOV", 10)) {
ParseLV4MeshFloat(camera.mFOV);
continue;
}
}
AI_ASE_HANDLE_SECTION("2", "CAMERA_SETTINGS");
}
return;
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV2LightSettingsBlock(ASE::Light &light) {
AI_ASE_PARSER_INIT();
while (true) {
if ('*' == *filePtr) {
++filePtr;
if (TokenMatch(filePtr, "LIGHT_COLOR", 11)) {
ParseLV4MeshFloatTriple(&light.mColor.r);
continue;
}
if (TokenMatch(filePtr, "LIGHT_INTENS", 12)) {
ParseLV4MeshFloat(light.mIntensity);
continue;
}
if (TokenMatch(filePtr, "LIGHT_HOTSPOT", 13)) {
ParseLV4MeshFloat(light.mAngle);
continue;
}
if (TokenMatch(filePtr, "LIGHT_FALLOFF", 13)) {
ParseLV4MeshFloat(light.mFalloff);
continue;
}
}
AI_ASE_HANDLE_SECTION("2", "LIGHT_SETTINGS");
}
return;
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV2AnimationBlock(ASE::BaseNode &mesh) {
AI_ASE_PARSER_INIT();
ASE::Animation *anim = &mesh.mAnim;
while (true) {
if ('*' == *filePtr) {
++filePtr;
if (TokenMatch(filePtr, "NODE_NAME", 9)) {
std::string temp;
if (!ParseString(temp, "*NODE_NAME"))
SkipToNextToken();
// If the name of the node contains .target it
// represents an animated camera or spot light
// target.
if (std::string::npos != temp.find(".Target")) {
if ((mesh.mType != BaseNode::Camera || ((ASE::Camera &)mesh).mCameraType != ASE::Camera::TARGET) &&
(mesh.mType != BaseNode::Light || ((ASE::Light &)mesh).mLightType != ASE::Light::TARGET)) {
ASSIMP_LOG_ERROR("ASE: Found target animation channel "
"but the node is neither a camera nor a spot light");
anim = NULL;
} else
anim = &mesh.mTargetAnim;
}
continue;
}
// position keyframes
if (TokenMatch(filePtr, "CONTROL_POS_TRACK", 17) ||
TokenMatch(filePtr, "CONTROL_POS_BEZIER", 18) ||
TokenMatch(filePtr, "CONTROL_POS_TCB", 15)) {
if (!anim)
SkipSection();
else
ParseLV3PosAnimationBlock(*anim);
continue;
}
// scaling keyframes
if (TokenMatch(filePtr, "CONTROL_SCALE_TRACK", 19) ||
TokenMatch(filePtr, "CONTROL_SCALE_BEZIER", 20) ||
TokenMatch(filePtr, "CONTROL_SCALE_TCB", 17)) {
if (!anim || anim == &mesh.mTargetAnim) {
// Target animation channels may have no rotation channels
ASSIMP_LOG_ERROR("ASE: Ignoring scaling channel in target animation");
SkipSection();
} else
ParseLV3ScaleAnimationBlock(*anim);
continue;
}
// rotation keyframes
if (TokenMatch(filePtr, "CONTROL_ROT_TRACK", 17) ||
TokenMatch(filePtr, "CONTROL_ROT_BEZIER", 18) ||
TokenMatch(filePtr, "CONTROL_ROT_TCB", 15)) {
if (!anim || anim == &mesh.mTargetAnim) {
// Target animation channels may have no rotation channels
ASSIMP_LOG_ERROR("ASE: Ignoring rotation channel in target animation");
SkipSection();
} else
ParseLV3RotAnimationBlock(*anim);
continue;
}
}
AI_ASE_HANDLE_SECTION("2", "TM_ANIMATION");
}
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV3ScaleAnimationBlock(ASE::Animation &anim) {
AI_ASE_PARSER_INIT();
unsigned int iIndex;
while (true) {
if ('*' == *filePtr) {
++filePtr;
bool b = false;
// For the moment we're just reading the three floats -
// we ignore the additional information for bezier's and TCBs
// simple scaling keyframe
if (TokenMatch(filePtr, "CONTROL_SCALE_SAMPLE", 20)) {
b = true;
anim.mScalingType = ASE::Animation::TRACK;
}
// Bezier scaling keyframe
if (TokenMatch(filePtr, "CONTROL_BEZIER_SCALE_KEY", 24)) {
b = true;
anim.mScalingType = ASE::Animation::BEZIER;
}
// TCB scaling keyframe
if (TokenMatch(filePtr, "CONTROL_TCB_SCALE_KEY", 21)) {
b = true;
anim.mScalingType = ASE::Animation::TCB;
}
if (b) {
anim.akeyScaling.push_back(aiVectorKey());
aiVectorKey &key = anim.akeyScaling.back();
ParseLV4MeshFloatTriple(&key.mValue.x, iIndex);
key.mTime = (double)iIndex;
}
}
AI_ASE_HANDLE_SECTION("3", "*CONTROL_POS_TRACK");
}
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV3PosAnimationBlock(ASE::Animation &anim) {
AI_ASE_PARSER_INIT();
unsigned int iIndex;
while (true) {
if ('*' == *filePtr) {
++filePtr;
bool b = false;
// For the moment we're just reading the three floats -
// we ignore the additional information for bezier's and TCBs
// simple scaling keyframe
if (TokenMatch(filePtr, "CONTROL_POS_SAMPLE", 18)) {
b = true;
anim.mPositionType = ASE::Animation::TRACK;
}
// Bezier scaling keyframe
if (TokenMatch(filePtr, "CONTROL_BEZIER_POS_KEY", 22)) {
b = true;
anim.mPositionType = ASE::Animation::BEZIER;
}
// TCB scaling keyframe
if (TokenMatch(filePtr, "CONTROL_TCB_POS_KEY", 19)) {
b = true;
anim.mPositionType = ASE::Animation::TCB;
}
if (b) {
anim.akeyPositions.push_back(aiVectorKey());
aiVectorKey &key = anim.akeyPositions.back();
ParseLV4MeshFloatTriple(&key.mValue.x, iIndex);
key.mTime = (double)iIndex;
}
}
AI_ASE_HANDLE_SECTION("3", "*CONTROL_POS_TRACK");
}
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV3RotAnimationBlock(ASE::Animation &anim) {
AI_ASE_PARSER_INIT();
unsigned int iIndex;
while (true) {
if ('*' == *filePtr) {
++filePtr;
bool b = false;
// For the moment we're just reading the floats -
// we ignore the additional information for bezier's and TCBs
// simple scaling keyframe
if (TokenMatch(filePtr, "CONTROL_ROT_SAMPLE", 18)) {
b = true;
anim.mRotationType = ASE::Animation::TRACK;
}
// Bezier scaling keyframe
if (TokenMatch(filePtr, "CONTROL_BEZIER_ROT_KEY", 22)) {
b = true;
anim.mRotationType = ASE::Animation::BEZIER;
}
// TCB scaling keyframe
if (TokenMatch(filePtr, "CONTROL_TCB_ROT_KEY", 19)) {
b = true;
anim.mRotationType = ASE::Animation::TCB;
}
if (b) {
anim.akeyRotations.push_back(aiQuatKey());
aiQuatKey &key = anim.akeyRotations.back();
aiVector3D v;
ai_real f;
ParseLV4MeshFloatTriple(&v.x, iIndex);
ParseLV4MeshFloat(f);
key.mTime = (double)iIndex;
key.mValue = aiQuaternion(v, f);
}
}
AI_ASE_HANDLE_SECTION("3", "*CONTROL_ROT_TRACK");
}
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV2NodeTransformBlock(ASE::BaseNode &mesh) {
AI_ASE_PARSER_INIT();
int mode = 0;
while (true) {
if ('*' == *filePtr) {
++filePtr;
// name of the node
if (TokenMatch(filePtr, "NODE_NAME", 9)) {
std::string temp;
if (!ParseString(temp, "*NODE_NAME"))
SkipToNextToken();
std::string::size_type s;
if (temp == mesh.mName) {
mode = 1;
} else if (std::string::npos != (s = temp.find(".Target")) &&
mesh.mName == temp.substr(0, s)) {
// This should be either a target light or a target camera
if ((mesh.mType == BaseNode::Light && ((ASE::Light &)mesh).mLightType == ASE::Light::TARGET) ||
(mesh.mType == BaseNode::Camera && ((ASE::Camera &)mesh).mCameraType == ASE::Camera::TARGET)) {
mode = 2;
} else {
ASSIMP_LOG_ERROR("ASE: Ignoring target transform, "
"this is no spot light or target camera");
}
} else {
ASSIMP_LOG_ERROR("ASE: Unknown node transformation: " + temp);
// mode = 0
}
continue;
}
if (mode) {
// fourth row of the transformation matrix - and also the
// only information here that is interesting for targets
if (TokenMatch(filePtr, "TM_ROW3", 7)) {
ParseLV4MeshFloatTriple((mode == 1 ? mesh.mTransform[3] : &mesh.mTargetPosition.x));
continue;
}
if (mode == 1) {
// first row of the transformation matrix
if (TokenMatch(filePtr, "TM_ROW0", 7)) {
ParseLV4MeshFloatTriple(mesh.mTransform[0]);
continue;
}
// second row of the transformation matrix
if (TokenMatch(filePtr, "TM_ROW1", 7)) {
ParseLV4MeshFloatTriple(mesh.mTransform[1]);
continue;
}
// third row of the transformation matrix
if (TokenMatch(filePtr, "TM_ROW2", 7)) {
ParseLV4MeshFloatTriple(mesh.mTransform[2]);
continue;
}
// inherited position axes
if (TokenMatch(filePtr, "INHERIT_POS", 11)) {
unsigned int aiVal[3];
ParseLV4MeshLongTriple(aiVal);
for (unsigned int i = 0; i < 3; ++i)
mesh.inherit.abInheritPosition[i] = aiVal[i] != 0;
continue;
}
// inherited rotation axes
if (TokenMatch(filePtr, "INHERIT_ROT", 11)) {
unsigned int aiVal[3];
ParseLV4MeshLongTriple(aiVal);
for (unsigned int i = 0; i < 3; ++i)
mesh.inherit.abInheritRotation[i] = aiVal[i] != 0;
continue;
}
// inherited scaling axes
if (TokenMatch(filePtr, "INHERIT_SCL", 11)) {
unsigned int aiVal[3];
ParseLV4MeshLongTriple(aiVal);
for (unsigned int i = 0; i < 3; ++i)
mesh.inherit.abInheritScaling[i] = aiVal[i] != 0;
continue;
}
}
}
}
AI_ASE_HANDLE_SECTION("2", "*NODE_TM");
}
return;
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV2MeshBlock(ASE::Mesh &mesh) {
AI_ASE_PARSER_INIT();
unsigned int iNumVertices = 0;
unsigned int iNumFaces = 0;
unsigned int iNumTVertices = 0;
unsigned int iNumTFaces = 0;
unsigned int iNumCVertices = 0;
unsigned int iNumCFaces = 0;
while (true) {
if ('*' == *filePtr) {
++filePtr;
// Number of vertices in the mesh
if (TokenMatch(filePtr, "MESH_NUMVERTEX", 14)) {
ParseLV4MeshLong(iNumVertices);
continue;
}
// Number of texture coordinates in the mesh
if (TokenMatch(filePtr, "MESH_NUMTVERTEX", 15)) {
ParseLV4MeshLong(iNumTVertices);
continue;
}
// Number of vertex colors in the mesh
if (TokenMatch(filePtr, "MESH_NUMCVERTEX", 15)) {
ParseLV4MeshLong(iNumCVertices);
continue;
}
// Number of regular faces in the mesh
if (TokenMatch(filePtr, "MESH_NUMFACES", 13)) {
ParseLV4MeshLong(iNumFaces);
continue;
}
// Number of UVWed faces in the mesh
if (TokenMatch(filePtr, "MESH_NUMTVFACES", 15)) {
ParseLV4MeshLong(iNumTFaces);
continue;
}
// Number of colored faces in the mesh
if (TokenMatch(filePtr, "MESH_NUMCVFACES", 15)) {
ParseLV4MeshLong(iNumCFaces);
continue;
}
// mesh vertex list block
if (TokenMatch(filePtr, "MESH_VERTEX_LIST", 16)) {
ParseLV3MeshVertexListBlock(iNumVertices, mesh);
continue;
}
// mesh face list block
if (TokenMatch(filePtr, "MESH_FACE_LIST", 14)) {
ParseLV3MeshFaceListBlock(iNumFaces, mesh);
continue;
}
// mesh texture vertex list block
if (TokenMatch(filePtr, "MESH_TVERTLIST", 14)) {
ParseLV3MeshTListBlock(iNumTVertices, mesh);
continue;
}
// mesh texture face block
if (TokenMatch(filePtr, "MESH_TFACELIST", 14)) {
ParseLV3MeshTFaceListBlock(iNumTFaces, mesh);
continue;
}
// mesh color vertex list block
if (TokenMatch(filePtr, "MESH_CVERTLIST", 14)) {
ParseLV3MeshCListBlock(iNumCVertices, mesh);
continue;
}
// mesh color face block
if (TokenMatch(filePtr, "MESH_CFACELIST", 14)) {
ParseLV3MeshCFaceListBlock(iNumCFaces, mesh);
continue;
}
// mesh normals
if (TokenMatch(filePtr, "MESH_NORMALS", 12)) {
ParseLV3MeshNormalListBlock(mesh);
continue;
}
// another mesh UV channel ...
if (TokenMatch(filePtr, "MESH_MAPPINGCHANNEL", 19)) {
unsigned int iIndex(0);
ParseLV4MeshLong(iIndex);
if (0 == iIndex) {
LogWarning("Mapping channel has an invalid index. Skipping UV channel");
// skip it ...
SkipSection();
} else {
if (iIndex < 2) {
LogWarning("Mapping channel has an invalid index. Skipping UV channel");
// skip it ...
SkipSection();
}
if (iIndex > AI_MAX_NUMBER_OF_TEXTURECOORDS) {
LogWarning("Too many UV channels specified. Skipping channel ..");
// skip it ...
SkipSection();
} else {
// parse the mapping channel
ParseLV3MappingChannel(iIndex - 1, mesh);
}
continue;
}
}
// mesh animation keyframe. Not supported
if (TokenMatch(filePtr, "MESH_ANIMATION", 14)) {
LogWarning("Found *MESH_ANIMATION element in ASE/ASK file. "
"Keyframe animation is not supported by Assimp, this element "
"will be ignored");
//SkipSection();
continue;
}
if (TokenMatch(filePtr, "MESH_WEIGHTS", 12)) {
ParseLV3MeshWeightsBlock(mesh);
continue;
}
}
AI_ASE_HANDLE_SECTION("2", "*MESH");
}
return;
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV3MeshWeightsBlock(ASE::Mesh &mesh) {
AI_ASE_PARSER_INIT();
unsigned int iNumVertices = 0, iNumBones = 0;
while (true) {
if ('*' == *filePtr) {
++filePtr;
// Number of bone vertices ...
if (TokenMatch(filePtr, "MESH_NUMVERTEX", 14)) {
ParseLV4MeshLong(iNumVertices);
continue;
}
// Number of bones
if (TokenMatch(filePtr, "MESH_NUMBONE", 12)) {
ParseLV4MeshLong(iNumBones);
continue;
}
// parse the list of bones
if (TokenMatch(filePtr, "MESH_BONE_LIST", 14)) {
ParseLV4MeshBones(iNumBones, mesh);
continue;
}
// parse the list of bones vertices
if (TokenMatch(filePtr, "MESH_BONE_VERTEX_LIST", 21)) {
ParseLV4MeshBonesVertices(iNumVertices, mesh);
continue;
}
}
AI_ASE_HANDLE_SECTION("3", "*MESH_WEIGHTS");
}
return;
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV4MeshBones(unsigned int iNumBones, ASE::Mesh &mesh) {
AI_ASE_PARSER_INIT();
mesh.mBones.resize(iNumBones, Bone("UNNAMED"));
while (true) {
if ('*' == *filePtr) {
++filePtr;
// Mesh bone with name ...
if (TokenMatch(filePtr, "MESH_BONE_NAME", 14)) {
// parse an index ...
if (SkipSpaces(&filePtr)) {
unsigned int iIndex = strtoul10(filePtr, &filePtr);
if (iIndex >= iNumBones) {
LogWarning("Bone index is out of bounds");
continue;
}
if (!ParseString(mesh.mBones[iIndex].mName, "*MESH_BONE_NAME"))
SkipToNextToken();
continue;
}
}
}
AI_ASE_HANDLE_SECTION("3", "*MESH_BONE_LIST");
}
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV4MeshBonesVertices(unsigned int iNumVertices, ASE::Mesh &mesh) {
AI_ASE_PARSER_INIT();
mesh.mBoneVertices.resize(iNumVertices);
while (true) {
if ('*' == *filePtr) {
++filePtr;
// Mesh bone vertex
if (TokenMatch(filePtr, "MESH_BONE_VERTEX", 16)) {
// read the vertex index
unsigned int iIndex = strtoul10(filePtr, &filePtr);
if (iIndex >= mesh.mPositions.size()) {
iIndex = (unsigned int)mesh.mPositions.size() - 1;
LogWarning("Bone vertex index is out of bounds. Using the largest valid "
"bone vertex index instead");
}
// --- ignored
ai_real afVert[3];
ParseLV4MeshFloatTriple(afVert);
std::pair<int, float> pairOut;
while (true) {
// first parse the bone index ...
if (!SkipSpaces(&filePtr)) break;
pairOut.first = strtoul10(filePtr, &filePtr);
// then parse the vertex weight
if (!SkipSpaces(&filePtr)) break;
filePtr = fast_atoreal_move<float>(filePtr, pairOut.second);
// -1 marks unused entries
if (-1 != pairOut.first) {
mesh.mBoneVertices[iIndex].mBoneWeights.push_back(pairOut);
}
}
continue;
}
}
AI_ASE_HANDLE_SECTION("4", "*MESH_BONE_VERTEX");
}
return;
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV3MeshVertexListBlock(
unsigned int iNumVertices, ASE::Mesh &mesh) {
AI_ASE_PARSER_INIT();
// allocate enough storage in the array
mesh.mPositions.resize(iNumVertices);
while (true) {
if ('*' == *filePtr) {
++filePtr;
// Vertex entry
if (TokenMatch(filePtr, "MESH_VERTEX", 11)) {
aiVector3D vTemp;
unsigned int iIndex;
ParseLV4MeshFloatTriple(&vTemp.x, iIndex);
if (iIndex >= iNumVertices) {
LogWarning("Invalid vertex index. It will be ignored");
} else
mesh.mPositions[iIndex] = vTemp;
continue;
}
}
AI_ASE_HANDLE_SECTION("3", "*MESH_VERTEX_LIST");
}
return;
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV3MeshFaceListBlock(unsigned int iNumFaces, ASE::Mesh &mesh) {
AI_ASE_PARSER_INIT();
// allocate enough storage in the face array
mesh.mFaces.resize(iNumFaces);
while (true) {
if ('*' == *filePtr) {
++filePtr;
// Face entry
if (TokenMatch(filePtr, "MESH_FACE", 9)) {
ASE::Face mFace;
ParseLV4MeshFace(mFace);
if (mFace.iFace >= iNumFaces) {
LogWarning("Face has an invalid index. It will be ignored");
} else
mesh.mFaces[mFace.iFace] = mFace;
continue;
}
}
AI_ASE_HANDLE_SECTION("3", "*MESH_FACE_LIST");
}
return;
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV3MeshTListBlock(unsigned int iNumVertices,
ASE::Mesh &mesh, unsigned int iChannel) {
AI_ASE_PARSER_INIT();
// allocate enough storage in the array
mesh.amTexCoords[iChannel].resize(iNumVertices);
while (true) {
if ('*' == *filePtr) {
++filePtr;
// Vertex entry
if (TokenMatch(filePtr, "MESH_TVERT", 10)) {
aiVector3D vTemp;
unsigned int iIndex;
ParseLV4MeshFloatTriple(&vTemp.x, iIndex);
if (iIndex >= iNumVertices) {
LogWarning("Tvertex has an invalid index. It will be ignored");
} else
mesh.amTexCoords[iChannel][iIndex] = vTemp;
if (0.0f != vTemp.z) {
// we need 3 coordinate channels
mesh.mNumUVComponents[iChannel] = 3;
}
continue;
}
}
AI_ASE_HANDLE_SECTION("3", "*MESH_TVERT_LIST");
}
return;
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV3MeshTFaceListBlock(unsigned int iNumFaces,
ASE::Mesh &mesh, unsigned int iChannel) {
AI_ASE_PARSER_INIT();
while (true) {
if ('*' == *filePtr) {
++filePtr;
// Face entry
if (TokenMatch(filePtr, "MESH_TFACE", 10)) {
unsigned int aiValues[3];
unsigned int iIndex = 0;
ParseLV4MeshLongTriple(aiValues, iIndex);
if (iIndex >= iNumFaces || iIndex >= mesh.mFaces.size()) {
LogWarning("UV-Face has an invalid index. It will be ignored");
} else {
// copy UV indices
mesh.mFaces[iIndex].amUVIndices[iChannel][0] = aiValues[0];
mesh.mFaces[iIndex].amUVIndices[iChannel][1] = aiValues[1];
mesh.mFaces[iIndex].amUVIndices[iChannel][2] = aiValues[2];
}
continue;
}
}
AI_ASE_HANDLE_SECTION("3", "*MESH_TFACE_LIST");
}
return;
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV3MappingChannel(unsigned int iChannel, ASE::Mesh &mesh) {
AI_ASE_PARSER_INIT();
unsigned int iNumTVertices = 0;
unsigned int iNumTFaces = 0;
while (true) {
if ('*' == *filePtr) {
++filePtr;
// Number of texture coordinates in the mesh
if (TokenMatch(filePtr, "MESH_NUMTVERTEX", 15)) {
ParseLV4MeshLong(iNumTVertices);
continue;
}
// Number of UVWed faces in the mesh
if (TokenMatch(filePtr, "MESH_NUMTVFACES", 15)) {
ParseLV4MeshLong(iNumTFaces);
continue;
}
// mesh texture vertex list block
if (TokenMatch(filePtr, "MESH_TVERTLIST", 14)) {
ParseLV3MeshTListBlock(iNumTVertices, mesh, iChannel);
continue;
}
// mesh texture face block
if (TokenMatch(filePtr, "MESH_TFACELIST", 14)) {
ParseLV3MeshTFaceListBlock(iNumTFaces, mesh, iChannel);
continue;
}
}
AI_ASE_HANDLE_SECTION("3", "*MESH_MAPPING_CHANNEL");
}
return;
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV3MeshCListBlock(unsigned int iNumVertices, ASE::Mesh &mesh) {
AI_ASE_PARSER_INIT();
// allocate enough storage in the array
mesh.mVertexColors.resize(iNumVertices);
while (true) {
if ('*' == *filePtr) {
++filePtr;
// Vertex entry
if (TokenMatch(filePtr, "MESH_VERTCOL", 12)) {
aiColor4D vTemp;
vTemp.a = 1.0f;
unsigned int iIndex;
ParseLV4MeshFloatTriple(&vTemp.r, iIndex);
if (iIndex >= iNumVertices) {
LogWarning("Vertex color has an invalid index. It will be ignored");
} else
mesh.mVertexColors[iIndex] = vTemp;
continue;
}
}
AI_ASE_HANDLE_SECTION("3", "*MESH_CVERTEX_LIST");
}
return;
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV3MeshCFaceListBlock(unsigned int iNumFaces, ASE::Mesh &mesh) {
AI_ASE_PARSER_INIT();
while (true) {
if ('*' == *filePtr) {
++filePtr;
// Face entry
if (TokenMatch(filePtr, "MESH_CFACE", 10)) {
unsigned int aiValues[3];
unsigned int iIndex = 0;
ParseLV4MeshLongTriple(aiValues, iIndex);
if (iIndex >= iNumFaces || iIndex >= mesh.mFaces.size()) {
LogWarning("UV-Face has an invalid index. It will be ignored");
} else {
// copy color indices
mesh.mFaces[iIndex].mColorIndices[0] = aiValues[0];
mesh.mFaces[iIndex].mColorIndices[1] = aiValues[1];
mesh.mFaces[iIndex].mColorIndices[2] = aiValues[2];
}
continue;
}
}
AI_ASE_HANDLE_SECTION("3", "*MESH_CFACE_LIST");
}
return;
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV3MeshNormalListBlock(ASE::Mesh &sMesh) {
AI_ASE_PARSER_INIT();
// Allocate enough storage for the normals
sMesh.mNormals.resize(sMesh.mFaces.size() * 3, aiVector3D(0.f, 0.f, 0.f));
unsigned int index, faceIdx = UINT_MAX;
// FIXME: rewrite this and find out how to interpret the normals
// correctly. This is crap.
// Smooth the vertex and face normals together. The result
// will be edgy then, but otherwise everything would be soft ...
while (true) {
if ('*' == *filePtr) {
++filePtr;
if (faceIdx != UINT_MAX && TokenMatch(filePtr, "MESH_VERTEXNORMAL", 17)) {
aiVector3D vNormal;
ParseLV4MeshFloatTriple(&vNormal.x, index);
if (faceIdx >= sMesh.mFaces.size())
continue;
// Make sure we assign it to the correct face
const ASE::Face &face = sMesh.mFaces[faceIdx];
if (index == face.mIndices[0])
index = 0;
else if (index == face.mIndices[1])
index = 1;
else if (index == face.mIndices[2])
index = 2;
else {
ASSIMP_LOG_ERROR("ASE: Invalid vertex index in MESH_VERTEXNORMAL section");
continue;
}
// We'll renormalize later
sMesh.mNormals[faceIdx * 3 + index] += vNormal;
continue;
}
if (TokenMatch(filePtr, "MESH_FACENORMAL", 15)) {
aiVector3D vNormal;
ParseLV4MeshFloatTriple(&vNormal.x, faceIdx);
if (faceIdx >= sMesh.mFaces.size()) {
ASSIMP_LOG_ERROR("ASE: Invalid vertex index in MESH_FACENORMAL section");
continue;
}
// We'll renormalize later
sMesh.mNormals[faceIdx * 3] += vNormal;
sMesh.mNormals[faceIdx * 3 + 1] += vNormal;
sMesh.mNormals[faceIdx * 3 + 2] += vNormal;
continue;
}
}
AI_ASE_HANDLE_SECTION("3", "*MESH_NORMALS");
}
return;
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV4MeshFace(ASE::Face &out) {
// skip spaces and tabs
if (!SkipSpaces(&filePtr)) {
LogWarning("Unable to parse *MESH_FACE Element: Unexpected EOL [#1]");
SkipToNextToken();
return;
}
// parse the face index
out.iFace = strtoul10(filePtr, &filePtr);
// next character should be ':'
if (!SkipSpaces(&filePtr)) {
// FIX: there are some ASE files which haven't got : here ....
LogWarning("Unable to parse *MESH_FACE Element: Unexpected EOL. \':\' expected [#2]");
SkipToNextToken();
return;
}
// FIX: There are some ASE files which haven't got ':' here
if (':' == *filePtr) ++filePtr;
// Parse all mesh indices
for (unsigned int i = 0; i < 3; ++i) {
unsigned int iIndex = 0;
if (!SkipSpaces(&filePtr)) {
LogWarning("Unable to parse *MESH_FACE Element: Unexpected EOL");
SkipToNextToken();
return;
}
switch (*filePtr) {
case 'A':
case 'a':
break;
case 'B':
case 'b':
iIndex = 1;
break;
case 'C':
case 'c':
iIndex = 2;
break;
default:
LogWarning("Unable to parse *MESH_FACE Element: Unexpected EOL. "
"A,B or C expected [#3]");
SkipToNextToken();
return;
};
++filePtr;
// next character should be ':'
if (!SkipSpaces(&filePtr) || ':' != *filePtr) {
LogWarning("Unable to parse *MESH_FACE Element: "
"Unexpected EOL. \':\' expected [#2]");
SkipToNextToken();
return;
}
++filePtr;
if (!SkipSpaces(&filePtr)) {
LogWarning("Unable to parse *MESH_FACE Element: Unexpected EOL. "
"Vertex index ecpected [#4]");
SkipToNextToken();
return;
}
out.mIndices[iIndex] = strtoul10(filePtr, &filePtr);
}
// now we need to skip the AB, BC, CA blocks.
while (true) {
if ('*' == *filePtr) break;
if (IsLineEnd(*filePtr)) {
//iLineNumber++;
return;
}
filePtr++;
}
// parse the smoothing group of the face
if (TokenMatch(filePtr, "*MESH_SMOOTHING", 15)) {
if (!SkipSpaces(&filePtr)) {
LogWarning("Unable to parse *MESH_SMOOTHING Element: "
"Unexpected EOL. Smoothing group(s) expected [#5]");
SkipToNextToken();
return;
}
// Parse smoothing groups until we don't anymore see commas
// FIX: There needn't always be a value, sad but true
while (true) {
if (*filePtr < '9' && *filePtr >= '0') {
out.iSmoothGroup |= (1 << strtoul10(filePtr, &filePtr));
}
SkipSpaces(&filePtr);
if (',' != *filePtr) {
break;
}
++filePtr;
SkipSpaces(&filePtr);
}
}
// *MESH_MTLID is optional, too
while (true) {
if ('*' == *filePtr) break;
if (IsLineEnd(*filePtr)) {
return;
}
filePtr++;
}
if (TokenMatch(filePtr, "*MESH_MTLID", 11)) {
if (!SkipSpaces(&filePtr)) {
LogWarning("Unable to parse *MESH_MTLID Element: Unexpected EOL. "
"Material index expected [#6]");
SkipToNextToken();
return;
}
out.iMaterial = strtoul10(filePtr, &filePtr);
}
return;
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV4MeshLongTriple(unsigned int *apOut) {
ai_assert(NULL != apOut);
for (unsigned int i = 0; i < 3; ++i)
ParseLV4MeshLong(apOut[i]);
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV4MeshLongTriple(unsigned int *apOut, unsigned int &rIndexOut) {
ai_assert(NULL != apOut);
// parse the index
ParseLV4MeshLong(rIndexOut);
// parse the three others
ParseLV4MeshLongTriple(apOut);
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV4MeshFloatTriple(ai_real *apOut, unsigned int &rIndexOut) {
ai_assert(NULL != apOut);
// parse the index
ParseLV4MeshLong(rIndexOut);
// parse the three others
ParseLV4MeshFloatTriple(apOut);
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV4MeshFloatTriple(ai_real *apOut) {
ai_assert(NULL != apOut);
for (unsigned int i = 0; i < 3; ++i)
ParseLV4MeshFloat(apOut[i]);
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV4MeshFloat(ai_real &fOut) {
// skip spaces and tabs
if (!SkipSpaces(&filePtr)) {
// LOG
LogWarning("Unable to parse float: unexpected EOL [#1]");
fOut = 0.0;
++iLineNumber;
return;
}
// parse the first float
filePtr = fast_atoreal_move<ai_real>(filePtr, fOut);
}
// ------------------------------------------------------------------------------------------------
void Parser::ParseLV4MeshLong(unsigned int &iOut) {
// Skip spaces and tabs
if (!SkipSpaces(&filePtr)) {
// LOG
LogWarning("Unable to parse long: unexpected EOL [#1]");
iOut = 0;
++iLineNumber;
return;
}
// parse the value
iOut = strtoul10(filePtr, &filePtr);
}
#endif // ASSIMP_BUILD_NO_3DS_IMPORTER
#endif // !! ASSIMP_BUILD_NO_BASE_IMPORTER
/*
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 Defines the helper data structures for importing ASE files */
#ifndef AI_ASEFILEHELPER_H_INC
#define AI_ASEFILEHELPER_H_INC
// public ASSIMP headers
#include <assimp/types.h>
#include <assimp/mesh.h>
#include <assimp/anim.h>
#ifndef ASSIMP_BUILD_NO_3DS_IMPORTER
// for some helper routines like IsSpace()
#include <assimp/ParsingUtils.h>
#include <assimp/qnan.h>
// ASE is quite similar to 3ds. We can reuse some structures
#include "AssetLib/3DS/3DSLoader.h"
namespace Assimp {
namespace ASE {
using namespace D3DS;
// ---------------------------------------------------------------------------
/** Helper structure representing an ASE material */
struct Material : public D3DS::Material
{
//! Default constructor has been deleted
Material() = delete;
//! Constructor with explicit name
explicit Material(const std::string &name)
: D3DS::Material(name)
, pcInstance(NULL)
, bNeed (false) {
// empty
}
Material(const Material &other) = default;
Material &operator=(const Material &other) {
if (this == &other) {
return *this;
}
avSubMaterials = other.avSubMaterials;
pcInstance = other.pcInstance;
bNeed = other.bNeed;
return *this;
}
//! Move constructor. This is explicitly written because MSVC doesn't support defaulting it
Material(Material &&other) AI_NO_EXCEPT
: D3DS::Material(std::move(other))
, avSubMaterials(std::move(other.avSubMaterials))
, pcInstance(std::move(other.pcInstance))
, bNeed(std::move(other.bNeed))
{
other.pcInstance = nullptr;
}
Material &operator=( Material &&other) AI_NO_EXCEPT {
if (this == &other) {
return *this;
}
//D3DS::Material::operator=(std::move(other));
avSubMaterials = std::move(other.avSubMaterials);
pcInstance = std::move(other.pcInstance);
bNeed = std::move(other.bNeed);
other.pcInstance = nullptr;
return *this;
}
~Material() {}
//! Contains all sub materials of this material
std::vector<Material> avSubMaterials;
//! aiMaterial object
aiMaterial* pcInstance;
//! Can we remove this material?
bool bNeed;
};
// ---------------------------------------------------------------------------
/** Helper structure to represent an ASE file face */
struct Face : public FaceWithSmoothingGroup {
//! Default constructor. Initializes everything with 0
Face() AI_NO_EXCEPT
: iMaterial(DEFAULT_MATINDEX)
, iFace(0) {
// empty
}
//! special value to indicate that no material index has
//! been assigned to a face. The default material index
//! will replace this value later.
static const unsigned int DEFAULT_MATINDEX = 0xFFFFFFFF;
//! Indices into each list of texture coordinates
unsigned int amUVIndices[AI_MAX_NUMBER_OF_TEXTURECOORDS][3];
//! Index into the list of vertex colors
unsigned int mColorIndices[3];
//! (Sub)Material index to be assigned to this face
unsigned int iMaterial;
//! Index of the face. It is not specified whether it is
//! a requirement of the file format that all faces are
//! written in sequential order, so we have to expect this case
unsigned int iFace;
};
// ---------------------------------------------------------------------------
/** Helper structure to represent an ASE file bone */
struct Bone {
//! Constructor
Bone() = delete;
//! Construction from an existing name
explicit Bone( const std::string& name)
: mName(name) {
// empty
}
//! Name of the bone
std::string mName;
};
// ---------------------------------------------------------------------------
/** Helper structure to represent an ASE file bone vertex */
struct BoneVertex {
//! Bone and corresponding vertex weight.
//! -1 for unrequired bones ....
std::vector<std::pair<int,float> > mBoneWeights;
};
// ---------------------------------------------------------------------------
/** Helper structure to represent an ASE file animation */
struct Animation {
enum Type {
TRACK = 0x0,
BEZIER = 0x1,
TCB = 0x2
} mRotationType, mScalingType, mPositionType;
Animation() AI_NO_EXCEPT
: mRotationType (TRACK)
, mScalingType (TRACK)
, mPositionType (TRACK) {
// empty
}
//! List of track rotation keyframes
std::vector< aiQuatKey > akeyRotations;
//! List of track position keyframes
std::vector< aiVectorKey > akeyPositions;
//! List of track scaling keyframes
std::vector< aiVectorKey > akeyScaling;
};
// ---------------------------------------------------------------------------
/** Helper structure to represent the inheritance information of an ASE node */
struct InheritanceInfo {
//! Default constructor
InheritanceInfo() AI_NO_EXCEPT {
for ( size_t i=0; i<3; ++i ) {
abInheritPosition[i] = abInheritRotation[i] = abInheritScaling[i] = true;
}
}
//! Inherit the parent's position?, axis order is x,y,z
bool abInheritPosition[3];
//! Inherit the parent's rotation?, axis order is x,y,z
bool abInheritRotation[3];
//! Inherit the parent's scaling?, axis order is x,y,z
bool abInheritScaling[3];
};
// ---------------------------------------------------------------------------
/** Represents an ASE file node. Base class for mesh, light and cameras */
struct BaseNode {
enum Type {
Light,
Camera,
Mesh,
Dummy
} mType;
//! Construction from an existing name
BaseNode(Type _mType, const std::string &name)
: mType (_mType)
, mName (name)
, mProcessed (false) {
// Set mTargetPosition to qnan
const ai_real qnan = get_qnan();
mTargetPosition.x = qnan;
}
//! Name of the mesh
std::string mName;
//! Name of the parent of the node
//! "" if there is no parent ...
std::string mParent;
//! Transformation matrix of the node
aiMatrix4x4 mTransform;
//! Target position (target lights and cameras)
aiVector3D mTargetPosition;
//! Specifies which axes transformations a node inherits
//! from its parent ...
InheritanceInfo inherit;
//! Animation channels for the node
Animation mAnim;
//! Needed for lights and cameras: target animation channel
//! Should contain position keys only.
Animation mTargetAnim;
bool mProcessed;
};
// ---------------------------------------------------------------------------
/** Helper structure to represent an ASE file mesh */
struct Mesh : public MeshWithSmoothingGroups<ASE::Face>, public BaseNode {
//! Default constructor has been deleted
Mesh() = delete;
//! Construction from an existing name
explicit Mesh(const std::string &name)
: BaseNode( BaseNode::Mesh, name )
, mVertexColors()
, mBoneVertices()
, mBones()
, iMaterialIndex(Face::DEFAULT_MATINDEX)
, bSkip (false) {
for (unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS;++c) {
this->mNumUVComponents[c] = 2;
}
}
//! List of all texture coordinate sets
std::vector<aiVector3D> amTexCoords[AI_MAX_NUMBER_OF_TEXTURECOORDS];
//! List of all vertex color sets.
std::vector<aiColor4D> mVertexColors;
//! List of all bone vertices
std::vector<BoneVertex> mBoneVertices;
//! List of all bones
std::vector<Bone> mBones;
//! Material index of the mesh
unsigned int iMaterialIndex;
//! Number of vertex components for each UVW set
unsigned int mNumUVComponents[AI_MAX_NUMBER_OF_TEXTURECOORDS];
//! used internally
bool bSkip;
};
// ---------------------------------------------------------------------------
/** Helper structure to represent an ASE light source */
struct Light : public BaseNode
{
enum LightType
{
OMNI,
TARGET,
FREE,
DIRECTIONAL
};
//! Default constructor has been deleted
Light() = delete;
//! Construction from an existing name
explicit Light(const std::string &name)
: BaseNode (BaseNode::Light, name)
, mLightType (OMNI)
, mColor (1.f,1.f,1.f)
, mIntensity (1.f) // light is white by default
, mAngle (45.f)
, mFalloff (0.f)
{
}
LightType mLightType;
aiColor3D mColor;
ai_real mIntensity;
ai_real mAngle; // in degrees
ai_real mFalloff;
};
// ---------------------------------------------------------------------------
/** Helper structure to represent an ASE camera */
struct Camera : public BaseNode
{
enum CameraType
{
FREE,
TARGET
};
//! Default constructor has been deleted
Camera() = delete;
//! Construction from an existing name
explicit Camera(const std::string &name)
: BaseNode (BaseNode::Camera, name)
, mFOV (0.75f) // in radians
, mNear (0.1f)
, mFar (1000.f) // could be zero
, mCameraType (FREE)
{
}
ai_real mFOV, mNear, mFar;
CameraType mCameraType;
};
// ---------------------------------------------------------------------------
/** Helper structure to represent an ASE helper object (dummy) */
struct Dummy : public BaseNode {
//! Constructor
Dummy() AI_NO_EXCEPT
: BaseNode (BaseNode::Dummy, "DUMMY") {
// empty
}
};
// Parameters to Parser::Parse()
#define AI_ASE_NEW_FILE_FORMAT 200
#define AI_ASE_OLD_FILE_FORMAT 110
// Internally we're a little bit more tolerant
#define AI_ASE_IS_NEW_FILE_FORMAT() (iFileFormat >= 200)
#define AI_ASE_IS_OLD_FILE_FORMAT() (iFileFormat < 200)
// -------------------------------------------------------------------------------
/** \brief Class to parse ASE files
*/
class Parser {
private:
Parser() AI_NO_EXCEPT {
// empty
}
public:
// -------------------------------------------------------------------
//! Construct a parser from a given input file which is
//! guaranteed to be terminated with zero.
//! @param szFile Input file
//! @param fileFormatDefault Assumed file format version. If the
//! file format is specified in the file the new value replaces
//! the default value.
Parser (const char* szFile, unsigned int fileFormatDefault);
// -------------------------------------------------------------------
//! Parses the file into the parsers internal representation
void Parse();
private:
// -------------------------------------------------------------------
//! Parse the *SCENE block in a file
void ParseLV1SceneBlock();
// -------------------------------------------------------------------
//! Parse the *MESH_SOFTSKINVERTS block in a file
void ParseLV1SoftSkinBlock();
// -------------------------------------------------------------------
//! Parse the *MATERIAL_LIST block in a file
void ParseLV1MaterialListBlock();
// -------------------------------------------------------------------
//! Parse a *<xxx>OBJECT block in a file
//! \param mesh Node to be filled
void ParseLV1ObjectBlock(BaseNode& mesh);
// -------------------------------------------------------------------
//! Parse a *MATERIAL blocks in a material list
//! \param mat Material structure to be filled
void ParseLV2MaterialBlock(Material& mat);
// -------------------------------------------------------------------
//! Parse a *NODE_TM block in a file
//! \param mesh Node (!) object to be filled
void ParseLV2NodeTransformBlock(BaseNode& mesh);
// -------------------------------------------------------------------
//! Parse a *TM_ANIMATION block in a file
//! \param mesh Mesh object to be filled
void ParseLV2AnimationBlock(BaseNode& mesh);
void ParseLV3PosAnimationBlock(ASE::Animation& anim);
void ParseLV3ScaleAnimationBlock(ASE::Animation& anim);
void ParseLV3RotAnimationBlock(ASE::Animation& anim);
// -------------------------------------------------------------------
//! Parse a *MESH block in a file
//! \param mesh Mesh object to be filled
void ParseLV2MeshBlock(Mesh& mesh);
// -------------------------------------------------------------------
//! Parse a *LIGHT_SETTINGS block in a file
//! \param light Light object to be filled
void ParseLV2LightSettingsBlock(Light& light);
// -------------------------------------------------------------------
//! Parse a *CAMERA_SETTINGS block in a file
//! \param cam Camera object to be filled
void ParseLV2CameraSettingsBlock(Camera& cam);
// -------------------------------------------------------------------
//! Parse the *MAP_XXXXXX blocks in a material
//! \param map Texture structure to be filled
void ParseLV3MapBlock(Texture& map);
// -------------------------------------------------------------------
//! Parse a *MESH_VERTEX_LIST block in a file
//! \param iNumVertices Value of *MESH_NUMVERTEX, if present.
//! Otherwise zero. This is used to check the consistency of the file.
//! A warning is sent to the logger if the validations fails.
//! \param mesh Mesh object to be filled
void ParseLV3MeshVertexListBlock(
unsigned int iNumVertices,Mesh& mesh);
// -------------------------------------------------------------------
//! Parse a *MESH_FACE_LIST block in a file
//! \param iNumFaces Value of *MESH_NUMFACES, if present.
//! Otherwise zero. This is used to check the consistency of the file.
//! A warning is sent to the logger if the validations fails.
//! \param mesh Mesh object to be filled
void ParseLV3MeshFaceListBlock(
unsigned int iNumFaces,Mesh& mesh);
// -------------------------------------------------------------------
//! Parse a *MESH_TVERT_LIST block in a file
//! \param iNumVertices Value of *MESH_NUMTVERTEX, if present.
//! Otherwise zero. This is used to check the consistency of the file.
//! A warning is sent to the logger if the validations fails.
//! \param mesh Mesh object to be filled
//! \param iChannel Output UVW channel
void ParseLV3MeshTListBlock(
unsigned int iNumVertices,Mesh& mesh, unsigned int iChannel = 0);
// -------------------------------------------------------------------
//! Parse a *MESH_TFACELIST block in a file
//! \param iNumFaces Value of *MESH_NUMTVFACES, if present.
//! Otherwise zero. This is used to check the consistency of the file.
//! A warning is sent to the logger if the validations fails.
//! \param mesh Mesh object to be filled
//! \param iChannel Output UVW channel
void ParseLV3MeshTFaceListBlock(
unsigned int iNumFaces,Mesh& mesh, unsigned int iChannel = 0);
// -------------------------------------------------------------------
//! Parse an additional mapping channel
//! (specified via *MESH_MAPPINGCHANNEL)
//! \param iChannel Channel index to be filled
//! \param mesh Mesh object to be filled
void ParseLV3MappingChannel(
unsigned int iChannel, Mesh& mesh);
// -------------------------------------------------------------------
//! Parse a *MESH_CVERTLIST block in a file
//! \param iNumVertices Value of *MESH_NUMCVERTEX, if present.
//! Otherwise zero. This is used to check the consistency of the file.
//! A warning is sent to the logger if the validations fails.
//! \param mesh Mesh object to be filled
void ParseLV3MeshCListBlock(
unsigned int iNumVertices, Mesh& mesh);
// -------------------------------------------------------------------
//! Parse a *MESH_CFACELIST block in a file
//! \param iNumFaces Value of *MESH_NUMCVFACES, if present.
//! Otherwise zero. This is used to check the consistency of the file.
//! A warning is sent to the logger if the validations fails.
//! \param mesh Mesh object to be filled
void ParseLV3MeshCFaceListBlock(
unsigned int iNumFaces, Mesh& mesh);
// -------------------------------------------------------------------
//! Parse a *MESH_NORMALS block in a file
//! \param mesh Mesh object to be filled
void ParseLV3MeshNormalListBlock(Mesh& mesh);
// -------------------------------------------------------------------
//! Parse a *MESH_WEIGHTSblock in a file
//! \param mesh Mesh object to be filled
void ParseLV3MeshWeightsBlock(Mesh& mesh);
// -------------------------------------------------------------------
//! Parse the bone list of a file
//! \param mesh Mesh object to be filled
//! \param iNumBones Number of bones in the mesh
void ParseLV4MeshBones(unsigned int iNumBones,Mesh& mesh);
// -------------------------------------------------------------------
//! Parse the bone vertices list of a file
//! \param mesh Mesh object to be filled
//! \param iNumVertices Number of vertices to be parsed
void ParseLV4MeshBonesVertices(unsigned int iNumVertices,Mesh& mesh);
// -------------------------------------------------------------------
//! Parse a *MESH_FACE block in a file
//! \param out receive the face data
void ParseLV4MeshFace(ASE::Face& out);
// -------------------------------------------------------------------
//! Parse a *MESH_VERT block in a file
//! (also works for MESH_TVERT, MESH_CFACE, MESH_VERTCOL ...)
//! \param apOut Output buffer (3 floats)
//! \param rIndexOut Output index
void ParseLV4MeshFloatTriple(ai_real* apOut, unsigned int& rIndexOut);
// -------------------------------------------------------------------
//! Parse a *MESH_VERT block in a file
//! (also works for MESH_TVERT, MESH_CFACE, MESH_VERTCOL ...)
//! \param apOut Output buffer (3 floats)
void ParseLV4MeshFloatTriple(ai_real* apOut);
// -------------------------------------------------------------------
//! Parse a *MESH_TFACE block in a file
//! (also works for MESH_CFACE)
//! \param apOut Output buffer (3 ints)
//! \param rIndexOut Output index
void ParseLV4MeshLongTriple(unsigned int* apOut, unsigned int& rIndexOut);
// -------------------------------------------------------------------
//! Parse a *MESH_TFACE block in a file
//! (also works for MESH_CFACE)
//! \param apOut Output buffer (3 ints)
void ParseLV4MeshLongTriple(unsigned int* apOut);
// -------------------------------------------------------------------
//! Parse a single float element
//! \param fOut Output float
void ParseLV4MeshFloat(ai_real& fOut);
// -------------------------------------------------------------------
//! Parse a single int element
//! \param iOut Output integer
void ParseLV4MeshLong(unsigned int& iOut);
// -------------------------------------------------------------------
//! Skip everything to the next: '*' or '\0'
bool SkipToNextToken();
// -------------------------------------------------------------------
//! Skip the current section until the token after the closing }.
//! This function handles embedded subsections correctly
bool SkipSection();
// -------------------------------------------------------------------
//! Output a warning to the logger
//! \param szWarn Warn message
void LogWarning(const char* szWarn);
// -------------------------------------------------------------------
//! Output a message to the logger
//! \param szWarn Message
void LogInfo(const char* szWarn);
// -------------------------------------------------------------------
//! Output an error to the logger
//! \param szWarn Error message
AI_WONT_RETURN void LogError(const char* szWarn) AI_WONT_RETURN_SUFFIX;
// -------------------------------------------------------------------
//! Parse a string, enclosed in double quotation marks
//! \param out Output string
//! \param szName Name of the enclosing element -> used in error
//! messages.
//! \return false if an error occurred
bool ParseString(std::string& out,const char* szName);
public:
//! Pointer to current data
const char* filePtr;
//! background color to be passed to the viewer
//! QNAN if none was found
aiColor3D m_clrBackground;
//! Base ambient color to be passed to all materials
//! QNAN if none was found
aiColor3D m_clrAmbient;
//! List of all materials found in the file
std::vector<Material> m_vMaterials;
//! List of all meshes found in the file
std::vector<Mesh> m_vMeshes;
//! List of all dummies found in the file
std::vector<Dummy> m_vDummies;
//! List of all lights found in the file
std::vector<Light> m_vLights;
//! List of all cameras found in the file
std::vector<Camera> m_vCameras;
//! Current line in the file
unsigned int iLineNumber;
//! First frame
unsigned int iFirstFrame;
//! Last frame
unsigned int iLastFrame;
//! Frame speed - frames per second
unsigned int iFrameSpeed;
//! Ticks per frame
unsigned int iTicksPerFrame;
//! true if the last character read was an end-line character
bool bLastWasEndLine;
//! File format version
unsigned int iFileFormat;
};
} // Namespace ASE
} // Namespace ASSIMP
#endif // ASSIMP_BUILD_NO_3DS_IMPORTER
#endif // !! include guard
/*
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 AssbinExporter.cpp
* ASSBIN exporter main code
*/
#ifndef ASSIMP_BUILD_NO_EXPORT
#ifndef ASSIMP_BUILD_NO_ASSBIN_EXPORTER
#include "AssbinFileWriter.h"
#include <assimp/scene.h>
#include <assimp/Exporter.hpp>
#include <assimp/IOSystem.hpp>
namespace Assimp {
void ExportSceneAssbin(const char *pFile, IOSystem *pIOSystem, const aiScene *pScene, const ExportProperties * /*pProperties*/) {
DumpSceneToAssbin(
pFile,
"\0", // no command(s).
pIOSystem,
pScene,
false, // shortened?
false); // compressed?
}
} // end of namespace Assimp
#endif // ASSIMP_BUILD_NO_ASSBIN_EXPORTER
#endif // ASSIMP_BUILD_NO_EXPORT
/*
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 AssbinExporter.h
* ASSBIN Exporter Main Header
*/
#ifndef AI_ASSBINEXPORTER_H_INC
#define AI_ASSBINEXPORTER_H_INC
#include <assimp/defs.h>
// nothing really needed here - reserved for future use like properties
namespace Assimp {
void ASSIMP_API ExportSceneAssbin(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* /*pProperties*/);
}
#endif // AI_ASSBINEXPORTER_H_INC
/*
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 AssbinFileWriter.cpp
* @brief Implementation of Assbin file writer.
*/
#include "AssbinFileWriter.h"
#include "Common/assbin_chunks.h"
#include "PostProcessing/ProcessHelper.h"
#include <assimp/Exceptional.h>
#include <assimp/version.h>
#include <assimp/Exporter.hpp>
#include <assimp/IOStream.hpp>
#ifdef ASSIMP_BUILD_NO_OWN_ZLIB
#include <zlib.h>
#else
#include "../contrib/zlib/zlib.h"
#endif
#include <time.h>
#ifdef _WIN32
#pragma warning(push)
#pragma warning(disable : 4706)
#endif // _WIN32
namespace Assimp {
template <typename T>
size_t Write(IOStream *stream, const T &v) {
return stream->Write(&v, sizeof(T), 1);
}
// -----------------------------------------------------------------------------------
// Serialize an aiString
template <>
inline size_t Write<aiString>(IOStream *stream, const aiString &s) {
const size_t s2 = (uint32_t)s.length;
stream->Write(&s, 4, 1);
stream->Write(s.data, s2, 1);
return s2 + 4;
}
// -----------------------------------------------------------------------------------
// Serialize an unsigned int as uint32_t
template <>
inline size_t Write<unsigned int>(IOStream *stream, const unsigned int &w) {
const uint32_t t = (uint32_t)w;
if (w > t) {
// this shouldn't happen, integers in Assimp data structures never exceed 2^32
throw DeadlyExportError("loss of data due to 64 -> 32 bit integer conversion");
}
stream->Write(&t, 4, 1);
return 4;
}
// -----------------------------------------------------------------------------------
// Serialize an unsigned int as uint16_t
template <>
inline size_t Write<uint16_t>(IOStream *stream, const uint16_t &w) {
static_assert(sizeof(uint16_t) == 2, "sizeof(uint16_t)==2");
stream->Write(&w, 2, 1);
return 2;
}
// -----------------------------------------------------------------------------------
// Serialize a float
template <>
inline size_t Write<float>(IOStream *stream, const float &f) {
static_assert(sizeof(float) == 4, "sizeof(float)==4");
stream->Write(&f, 4, 1);
return 4;
}
// -----------------------------------------------------------------------------------
// Serialize a double
template <>
inline size_t Write<double>(IOStream *stream, const double &f) {
static_assert(sizeof(double) == 8, "sizeof(double)==8");
stream->Write(&f, 8, 1);
return 8;
}
// -----------------------------------------------------------------------------------
// Serialize a vec3
template <>
inline size_t Write<aiVector3D>(IOStream *stream, const aiVector3D &v) {
size_t t = Write<float>(stream, v.x);
t += Write<float>(stream, v.y);
t += Write<float>(stream, v.z);
return t;
}
// -----------------------------------------------------------------------------------
// Serialize a color value
template <>
inline size_t Write<aiColor3D>(IOStream *stream, const aiColor3D &v) {
size_t t = Write<float>(stream, v.r);
t += Write<float>(stream, v.g);
t += Write<float>(stream, v.b);
return t;
}
// -----------------------------------------------------------------------------------
// Serialize a color value
template <>
inline size_t Write<aiColor4D>(IOStream *stream, const aiColor4D &v) {
size_t t = Write<float>(stream, v.r);
t += Write<float>(stream, v.g);
t += Write<float>(stream, v.b);
t += Write<float>(stream, v.a);
return t;
}
// -----------------------------------------------------------------------------------
// Serialize a quaternion
template <>
inline size_t Write<aiQuaternion>(IOStream *stream, const aiQuaternion &v) {
size_t t = Write<float>(stream, v.w);
t += Write<float>(stream, v.x);
t += Write<float>(stream, v.y);
t += Write<float>(stream, v.z);
ai_assert(t == 16);
return 16;
}
// -----------------------------------------------------------------------------------
// Serialize a vertex weight
template <>
inline size_t Write<aiVertexWeight>(IOStream *stream, const aiVertexWeight &v) {
size_t t = Write<unsigned int>(stream, v.mVertexId);
return t + Write<float>(stream, v.mWeight);
}
// -----------------------------------------------------------------------------------
// Serialize a mat4x4
template <>
inline size_t Write<aiMatrix4x4>(IOStream *stream, const aiMatrix4x4 &m) {
for (unsigned int i = 0; i < 4; ++i) {
for (unsigned int i2 = 0; i2 < 4; ++i2) {
Write<float>(stream, m[i][i2]);
}
}
return 64;
}
// -----------------------------------------------------------------------------------
// Serialize an aiVectorKey
template <>
inline size_t Write<aiVectorKey>(IOStream *stream, const aiVectorKey &v) {
const size_t t = Write<double>(stream, v.mTime);
return t + Write<aiVector3D>(stream, v.mValue);
}
// -----------------------------------------------------------------------------------
// Serialize an aiQuatKey
template <>
inline size_t Write<aiQuatKey>(IOStream *stream, const aiQuatKey &v) {
const size_t t = Write<double>(stream, v.mTime);
return t + Write<aiQuaternion>(stream, v.mValue);
}
template <typename T>
inline size_t WriteBounds(IOStream *stream, const T *in, unsigned int size) {
T minc, maxc;
ArrayBounds(in, size, minc, maxc);
const size_t t = Write<T>(stream, minc);
return t + Write<T>(stream, maxc);
}
// We use this to write out non-byte arrays so that we write using the specializations.
// This way we avoid writing out extra bytes that potentially come from struct alignment.
template <typename T>
inline size_t WriteArray(IOStream *stream, const T *in, unsigned int size) {
size_t n = 0;
for (unsigned int i = 0; i < size; i++)
n += Write<T>(stream, in[i]);
return n;
}
// ----------------------------------------------------------------------------------
/** @class AssbinChunkWriter
* @brief Chunk writer mechanism for the .assbin file structure
*
* This is a standard in-memory IOStream (most of the code is based on BlobIOStream),
* the difference being that this takes another IOStream as a "container" in the
* constructor, and when it is destroyed, it appends the magic number, the chunk size,
* and the chunk contents to the container stream. This allows relatively easy chunk
* chunk construction, even recursively.
*/
class AssbinChunkWriter : public IOStream {
private:
uint8_t *buffer;
uint32_t magic;
IOStream *container;
size_t cur_size, cursor, initial;
private:
// -------------------------------------------------------------------
void Grow(size_t need = 0) {
size_t new_size = std::max(initial, std::max(need, cur_size + (cur_size >> 1)));
const uint8_t *const old = buffer;
buffer = new uint8_t[new_size];
if (old) {
memcpy(buffer, old, cur_size);
delete[] old;
}
cur_size = new_size;
}
public:
AssbinChunkWriter(IOStream *container, uint32_t magic, size_t initial = 4096) :
buffer(nullptr),
magic(magic),
container(container),
cur_size(0),
cursor(0),
initial(initial) {
// empty
}
virtual ~AssbinChunkWriter() {
if (container) {
container->Write(&magic, sizeof(uint32_t), 1);
container->Write(&cursor, sizeof(uint32_t), 1);
container->Write(buffer, 1, cursor);
}
if (buffer) delete[] buffer;
}
void *GetBufferPointer() { return buffer; }
// -------------------------------------------------------------------
virtual size_t Read(void * /*pvBuffer*/, size_t /*pSize*/, size_t /*pCount*/) {
return 0;
}
virtual aiReturn Seek(size_t /*pOffset*/, aiOrigin /*pOrigin*/) {
return aiReturn_FAILURE;
}
virtual size_t Tell() const {
return cursor;
}
virtual void Flush() {
// not implemented
}
virtual size_t FileSize() const {
return cursor;
}
// -------------------------------------------------------------------
virtual size_t Write(const void *pvBuffer, size_t pSize, size_t pCount) {
pSize *= pCount;
if (cursor + pSize > cur_size) {
Grow(cursor + pSize);
}
memcpy(buffer + cursor, pvBuffer, pSize);
cursor += pSize;
return pCount;
}
};
// ----------------------------------------------------------------------------------
/** @class AssbinFileWriter
* @brief Assbin file writer class
*
* This class writes an .assbin file, and is responsible for the file layout.
*/
class AssbinFileWriter {
private:
bool shortened;
bool compressed;
protected:
// -----------------------------------------------------------------------------------
void WriteBinaryNode(IOStream *container, const aiNode *node) {
AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AINODE);
unsigned int nb_metadata = (node->mMetaData != NULL ? node->mMetaData->mNumProperties : 0);
Write<aiString>(&chunk, node->mName);
Write<aiMatrix4x4>(&chunk, node->mTransformation);
Write<unsigned int>(&chunk, node->mNumChildren);
Write<unsigned int>(&chunk, node->mNumMeshes);
Write<unsigned int>(&chunk, nb_metadata);
for (unsigned int i = 0; i < node->mNumMeshes; ++i) {
Write<unsigned int>(&chunk, node->mMeshes[i]);
}
for (unsigned int i = 0; i < node->mNumChildren; ++i) {
WriteBinaryNode(&chunk, node->mChildren[i]);
}
for (unsigned int i = 0; i < nb_metadata; ++i) {
const aiString &key = node->mMetaData->mKeys[i];
aiMetadataType type = node->mMetaData->mValues[i].mType;
void *value = node->mMetaData->mValues[i].mData;
Write<aiString>(&chunk, key);
Write<uint16_t>(&chunk, (uint16_t)type);
switch (type) {
case AI_BOOL:
Write<bool>(&chunk, *((bool *)value));
break;
case AI_INT32:
Write<int32_t>(&chunk, *((int32_t *)value));
break;
case AI_UINT64:
Write<uint64_t>(&chunk, *((uint64_t *)value));
break;
case AI_FLOAT:
Write<float>(&chunk, *((float *)value));
break;
case AI_DOUBLE:
Write<double>(&chunk, *((double *)value));
break;
case AI_AISTRING:
Write<aiString>(&chunk, *((aiString *)value));
break;
case AI_AIVECTOR3D:
Write<aiVector3D>(&chunk, *((aiVector3D *)value));
break;
#ifdef SWIG
case FORCE_32BIT:
#endif // SWIG
default:
break;
}
}
}
// -----------------------------------------------------------------------------------
void WriteBinaryTexture(IOStream *container, const aiTexture *tex) {
AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AITEXTURE);
Write<unsigned int>(&chunk, tex->mWidth);
Write<unsigned int>(&chunk, tex->mHeight);
// Write the texture format, but don't include the null terminator.
chunk.Write(tex->achFormatHint, sizeof(char), HINTMAXTEXTURELEN - 1);
if (!shortened) {
if (!tex->mHeight) {
chunk.Write(tex->pcData, 1, tex->mWidth);
} else {
chunk.Write(tex->pcData, 1, tex->mWidth * tex->mHeight * 4);
}
}
}
// -----------------------------------------------------------------------------------
void WriteBinaryBone(IOStream *container, const aiBone *b) {
AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AIBONE);
Write<aiString>(&chunk, b->mName);
Write<unsigned int>(&chunk, b->mNumWeights);
Write<aiMatrix4x4>(&chunk, b->mOffsetMatrix);
// for the moment we write dumb min/max values for the bones, too.
// maybe I'll add a better, hash-like solution later
if (shortened) {
WriteBounds(&chunk, b->mWeights, b->mNumWeights);
} // else write as usual
else
WriteArray<aiVertexWeight>(&chunk, b->mWeights, b->mNumWeights);
}
// -----------------------------------------------------------------------------------
void WriteBinaryMesh(IOStream *container, const aiMesh *mesh) {
AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AIMESH);
Write<unsigned int>(&chunk, mesh->mPrimitiveTypes);
Write<unsigned int>(&chunk, mesh->mNumVertices);
Write<unsigned int>(&chunk, mesh->mNumFaces);
Write<unsigned int>(&chunk, mesh->mNumBones);
Write<unsigned int>(&chunk, mesh->mMaterialIndex);
// first of all, write bits for all existent vertex components
unsigned int c = 0;
if (mesh->mVertices) {
c |= ASSBIN_MESH_HAS_POSITIONS;
}
if (mesh->mNormals) {
c |= ASSBIN_MESH_HAS_NORMALS;
}
if (mesh->mTangents && mesh->mBitangents) {
c |= ASSBIN_MESH_HAS_TANGENTS_AND_BITANGENTS;
}
for (unsigned int n = 0; n < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++n) {
if (!mesh->mTextureCoords[n]) {
break;
}
c |= ASSBIN_MESH_HAS_TEXCOORD(n);
}
for (unsigned int n = 0; n < AI_MAX_NUMBER_OF_COLOR_SETS; ++n) {
if (!mesh->mColors[n]) {
break;
}
c |= ASSBIN_MESH_HAS_COLOR(n);
}
Write<unsigned int>(&chunk, c);
aiVector3D minVec, maxVec;
if (mesh->mVertices) {
if (shortened) {
WriteBounds(&chunk, mesh->mVertices, mesh->mNumVertices);
} // else write as usual
else
WriteArray<aiVector3D>(&chunk, mesh->mVertices, mesh->mNumVertices);
}
if (mesh->mNormals) {
if (shortened) {
WriteBounds(&chunk, mesh->mNormals, mesh->mNumVertices);
} // else write as usual
else
WriteArray<aiVector3D>(&chunk, mesh->mNormals, mesh->mNumVertices);
}
if (mesh->mTangents && mesh->mBitangents) {
if (shortened) {
WriteBounds(&chunk, mesh->mTangents, mesh->mNumVertices);
WriteBounds(&chunk, mesh->mBitangents, mesh->mNumVertices);
} // else write as usual
else {
WriteArray<aiVector3D>(&chunk, mesh->mTangents, mesh->mNumVertices);
WriteArray<aiVector3D>(&chunk, mesh->mBitangents, mesh->mNumVertices);
}
}
for (unsigned int n = 0; n < AI_MAX_NUMBER_OF_COLOR_SETS; ++n) {
if (!mesh->mColors[n])
break;
if (shortened) {
WriteBounds(&chunk, mesh->mColors[n], mesh->mNumVertices);
} // else write as usual
else
WriteArray<aiColor4D>(&chunk, mesh->mColors[n], mesh->mNumVertices);
}
for (unsigned int n = 0; n < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++n) {
if (!mesh->mTextureCoords[n])
break;
// write number of UV components
Write<unsigned int>(&chunk, mesh->mNumUVComponents[n]);
if (shortened) {
WriteBounds(&chunk, mesh->mTextureCoords[n], mesh->mNumVertices);
} // else write as usual
else
WriteArray<aiVector3D>(&chunk, mesh->mTextureCoords[n], mesh->mNumVertices);
}
// write faces. There are no floating-point calculations involved
// in these, so we can write a simple hash over the face data
// to the dump file. We generate a single 32 Bit hash for 512 faces
// using Assimp's standard hashing function.
if (shortened) {
unsigned int processed = 0;
for (unsigned int job; (job = std::min(mesh->mNumFaces - processed, 512u)); processed += job) {
uint32_t hash = 0;
for (unsigned int a = 0; a < job; ++a) {
const aiFace &f = mesh->mFaces[processed + a];
uint32_t tmp = f.mNumIndices;
hash = SuperFastHash(reinterpret_cast<const char *>(&tmp), sizeof tmp, hash);
for (unsigned int i = 0; i < f.mNumIndices; ++i) {
static_assert(AI_MAX_VERTICES <= 0xffffffff, "AI_MAX_VERTICES <= 0xffffffff");
tmp = static_cast<uint32_t>(f.mIndices[i]);
hash = SuperFastHash(reinterpret_cast<const char *>(&tmp), sizeof tmp, hash);
}
}
Write<unsigned int>(&chunk, hash);
}
} else // else write as usual
{
// if there are less than 2^16 vertices, we can simply use 16 bit integers ...
for (unsigned int i = 0; i < mesh->mNumFaces; ++i) {
const aiFace &f = mesh->mFaces[i];
static_assert(AI_MAX_FACE_INDICES <= 0xffff, "AI_MAX_FACE_INDICES <= 0xffff");
Write<uint16_t>(&chunk, static_cast<uint16_t>(f.mNumIndices));
for (unsigned int a = 0; a < f.mNumIndices; ++a) {
if (mesh->mNumVertices < (1u << 16)) {
Write<uint16_t>(&chunk, static_cast<uint16_t>(f.mIndices[a]));
} else {
Write<unsigned int>(&chunk, f.mIndices[a]);
}
}
}
}
// write bones
if (mesh->mNumBones) {
for (unsigned int a = 0; a < mesh->mNumBones; ++a) {
const aiBone *b = mesh->mBones[a];
WriteBinaryBone(&chunk, b);
}
}
}
// -----------------------------------------------------------------------------------
void WriteBinaryMaterialProperty(IOStream *container, const aiMaterialProperty *prop) {
AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AIMATERIALPROPERTY);
Write<aiString>(&chunk, prop->mKey);
Write<unsigned int>(&chunk, prop->mSemantic);
Write<unsigned int>(&chunk, prop->mIndex);
Write<unsigned int>(&chunk, prop->mDataLength);
Write<unsigned int>(&chunk, (unsigned int)prop->mType);
chunk.Write(prop->mData, 1, prop->mDataLength);
}
// -----------------------------------------------------------------------------------
void WriteBinaryMaterial(IOStream *container, const aiMaterial *mat) {
AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AIMATERIAL);
Write<unsigned int>(&chunk, mat->mNumProperties);
for (unsigned int i = 0; i < mat->mNumProperties; ++i) {
WriteBinaryMaterialProperty(&chunk, mat->mProperties[i]);
}
}
// -----------------------------------------------------------------------------------
void WriteBinaryNodeAnim(IOStream *container, const aiNodeAnim *nd) {
AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AINODEANIM);
Write<aiString>(&chunk, nd->mNodeName);
Write<unsigned int>(&chunk, nd->mNumPositionKeys);
Write<unsigned int>(&chunk, nd->mNumRotationKeys);
Write<unsigned int>(&chunk, nd->mNumScalingKeys);
Write<unsigned int>(&chunk, nd->mPreState);
Write<unsigned int>(&chunk, nd->mPostState);
if (nd->mPositionKeys) {
if (shortened) {
WriteBounds(&chunk, nd->mPositionKeys, nd->mNumPositionKeys);
} // else write as usual
else
WriteArray<aiVectorKey>(&chunk, nd->mPositionKeys, nd->mNumPositionKeys);
}
if (nd->mRotationKeys) {
if (shortened) {
WriteBounds(&chunk, nd->mRotationKeys, nd->mNumRotationKeys);
} // else write as usual
else
WriteArray<aiQuatKey>(&chunk, nd->mRotationKeys, nd->mNumRotationKeys);
}
if (nd->mScalingKeys) {
if (shortened) {
WriteBounds(&chunk, nd->mScalingKeys, nd->mNumScalingKeys);
} // else write as usual
else
WriteArray<aiVectorKey>(&chunk, nd->mScalingKeys, nd->mNumScalingKeys);
}
}
// -----------------------------------------------------------------------------------
void WriteBinaryAnim(IOStream *container, const aiAnimation *anim) {
AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AIANIMATION);
Write<aiString>(&chunk, anim->mName);
Write<double>(&chunk, anim->mDuration);
Write<double>(&chunk, anim->mTicksPerSecond);
Write<unsigned int>(&chunk, anim->mNumChannels);
for (unsigned int a = 0; a < anim->mNumChannels; ++a) {
const aiNodeAnim *nd = anim->mChannels[a];
WriteBinaryNodeAnim(&chunk, nd);
}
}
// -----------------------------------------------------------------------------------
void WriteBinaryLight(IOStream *container, const aiLight *l) {
AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AILIGHT);
Write<aiString>(&chunk, l->mName);
Write<unsigned int>(&chunk, l->mType);
if (l->mType != aiLightSource_DIRECTIONAL) {
Write<float>(&chunk, l->mAttenuationConstant);
Write<float>(&chunk, l->mAttenuationLinear);
Write<float>(&chunk, l->mAttenuationQuadratic);
}
Write<aiColor3D>(&chunk, l->mColorDiffuse);
Write<aiColor3D>(&chunk, l->mColorSpecular);
Write<aiColor3D>(&chunk, l->mColorAmbient);
if (l->mType == aiLightSource_SPOT) {
Write<float>(&chunk, l->mAngleInnerCone);
Write<float>(&chunk, l->mAngleOuterCone);
}
}
// -----------------------------------------------------------------------------------
void WriteBinaryCamera(IOStream *container, const aiCamera *cam) {
AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AICAMERA);
Write<aiString>(&chunk, cam->mName);
Write<aiVector3D>(&chunk, cam->mPosition);
Write<aiVector3D>(&chunk, cam->mLookAt);
Write<aiVector3D>(&chunk, cam->mUp);
Write<float>(&chunk, cam->mHorizontalFOV);
Write<float>(&chunk, cam->mClipPlaneNear);
Write<float>(&chunk, cam->mClipPlaneFar);
Write<float>(&chunk, cam->mAspect);
}
// -----------------------------------------------------------------------------------
void WriteBinaryScene(IOStream *container, const aiScene *scene) {
AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AISCENE);
// basic scene information
Write<unsigned int>(&chunk, scene->mFlags);
Write<unsigned int>(&chunk, scene->mNumMeshes);
Write<unsigned int>(&chunk, scene->mNumMaterials);
Write<unsigned int>(&chunk, scene->mNumAnimations);
Write<unsigned int>(&chunk, scene->mNumTextures);
Write<unsigned int>(&chunk, scene->mNumLights);
Write<unsigned int>(&chunk, scene->mNumCameras);
// write node graph
WriteBinaryNode(&chunk, scene->mRootNode);
// write all meshes
for (unsigned int i = 0; i < scene->mNumMeshes; ++i) {
const aiMesh *mesh = scene->mMeshes[i];
WriteBinaryMesh(&chunk, mesh);
}
// write materials
for (unsigned int i = 0; i < scene->mNumMaterials; ++i) {
const aiMaterial *mat = scene->mMaterials[i];
WriteBinaryMaterial(&chunk, mat);
}
// write all animations
for (unsigned int i = 0; i < scene->mNumAnimations; ++i) {
const aiAnimation *anim = scene->mAnimations[i];
WriteBinaryAnim(&chunk, anim);
}
// write all textures
for (unsigned int i = 0; i < scene->mNumTextures; ++i) {
const aiTexture *mesh = scene->mTextures[i];
WriteBinaryTexture(&chunk, mesh);
}
// write lights
for (unsigned int i = 0; i < scene->mNumLights; ++i) {
const aiLight *l = scene->mLights[i];
WriteBinaryLight(&chunk, l);
}
// write cameras
for (unsigned int i = 0; i < scene->mNumCameras; ++i) {
const aiCamera *cam = scene->mCameras[i];
WriteBinaryCamera(&chunk, cam);
}
}
public:
AssbinFileWriter(bool shortened, bool compressed) :
shortened(shortened), compressed(compressed) {
}
// -----------------------------------------------------------------------------------
// Write a binary model dump
void WriteBinaryDump(const char *pFile, const char *cmd, IOSystem *pIOSystem, const aiScene *pScene) {
IOStream *out = pIOSystem->Open(pFile, "wb");
if (!out)
throw std::runtime_error("Unable to open output file " + std::string(pFile) + '\n');
auto CloseIOStream = [&]() {
if (out) {
pIOSystem->Close(out);
out = nullptr; // Ensure this is only done once.
}
};
try {
time_t tt = time(NULL);
#if _WIN32
tm *p = gmtime(&tt);
#else
struct tm now;
tm *p = gmtime_r(&tt, &now);
#endif
// header
char s[64];
memset(s, 0, 64);
#if _MSC_VER >= 1400
sprintf_s(s, "ASSIMP.binary-dump.%s", asctime(p));
#else
ai_snprintf(s, 64, "ASSIMP.binary-dump.%s", asctime(p));
#endif
out->Write(s, 44, 1);
// == 44 bytes
Write<unsigned int>(out, ASSBIN_VERSION_MAJOR);
Write<unsigned int>(out, ASSBIN_VERSION_MINOR);
Write<unsigned int>(out, aiGetVersionRevision());
Write<unsigned int>(out, aiGetCompileFlags());
Write<uint16_t>(out, shortened);
Write<uint16_t>(out, compressed);
// == 20 bytes
char buff[256] = { 0 };
ai_snprintf(buff, 256, "%s", pFile);
out->Write(buff, sizeof(char), 256);
memset(buff, 0, sizeof(buff));
ai_snprintf(buff, 128, "%s", cmd);
out->Write(buff, sizeof(char), 128);
// leave 64 bytes free for future extensions
memset(buff, 0xcd, 64);
out->Write(buff, sizeof(char), 64);
// == 435 bytes
// ==== total header size: 512 bytes
ai_assert(out->Tell() == ASSBIN_HEADER_LENGTH);
// Up to here the data is uncompressed. For compressed files, the rest
// is compressed using standard DEFLATE from zlib.
if (compressed) {
AssbinChunkWriter uncompressedStream(NULL, 0);
WriteBinaryScene(&uncompressedStream, pScene);
uLongf uncompressedSize = static_cast<uLongf>(uncompressedStream.Tell());
uLongf compressedSize = (uLongf)compressBound(uncompressedSize);
uint8_t *compressedBuffer = new uint8_t[compressedSize];
int res = compress2(compressedBuffer, &compressedSize, (const Bytef *)uncompressedStream.GetBufferPointer(), uncompressedSize, 9);
if (res != Z_OK) {
delete[] compressedBuffer;
throw DeadlyExportError("Compression failed.");
}
out->Write(&uncompressedSize, sizeof(uint32_t), 1);
out->Write(compressedBuffer, sizeof(char), compressedSize);
delete[] compressedBuffer;
} else {
WriteBinaryScene(out, pScene);
}
CloseIOStream();
} catch (...) {
CloseIOStream();
throw;
}
}
};
void DumpSceneToAssbin(
const char *pFile, const char *cmd, IOSystem *pIOSystem,
const aiScene *pScene, bool shortened, bool compressed) {
AssbinFileWriter fileWriter(shortened, compressed);
fileWriter.WriteBinaryDump(pFile, cmd, pIOSystem, pScene);
}
#ifdef _WIN32
#pragma warning(pop)
#endif // _WIN32
} // end of namespace Assimp
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment