assimp/code/AssetLib/MD5/MD5Loader.cpp

730 lines
30 KiB
C++
Raw Normal View History

/*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
2022-01-10 20:13:43 +00:00
Copyright (c) 2006-2022, assimp team
2018-01-28 18:42:05 +00:00
All rights reserved.
2015-05-19 03:52:10 +00:00
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.
2015-05-19 03:52:10 +00:00
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
2015-05-19 03:52:10 +00:00
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2015-05-19 03:52:10 +00:00
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2015-05-19 03:52:10 +00:00
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 MD5Loader.cpp
2015-05-19 03:52:10 +00:00
* @brief Implementation of the MD5 importer class
*/
#ifndef ASSIMP_BUILD_NO_MD5_IMPORTER
// internal headers
#include "MD5Loader.h"
2019-09-17 19:58:46 +00:00
#include <assimp/MathFunctions.h>
2020-03-01 12:15:45 +00:00
#include <assimp/RemoveComments.h>
#include <assimp/SkeletonMeshBuilder.h>
2020-03-01 12:15:45 +00:00
#include <assimp/StringComparison.h>
#include <assimp/fast_atof.h>
#include <assimp/importerdesc.h>
2016-06-06 20:04:29 +00:00
#include <assimp/scene.h>
#include <assimp/DefaultLogger.hpp>
2020-03-01 12:15:45 +00:00
#include <assimp/IOSystem.hpp>
#include <assimp/Importer.hpp>
#include <memory>
using namespace Assimp;
// Minimum weight value. Weights inside [-n ... n] are ignored
2019-09-17 19:58:46 +00:00
#define AI_MD5_WEIGHT_EPSILON Math::getEpsilon<float>()
2023-11-11 08:59:42 +00:00
static constexpr aiImporterDesc desc = {
2015-05-19 03:57:13 +00:00
"Doom 3 / MD5 Mesh Importer",
"",
"",
"",
aiImporterFlags_SupportBinaryFlavour,
0,
0,
0,
0,
"md5mesh md5camera md5anim"
};
// ------------------------------------------------------------------------------------------------
// Constructor to be privately used by Importer
2020-03-01 12:15:45 +00:00
MD5Importer::MD5Importer() :
2020-06-24 18:30:02 +00:00
mIOHandler(nullptr),
mBuffer(),
mFileSize(),
mLineNumber(),
mScene(),
mHadMD5Mesh(),
mHadMD5Anim(),
mHadMD5Camera(),
mCconfigNoAutoLoad(false) {
2020-03-01 12:15:45 +00:00
// empty
}
// ------------------------------------------------------------------------------------------------
2015-05-19 03:52:10 +00:00
// Returns whether the class can handle the format of the given file.
bool MD5Importer::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool /*checkSig*/) const {
static const char *tokens[] = { "MD5Version" };
return SearchFileHeaderForToken(pIOHandler, pFile, tokens, AI_COUNT_OF(tokens));
}
// ------------------------------------------------------------------------------------------------
// Get list of all supported extensions
2020-03-01 12:15:45 +00:00
const aiImporterDesc *MD5Importer::GetInfo() const {
2015-05-19 03:57:13 +00:00
return &desc;
}
// ------------------------------------------------------------------------------------------------
// Setup import properties
2020-03-01 12:15:45 +00:00
void MD5Importer::SetupProperties(const Importer *pImp) {
2015-05-19 03:57:13 +00:00
// AI_CONFIG_IMPORT_MD5_NO_ANIM_AUTOLOAD
2020-06-24 18:30:02 +00:00
mCconfigNoAutoLoad = (0 != pImp->GetPropertyInteger(AI_CONFIG_IMPORT_MD5_NO_ANIM_AUTOLOAD, 0));
}
// ------------------------------------------------------------------------------------------------
2015-05-19 03:52:10 +00:00
// Imports the given file into the given scene structure.
2020-06-24 18:30:02 +00:00
void MD5Importer::InternReadFile(const std::string &pFile, aiScene *_pScene, IOSystem *pIOHandler) {
2020-03-01 12:15:45 +00:00
mIOHandler = pIOHandler;
2020-06-24 18:30:02 +00:00
mScene = _pScene;
mHadMD5Mesh = mHadMD5Anim = mHadMD5Camera = false;
2015-05-19 03:57:13 +00:00
// remove the file extension
const std::string::size_type pos = pFile.find_last_of('.');
2020-03-01 12:15:45 +00:00
mFile = (std::string::npos == pos ? pFile : pFile.substr(0, pos + 1));
2015-05-19 03:57:13 +00:00
const std::string extension = GetExtension(pFile);
try {
if (extension == "md5camera") {
LoadMD5CameraFile();
2020-06-24 18:30:02 +00:00
} else if (mCconfigNoAutoLoad || extension == "md5anim") {
2015-05-19 03:57:13 +00:00
// determine file extension and process just *one* file
if (extension.length() == 0) {
throw DeadlyImportError("Failure, need file extension to determine MD5 part type");
}
if (extension == "md5anim") {
LoadMD5AnimFile();
2020-03-01 12:15:45 +00:00
} else if (extension == "md5mesh") {
2015-05-19 03:57:13 +00:00
LoadMD5MeshFile();
}
2020-03-01 12:15:45 +00:00
} else {
2015-05-19 03:57:13 +00:00
LoadMD5MeshFile();
LoadMD5AnimFile();
}
2020-03-01 12:15:45 +00:00
} catch (...) { // std::exception, Assimp::DeadlyImportError
2015-05-19 03:57:13 +00:00
UnloadFileFromMemory();
throw;
}
// make sure we have at least one file
2020-06-24 18:30:02 +00:00
if (!mHadMD5Mesh && !mHadMD5Anim && !mHadMD5Camera) {
2015-05-19 03:57:13 +00:00
throw DeadlyImportError("Failed to read valid contents out of this MD5* file");
}
// Now rotate the whole scene 90 degrees around the x axis to match our internal coordinate system
2020-06-24 18:30:02 +00:00
mScene->mRootNode->mTransformation = aiMatrix4x4(1.f, 0.f, 0.f, 0.f,
2020-03-01 12:15:45 +00:00
0.f, 0.f, 1.f, 0.f, 0.f, -1.f, 0.f, 0.f, 0.f, 0.f, 0.f, 1.f);
2015-05-19 03:57:13 +00:00
// the output scene wouldn't pass the validation without this flag
2020-06-24 18:30:02 +00:00
if (!mHadMD5Mesh) {
mScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
2015-05-19 03:57:13 +00:00
}
// clean the instance -- the BaseImporter instance may be reused later.
UnloadFileFromMemory();
}
// ------------------------------------------------------------------------------------------------
// Load a file into a memory buffer
2020-03-01 12:15:45 +00:00
void MD5Importer::LoadFileIntoMemory(IOStream *file) {
2015-05-19 03:57:13 +00:00
// unload the previous buffer, if any
UnloadFileFromMemory();
ai_assert(nullptr != file);
2020-06-24 18:30:02 +00:00
mFileSize = (unsigned int)file->FileSize();
ai_assert(mFileSize);
2015-05-19 03:57:13 +00:00
// allocate storage and copy the contents of the file to a memory buffer
2020-06-24 18:30:02 +00:00
mBuffer = new char[mFileSize + 1];
file->Read((void *)mBuffer, 1, mFileSize);
mLineNumber = 1;
2015-05-19 03:57:13 +00:00
// append a terminal 0
2020-06-24 18:30:02 +00:00
mBuffer[mFileSize] = '\0';
2015-05-19 03:57:13 +00:00
// now remove all line comments from the file
2020-03-01 12:15:45 +00:00
CommentRemover::RemoveLineComments("//", mBuffer, ' ');
}
// ------------------------------------------------------------------------------------------------
// Unload the current memory buffer
2020-03-01 12:15:45 +00:00
void MD5Importer::UnloadFileFromMemory() {
2015-05-19 03:57:13 +00:00
// delete the file buffer
delete[] mBuffer;
mBuffer = nullptr;
2020-06-24 18:30:02 +00:00
mFileSize = 0;
}
// ------------------------------------------------------------------------------------------------
// Build unique vertices
2020-03-01 12:15:45 +00:00
void MD5Importer::MakeDataUnique(MD5::MeshDesc &meshSrc) {
std::vector<bool> abHad(meshSrc.mVertices.size(), false);
2015-05-19 03:57:13 +00:00
// allocate enough storage to keep the output structures
2020-03-01 12:15:45 +00:00
const unsigned int iNewNum = static_cast<unsigned int>(meshSrc.mFaces.size() * 3);
unsigned int iNewIndex = static_cast<unsigned int>(meshSrc.mVertices.size());
2015-05-19 03:57:13 +00:00
meshSrc.mVertices.resize(iNewNum);
// try to guess how much storage we'll need for new weights
const float fWeightsPerVert = meshSrc.mWeights.size() / (float)iNewIndex;
2020-03-01 12:15:45 +00:00
const unsigned int guess = (unsigned int)(fWeightsPerVert * iNewNum);
2015-05-19 03:57:13 +00:00
meshSrc.mWeights.reserve(guess + (guess >> 3)); // + 12.5% as buffer
for (FaceArray::const_iterator iter = meshSrc.mFaces.begin(), iterEnd = meshSrc.mFaces.end(); iter != iterEnd; ++iter) {
2020-03-01 12:15:45 +00:00
const aiFace &face = *iter;
for (unsigned int i = 0; i < 3; ++i) {
2015-05-19 03:57:13 +00:00
if (face.mIndices[0] >= meshSrc.mVertices.size()) {
throw DeadlyImportError("MD5MESH: Invalid vertex index");
}
2020-03-01 12:15:45 +00:00
if (abHad[face.mIndices[i]]) {
2015-05-19 03:57:13 +00:00
// generate a new vertex
meshSrc.mVertices[iNewIndex] = meshSrc.mVertices[face.mIndices[i]];
face.mIndices[i] = iNewIndex++;
2020-03-01 12:15:45 +00:00
} else
abHad[face.mIndices[i]] = true;
2015-05-19 03:57:13 +00:00
}
// swap face order
2020-03-01 12:15:45 +00:00
std::swap(face.mIndices[0], face.mIndices[2]);
2015-05-19 03:57:13 +00:00
}
}
// ------------------------------------------------------------------------------------------------
// Recursive node graph construction from a MD5MESH
void MD5Importer::AttachChilds_Mesh(int iParentID, aiNode *piParent, BoneArray &bones) {
ai_assert(nullptr != piParent);
ai_assert(!piParent->mNumChildren);
2015-05-19 03:57:13 +00:00
// First find out how many children we'll have
2020-03-01 12:15:45 +00:00
for (int i = 0; i < (int)bones.size(); ++i) {
if (iParentID != i && bones[i].mParentIndex == iParentID) {
2015-05-19 03:57:13 +00:00
++piParent->mNumChildren;
}
}
if (piParent->mNumChildren) {
2020-03-01 12:15:45 +00:00
piParent->mChildren = new aiNode *[piParent->mNumChildren];
for (int i = 0; i < (int)bones.size(); ++i) {
2015-05-19 03:57:13 +00:00
// (avoid infinite recursion)
2020-03-01 12:15:45 +00:00
if (iParentID != i && bones[i].mParentIndex == iParentID) {
aiNode *pc;
2015-05-19 03:57:13 +00:00
// setup a new node
*piParent->mChildren++ = pc = new aiNode();
pc->mName = aiString(bones[i].mName);
pc->mParent = piParent;
// get the transformation matrix from rotation and translational components
aiQuaternion quat;
2020-03-01 12:15:45 +00:00
MD5::ConvertQuaternion(bones[i].mRotationQuat, quat);
2015-05-19 03:57:13 +00:00
2020-03-01 12:15:45 +00:00
bones[i].mTransform = aiMatrix4x4(quat.GetMatrix());
2015-05-19 03:57:13 +00:00
bones[i].mTransform.a4 = bones[i].mPositionXYZ.x;
bones[i].mTransform.b4 = bones[i].mPositionXYZ.y;
bones[i].mTransform.c4 = bones[i].mPositionXYZ.z;
// store it for later use
pc->mTransformation = bones[i].mInvTransform = bones[i].mTransform;
bones[i].mInvTransform.Inverse();
// the transformations for each bone are absolute, so we need to multiply them
// with the inverse of the absolute matrix of the parent joint
2020-03-01 12:15:45 +00:00
if (-1 != iParentID) {
2015-05-19 03:57:13 +00:00
pc->mTransformation = bones[iParentID].mInvTransform * pc->mTransformation;
}
// add children to this node, too
2020-03-01 12:15:45 +00:00
AttachChilds_Mesh(i, pc, bones);
2015-05-19 03:57:13 +00:00
}
}
// undo offset computations
piParent->mChildren -= piParent->mNumChildren;
}
}
// ------------------------------------------------------------------------------------------------
// Recursive node graph construction from a MD5ANIM
void MD5Importer::AttachChilds_Anim(int iParentID, aiNode *piParent, AnimBoneArray &bones, const aiNodeAnim **node_anims) {
ai_assert(nullptr != piParent);
ai_assert(!piParent->mNumChildren);
2015-05-19 03:57:13 +00:00
// First find out how many children we'll have
2020-03-01 12:15:45 +00:00
for (int i = 0; i < (int)bones.size(); ++i) {
if (iParentID != i && bones[i].mParentIndex == iParentID) {
2015-05-19 03:57:13 +00:00
++piParent->mNumChildren;
}
}
if (piParent->mNumChildren) {
2020-03-01 12:15:45 +00:00
piParent->mChildren = new aiNode *[piParent->mNumChildren];
for (int i = 0; i < (int)bones.size(); ++i) {
2015-05-19 03:57:13 +00:00
// (avoid infinite recursion)
2020-03-01 12:15:45 +00:00
if (iParentID != i && bones[i].mParentIndex == iParentID) {
aiNode *pc;
2015-05-19 03:57:13 +00:00
// setup a new node
*piParent->mChildren++ = pc = new aiNode();
pc->mName = aiString(bones[i].mName);
pc->mParent = piParent;
// get the corresponding animation channel and its first frame
2020-03-01 12:15:45 +00:00
const aiNodeAnim **cur = node_anims;
while ((**cur).mNodeName != pc->mName)
++cur;
2015-05-19 03:57:13 +00:00
2020-03-01 12:15:45 +00:00
aiMatrix4x4::Translation((**cur).mPositionKeys[0].mValue, pc->mTransformation);
pc->mTransformation = pc->mTransformation * aiMatrix4x4((**cur).mRotationKeys[0].mValue.GetMatrix());
2015-05-19 03:57:13 +00:00
// add children to this node, too
2020-03-01 12:15:45 +00:00
AttachChilds_Anim(i, pc, bones, node_anims);
2015-05-19 03:57:13 +00:00
}
}
// undo offset computations
piParent->mChildren -= piParent->mNumChildren;
}
}
// ------------------------------------------------------------------------------------------------
// Load a MD5MESH file
2020-03-01 12:15:45 +00:00
void MD5Importer::LoadMD5MeshFile() {
2020-06-21 10:03:38 +00:00
std::string filename = mFile + "md5mesh";
std::unique_ptr<IOStream> file(mIOHandler->Open(filename, "rb"));
2015-05-19 03:57:13 +00:00
// Check whether we can read from the file
if (file == nullptr || !file->FileSize()) {
2021-05-13 11:05:31 +00:00
ASSIMP_LOG_WARN("Failed to access MD5MESH file: ", filename);
2020-06-24 18:30:02 +00:00
return;
2015-05-19 03:57:13 +00:00
}
2020-06-24 18:30:02 +00:00
mHadMD5Mesh = true;
2015-05-19 03:57:13 +00:00
LoadFileIntoMemory(file.get());
// now construct a parser and parse the file
2020-06-24 18:30:02 +00:00
MD5::MD5Parser parser(mBuffer, mFileSize);
2015-05-19 03:57:13 +00:00
// load the mesh information from it
MD5::MD5MeshParser meshParser(parser.mSections);
// create the bone hierarchy - first the root node and dummy nodes for all meshes
2020-06-24 18:30:02 +00:00
mScene->mRootNode = new aiNode("<MD5_Root>");
mScene->mRootNode->mNumChildren = 2;
mScene->mRootNode->mChildren = new aiNode *[2];
2015-05-19 03:57:13 +00:00
// build the hierarchy from the MD5MESH file
2020-06-24 18:30:02 +00:00
aiNode *pcNode = mScene->mRootNode->mChildren[1] = new aiNode();
2015-05-19 03:57:13 +00:00
pcNode->mName.Set("<MD5_Hierarchy>");
2020-06-24 18:30:02 +00:00
pcNode->mParent = mScene->mRootNode;
2020-03-01 12:15:45 +00:00
AttachChilds_Mesh(-1, pcNode, meshParser.mJoints);
2015-05-19 03:57:13 +00:00
2020-06-24 18:30:02 +00:00
pcNode = mScene->mRootNode->mChildren[0] = new aiNode();
2015-05-19 03:57:13 +00:00
pcNode->mName.Set("<MD5_Mesh>");
2020-06-24 18:30:02 +00:00
pcNode->mParent = mScene->mRootNode;
#if 0
2015-05-19 03:57:13 +00:00
if (pScene->mRootNode->mChildren[1]->mNumChildren) /* start at the right hierarchy level */
SkeletonMeshBuilder skeleton_maker(pScene,pScene->mRootNode->mChildren[1]->mChildren[0]);
#else
2015-05-19 03:57:13 +00:00
// FIX: MD5 files exported from Blender can have empty meshes
2020-03-01 12:15:45 +00:00
for (std::vector<MD5::MeshDesc>::const_iterator it = meshParser.mMeshes.begin(), end = meshParser.mMeshes.end(); it != end; ++it) {
2020-06-24 18:30:02 +00:00
if (!(*it).mFaces.empty() && !(*it).mVertices.empty()) {
++mScene->mNumMaterials;
}
2015-05-19 03:57:13 +00:00
}
// generate all meshes
2020-06-24 18:30:02 +00:00
mScene->mNumMeshes = mScene->mNumMaterials;
mScene->mMeshes = new aiMesh *[mScene->mNumMeshes];
mScene->mMaterials = new aiMaterial *[mScene->mNumMeshes];
2015-05-19 03:57:13 +00:00
// storage for node mesh indices
2020-06-24 18:30:02 +00:00
pcNode->mNumMeshes = mScene->mNumMeshes;
2015-05-19 03:57:13 +00:00
pcNode->mMeshes = new unsigned int[pcNode->mNumMeshes];
2020-06-24 18:30:02 +00:00
for (unsigned int m = 0; m < pcNode->mNumMeshes; ++m) {
2015-05-19 03:57:13 +00:00
pcNode->mMeshes[m] = m;
2020-06-24 18:30:02 +00:00
}
2015-05-19 03:57:13 +00:00
unsigned int n = 0;
2020-03-01 12:15:45 +00:00
for (std::vector<MD5::MeshDesc>::iterator it = meshParser.mMeshes.begin(), end = meshParser.mMeshes.end(); it != end; ++it) {
MD5::MeshDesc &meshSrc = *it;
2020-06-24 18:30:02 +00:00
if (meshSrc.mFaces.empty() || meshSrc.mVertices.empty()) {
2015-05-19 03:57:13 +00:00
continue;
2020-06-24 18:30:02 +00:00
}
2015-05-19 03:57:13 +00:00
2020-06-24 18:30:02 +00:00
aiMesh *mesh = mScene->mMeshes[n] = new aiMesh();
2015-05-19 03:57:13 +00:00
mesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
// generate unique vertices in our internal verbose format
MakeDataUnique(meshSrc);
2020-03-01 12:15:45 +00:00
std::string name(meshSrc.mShader.C_Str());
2018-11-02 16:02:36 +00:00
name += ".msh";
mesh->mName = name;
2020-03-01 12:15:45 +00:00
mesh->mNumVertices = (unsigned int)meshSrc.mVertices.size();
2015-05-19 03:57:13 +00:00
mesh->mVertices = new aiVector3D[mesh->mNumVertices];
mesh->mTextureCoords[0] = new aiVector3D[mesh->mNumVertices];
mesh->mNumUVComponents[0] = 2;
// copy texture coordinates
2020-03-01 12:15:45 +00:00
aiVector3D *pv = mesh->mTextureCoords[0];
for (MD5::VertexArray::const_iterator iter = meshSrc.mVertices.begin(); iter != meshSrc.mVertices.end(); ++iter, ++pv) {
2015-05-19 03:57:13 +00:00
pv->x = (*iter).mUV.x;
2020-03-01 12:15:45 +00:00
pv->y = 1.0f - (*iter).mUV.y; // D3D to OpenGL
2015-05-19 03:57:13 +00:00
pv->z = 0.0f;
}
// sort all bone weights - per bone
2020-03-01 12:15:45 +00:00
unsigned int *piCount = new unsigned int[meshParser.mJoints.size()];
::memset(piCount, 0, sizeof(unsigned int) * meshParser.mJoints.size());
2015-05-19 03:57:13 +00:00
for (MD5::VertexArray::const_iterator iter = meshSrc.mVertices.begin(); iter != meshSrc.mVertices.end(); ++iter, ++pv) {
2020-03-01 12:15:45 +00:00
for (unsigned int jub = (*iter).mFirstWeight, w = jub; w < jub + (*iter).mNumWeights; ++w) {
MD5::WeightDesc &weightDesc = meshSrc.mWeights[w];
2015-05-19 03:57:13 +00:00
/* FIX for some invalid exporters */
2020-06-24 18:30:02 +00:00
if (!(weightDesc.mWeight < AI_MD5_WEIGHT_EPSILON && weightDesc.mWeight >= -AI_MD5_WEIGHT_EPSILON)) {
++piCount[weightDesc.mBone];
2020-06-24 18:30:02 +00:00
}
2015-05-19 03:57:13 +00:00
}
}
// check how many we will need
2020-06-24 18:30:02 +00:00
for (unsigned int p = 0; p < meshParser.mJoints.size(); ++p) {
2020-03-01 12:15:45 +00:00
if (piCount[p]) mesh->mNumBones++;
2020-06-24 18:30:02 +00:00
}
2015-05-19 03:57:13 +00:00
2020-06-24 18:30:02 +00:00
// just for safety
if (mesh->mNumBones) {
2020-03-01 12:15:45 +00:00
mesh->mBones = new aiBone *[mesh->mNumBones];
for (unsigned int q = 0, h = 0; q < meshParser.mJoints.size(); ++q) {
if (!piCount[q]) continue;
aiBone *p = mesh->mBones[h] = new aiBone();
2015-05-19 03:57:13 +00:00
p->mNumWeights = piCount[q];
p->mWeights = new aiVertexWeight[p->mNumWeights];
p->mName = aiString(meshParser.mJoints[q].mName);
p->mOffsetMatrix = meshParser.mJoints[q].mInvTransform;
// store the index for later use
2020-03-01 12:15:45 +00:00
MD5::BoneDesc &boneSrc = meshParser.mJoints[q];
2015-05-19 03:57:13 +00:00
boneSrc.mMap = h++;
// compute w-component of quaternion
2020-03-01 12:15:45 +00:00
MD5::ConvertQuaternion(boneSrc.mRotationQuat, boneSrc.mRotationQuatConverted);
2015-05-19 03:57:13 +00:00
}
pv = mesh->mVertices;
for (MD5::VertexArray::const_iterator iter = meshSrc.mVertices.begin(); iter != meshSrc.mVertices.end(); ++iter, ++pv) {
2015-05-19 03:57:13 +00:00
// compute the final vertex position from all single weights
*pv = aiVector3D();
// there are models which have weights which don't sum to 1 ...
ai_real fSum = 0.0;
2020-06-24 18:30:02 +00:00
for (unsigned int jub = (*iter).mFirstWeight, w = jub; w < jub + (*iter).mNumWeights; ++w) {
2015-05-19 03:57:13 +00:00
fSum += meshSrc.mWeights[w].mWeight;
2020-06-24 18:30:02 +00:00
}
2015-05-19 03:57:13 +00:00
if (!fSum) {
2018-04-20 14:23:24 +00:00
ASSIMP_LOG_ERROR("MD5MESH: The sum of all vertex bone weights is 0");
2015-05-19 03:57:13 +00:00
continue;
}
// process bone weights
2020-03-01 12:15:45 +00:00
for (unsigned int jub = (*iter).mFirstWeight, w = jub; w < jub + (*iter).mNumWeights; ++w) {
2020-06-24 18:30:02 +00:00
if (w >= meshSrc.mWeights.size()) {
2015-05-19 03:57:13 +00:00
throw DeadlyImportError("MD5MESH: Invalid weight index");
2020-06-24 18:30:02 +00:00
}
2015-05-19 03:57:13 +00:00
2020-03-01 12:15:45 +00:00
MD5::WeightDesc &weightDesc = meshSrc.mWeights[w];
if (weightDesc.mWeight < AI_MD5_WEIGHT_EPSILON && weightDesc.mWeight >= -AI_MD5_WEIGHT_EPSILON) {
2015-05-19 03:57:13 +00:00
continue;
}
const ai_real fNewWeight = weightDesc.mWeight / fSum;
2015-05-19 03:57:13 +00:00
// transform the local position into worldspace
2020-03-01 12:15:45 +00:00
MD5::BoneDesc &boneSrc = meshParser.mJoints[weightDesc.mBone];
const aiVector3D v = boneSrc.mRotationQuatConverted.Rotate(weightDesc.vOffsetPosition);
2015-05-19 03:57:13 +00:00
// use the original weight to compute the vertex position
// (some MD5s seem to depend on the invalid weight values ...)
2020-03-01 12:15:45 +00:00
*pv += ((boneSrc.mPositionXYZ + v) * (ai_real)weightDesc.mWeight);
2015-05-19 03:57:13 +00:00
2020-03-01 12:15:45 +00:00
aiBone *bone = mesh->mBones[boneSrc.mMap];
*bone->mWeights++ = aiVertexWeight((unsigned int)(pv - mesh->mVertices), fNewWeight);
2015-05-19 03:57:13 +00:00
}
}
// undo our nice offset tricks ...
2020-03-01 12:15:45 +00:00
for (unsigned int p = 0; p < mesh->mNumBones; ++p) {
2015-05-19 03:57:13 +00:00
mesh->mBones[p]->mWeights -= mesh->mBones[p]->mNumWeights;
}
}
delete[] piCount;
// now setup all faces - we can directly copy the list
// (however, take care that the aiFace destructor doesn't delete the mIndices array)
mesh->mNumFaces = (unsigned int)meshSrc.mFaces.size();
mesh->mFaces = new aiFace[mesh->mNumFaces];
2020-03-01 12:15:45 +00:00
for (unsigned int c = 0; c < mesh->mNumFaces; ++c) {
2015-05-19 03:57:13 +00:00
mesh->mFaces[c].mNumIndices = 3;
mesh->mFaces[c].mIndices = meshSrc.mFaces[c].mIndices;
meshSrc.mFaces[c].mIndices = nullptr;
2015-05-19 03:57:13 +00:00
}
// generate a material for the mesh
2020-03-01 12:15:45 +00:00
aiMaterial *mat = new aiMaterial();
2020-06-24 18:30:02 +00:00
mScene->mMaterials[n] = mat;
2015-05-19 03:57:13 +00:00
// insert the typical doom3 textures:
// nnn_local.tga - normal map
// nnn_h.tga - height map
// nnn_s.tga - specular map
// nnn_d.tga - diffuse map
2020-03-01 12:15:45 +00:00
if (meshSrc.mShader.length && !strchr(meshSrc.mShader.data, '.')) {
2015-05-19 03:57:13 +00:00
aiString temp(meshSrc.mShader);
temp.Append("_local.tga");
2020-03-01 12:15:45 +00:00
mat->AddProperty(&temp, AI_MATKEY_TEXTURE_NORMALS(0));
2015-05-19 03:57:13 +00:00
2020-03-01 12:15:45 +00:00
temp = aiString(meshSrc.mShader);
2015-05-19 03:57:13 +00:00
temp.Append("_s.tga");
2020-03-01 12:15:45 +00:00
mat->AddProperty(&temp, AI_MATKEY_TEXTURE_SPECULAR(0));
2015-05-19 03:57:13 +00:00
2020-03-01 12:15:45 +00:00
temp = aiString(meshSrc.mShader);
2015-05-19 03:57:13 +00:00
temp.Append("_d.tga");
2020-03-01 12:15:45 +00:00
mat->AddProperty(&temp, AI_MATKEY_TEXTURE_DIFFUSE(0));
2015-05-19 03:57:13 +00:00
2020-03-01 12:15:45 +00:00
temp = aiString(meshSrc.mShader);
2015-05-19 03:57:13 +00:00
temp.Append("_h.tga");
2020-03-01 12:15:45 +00:00
mat->AddProperty(&temp, AI_MATKEY_TEXTURE_HEIGHT(0));
2015-05-19 03:57:13 +00:00
// set this also as material name
2020-03-01 12:15:45 +00:00
mat->AddProperty(&meshSrc.mShader, AI_MATKEY_NAME);
} else {
2018-11-02 16:02:36 +00:00
mat->AddProperty(&meshSrc.mShader, AI_MATKEY_TEXTURE_DIFFUSE(0));
}
2015-05-19 03:57:13 +00:00
mesh->mMaterialIndex = n++;
}
#endif
}
// ------------------------------------------------------------------------------------------------
// Load an MD5ANIM file
2020-03-01 12:15:45 +00:00
void MD5Importer::LoadMD5AnimFile() {
2015-05-19 03:57:13 +00:00
std::string pFile = mFile + "md5anim";
2020-03-01 12:15:45 +00:00
std::unique_ptr<IOStream> file(mIOHandler->Open(pFile, "rb"));
2015-05-19 03:57:13 +00:00
// Check whether we can read from the file
if (!file || !file->FileSize()) {
2021-05-13 11:05:31 +00:00
ASSIMP_LOG_WARN("Failed to read MD5ANIM file: ", pFile);
2020-06-24 18:30:02 +00:00
return;
2015-05-19 03:57:13 +00:00
}
2020-06-21 10:03:38 +00:00
2015-05-19 03:57:13 +00:00
LoadFileIntoMemory(file.get());
// parse the basic file structure
2020-06-24 18:30:02 +00:00
MD5::MD5Parser parser(mBuffer, mFileSize);
2015-05-19 03:57:13 +00:00
// load the animation information from the parse tree
MD5::MD5AnimParser animParser(parser.mSections);
// generate and fill the output animation
if (animParser.mAnimatedBones.empty() || animParser.mFrames.empty() ||
2020-03-01 12:15:45 +00:00
animParser.mBaseFrames.size() != animParser.mAnimatedBones.size()) {
2018-04-20 14:23:24 +00:00
ASSIMP_LOG_ERROR("MD5ANIM: No frames or animated bones loaded");
2020-03-01 12:15:45 +00:00
} else {
2020-06-24 18:30:02 +00:00
mHadMD5Anim = true;
2015-05-19 03:57:13 +00:00
2020-06-24 18:30:02 +00:00
mScene->mAnimations = new aiAnimation *[mScene->mNumAnimations = 1];
aiAnimation *anim = mScene->mAnimations[0] = new aiAnimation();
2015-05-19 03:57:13 +00:00
anim->mNumChannels = (unsigned int)animParser.mAnimatedBones.size();
2020-03-01 12:15:45 +00:00
anim->mChannels = new aiNodeAnim *[anim->mNumChannels];
for (unsigned int i = 0; i < anim->mNumChannels; ++i) {
aiNodeAnim *node = anim->mChannels[i] = new aiNodeAnim();
node->mNodeName = aiString(animParser.mAnimatedBones[i].mName);
2015-05-19 03:57:13 +00:00
// allocate storage for the keyframes
node->mPositionKeys = new aiVectorKey[animParser.mFrames.size()];
node->mRotationKeys = new aiQuatKey[animParser.mFrames.size()];
}
// 1 tick == 1 frame
anim->mTicksPerSecond = animParser.fFrameRate;
for (FrameArray::const_iterator iter = animParser.mFrames.begin(), iterEnd = animParser.mFrames.end(); iter != iterEnd; ++iter) {
2015-05-19 03:57:13 +00:00
double dTime = (double)(*iter).iIndex;
2020-03-01 12:15:45 +00:00
aiNodeAnim **pcAnimNode = anim->mChannels;
2015-05-19 03:57:13 +00:00
if (!(*iter).mValues.empty() || iter == animParser.mFrames.begin()) /* be sure we have at least one frame */
{
// now process all values in there ... read all joints
2020-03-01 12:15:45 +00:00
MD5::BaseFrameDesc *pcBaseFrame = &animParser.mBaseFrames[0];
for (AnimBoneArray::const_iterator iter2 = animParser.mAnimatedBones.begin(); iter2 != animParser.mAnimatedBones.end(); ++iter2,
2020-03-01 12:15:45 +00:00
++pcAnimNode, ++pcBaseFrame) {
if ((*iter2).iFirstKeyIndex >= (*iter).mValues.size()) {
2015-05-19 03:57:13 +00:00
// Allow for empty frames
if ((*iter2).iFlags != 0) {
throw DeadlyImportError("MD5: Keyframe index is out of range");
}
continue;
}
2020-03-01 12:15:45 +00:00
const float *fpCur = &(*iter).mValues[(*iter2).iFirstKeyIndex];
aiNodeAnim *pcCurAnimBone = *pcAnimNode;
2015-05-19 03:57:13 +00:00
2020-03-01 12:15:45 +00:00
aiVectorKey *vKey = &pcCurAnimBone->mPositionKeys[pcCurAnimBone->mNumPositionKeys++];
aiQuatKey *qKey = &pcCurAnimBone->mRotationKeys[pcCurAnimBone->mNumRotationKeys++];
2015-05-19 03:57:13 +00:00
aiVector3D vTemp;
// translational component
for (unsigned int i = 0; i < 3; ++i) {
if ((*iter2).iFlags & (1u << i)) {
2020-03-01 12:15:45 +00:00
vKey->mValue[i] = *fpCur++;
} else
vKey->mValue[i] = pcBaseFrame->vPositionXYZ[i];
2015-05-19 03:57:13 +00:00
}
// orientation component
for (unsigned int i = 0; i < 3; ++i) {
if ((*iter2).iFlags & (8u << i)) {
2020-03-01 12:15:45 +00:00
vTemp[i] = *fpCur++;
} else
vTemp[i] = pcBaseFrame->vRotationQuat[i];
2015-05-19 03:57:13 +00:00
}
MD5::ConvertQuaternion(vTemp, qKey->mValue);
qKey->mTime = vKey->mTime = dTime;
}
}
// compute the duration of the animation
2020-03-01 12:15:45 +00:00
anim->mDuration = std::max(dTime, anim->mDuration);
2015-05-19 03:57:13 +00:00
}
// If we didn't build the hierarchy yet (== we didn't load a MD5MESH),
// construct it now from the data given in the MD5ANIM.
2020-06-24 18:30:02 +00:00
if (!mScene->mRootNode) {
mScene->mRootNode = new aiNode();
mScene->mRootNode->mName.Set("<MD5_Hierarchy>");
2015-05-19 03:57:13 +00:00
2020-06-24 18:30:02 +00:00
AttachChilds_Anim(-1, mScene->mRootNode, animParser.mAnimatedBones, (const aiNodeAnim **)anim->mChannels);
2015-05-19 03:57:13 +00:00
// Call SkeletonMeshBuilder to construct a mesh to represent the shape
2020-06-24 18:30:02 +00:00
if (mScene->mRootNode->mNumChildren) {
SkeletonMeshBuilder skeleton_maker(mScene, mScene->mRootNode->mChildren[0]);
2015-05-19 03:57:13 +00:00
}
}
}
}
// ------------------------------------------------------------------------------------------------
// Load an MD5CAMERA file
2020-03-01 12:15:45 +00:00
void MD5Importer::LoadMD5CameraFile() {
2015-05-19 03:57:13 +00:00
std::string pFile = mFile + "md5camera";
2020-03-01 12:15:45 +00:00
std::unique_ptr<IOStream> file(mIOHandler->Open(pFile, "rb"));
2015-05-19 03:57:13 +00:00
// Check whether we can read from the file
if (!file || !file->FileSize()) {
throw DeadlyImportError("Failed to read MD5CAMERA file: ", pFile);
2015-05-19 03:57:13 +00:00
}
2020-06-24 18:30:02 +00:00
mHadMD5Camera = true;
2015-05-19 03:57:13 +00:00
LoadFileIntoMemory(file.get());
// parse the basic file structure
2020-06-24 18:30:02 +00:00
MD5::MD5Parser parser(mBuffer, mFileSize);
2015-05-19 03:57:13 +00:00
// load the camera animation data from the parse tree
MD5::MD5CameraParser cameraParser(parser.mSections);
if (cameraParser.frames.empty()) {
throw DeadlyImportError("MD5CAMERA: No frames parsed");
}
2020-03-01 12:15:45 +00:00
std::vector<unsigned int> &cuts = cameraParser.cuts;
std::vector<MD5::CameraAnimFrameDesc> &frames = cameraParser.frames;
2015-05-19 03:57:13 +00:00
// Construct output graph - a simple root with a dummy child.
// The root node performs the coordinate system conversion
2020-06-24 18:30:02 +00:00
aiNode *root = mScene->mRootNode = new aiNode("<MD5CameraRoot>");
2020-03-01 12:15:45 +00:00
root->mChildren = new aiNode *[root->mNumChildren = 1];
2015-05-19 03:57:13 +00:00
root->mChildren[0] = new aiNode("<MD5Camera>");
root->mChildren[0]->mParent = root;
// ... but with one camera assigned to it
2020-06-24 18:30:02 +00:00
mScene->mCameras = new aiCamera *[mScene->mNumCameras = 1];
aiCamera *cam = mScene->mCameras[0] = new aiCamera();
2015-05-19 03:57:13 +00:00
cam->mName = "<MD5Camera>";
// FIXME: Fov is currently set to the first frame's value
2020-03-01 12:15:45 +00:00
cam->mHorizontalFOV = AI_DEG_TO_RAD(frames.front().fFOV);
2015-05-19 03:57:13 +00:00
// every cut is written to a separate aiAnimation
if (!cuts.size()) {
cuts.push_back(0);
2020-03-01 12:15:45 +00:00
cuts.push_back(static_cast<unsigned int>(frames.size() - 1));
} else {
cuts.insert(cuts.begin(), 0);
2015-05-19 03:57:13 +00:00
2020-03-01 12:15:45 +00:00
if (cuts.back() < frames.size() - 1)
cuts.push_back(static_cast<unsigned int>(frames.size() - 1));
2015-05-19 03:57:13 +00:00
}
2020-06-24 18:30:02 +00:00
mScene->mNumAnimations = static_cast<unsigned int>(cuts.size() - 1);
aiAnimation **tmp = mScene->mAnimations = new aiAnimation *[mScene->mNumAnimations];
2020-03-01 12:15:45 +00:00
for (std::vector<unsigned int>::const_iterator it = cuts.begin(); it != cuts.end() - 1; ++it) {
2015-05-19 03:57:13 +00:00
2020-03-01 12:15:45 +00:00
aiAnimation *anim = *tmp++ = new aiAnimation();
anim->mName.length = ::ai_snprintf(anim->mName.data, MAXLEN, "anim%u_from_%u_to_%u", (unsigned int)(it - cuts.begin()), (*it), *(it + 1));
2015-05-19 03:57:13 +00:00
anim->mTicksPerSecond = cameraParser.fFrameRate;
2020-03-01 12:15:45 +00:00
anim->mChannels = new aiNodeAnim *[anim->mNumChannels = 1];
aiNodeAnim *nd = anim->mChannels[0] = new aiNodeAnim();
2015-05-19 03:57:13 +00:00
nd->mNodeName.Set("<MD5Camera>");
2020-03-01 12:15:45 +00:00
nd->mNumPositionKeys = nd->mNumRotationKeys = *(it + 1) - (*it);
2015-05-19 03:57:13 +00:00
nd->mPositionKeys = new aiVectorKey[nd->mNumPositionKeys];
2020-03-01 12:15:45 +00:00
nd->mRotationKeys = new aiQuatKey[nd->mNumRotationKeys];
2015-05-19 03:57:13 +00:00
for (unsigned int i = 0; i < nd->mNumPositionKeys; ++i) {
2020-03-01 12:15:45 +00:00
nd->mPositionKeys[i].mValue = frames[*it + i].vPositionXYZ;
MD5::ConvertQuaternion(frames[*it + i].vRotationQuat, nd->mRotationKeys[i].mValue);
nd->mRotationKeys[i].mTime = nd->mPositionKeys[i].mTime = *it + i;
2015-05-19 03:57:13 +00:00
}
}
}
#endif // !! ASSIMP_BUILD_NO_MD5_IMPORTER