CSMLoader.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2024, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file CSMLoader.cpp
  35. * Implementation of the CSM importer class.
  36. */
  37. #ifndef ASSIMP_BUILD_NO_CSM_IMPORTER
  38. #include "CSMLoader.h"
  39. #include <assimp/SkeletonMeshBuilder.h>
  40. #include <assimp/ParsingUtils.h>
  41. #include <assimp/fast_atof.h>
  42. #include <assimp/Importer.hpp>
  43. #include <memory>
  44. #include <assimp/IOSystem.hpp>
  45. #include <assimp/anim.h>
  46. #include <assimp/DefaultLogger.hpp>
  47. #include <assimp/scene.h>
  48. #include <assimp/importerdesc.h>
  49. using namespace Assimp;
  50. static constexpr aiImporterDesc desc = {
  51. "CharacterStudio Motion Importer (MoCap)",
  52. "",
  53. "",
  54. "",
  55. aiImporterFlags_SupportTextFlavour,
  56. 0,
  57. 0,
  58. 0,
  59. 0,
  60. "csm"
  61. };
  62. // ------------------------------------------------------------------------------------------------
  63. // Constructor to be privately used by Importer
  64. CSMImporter::CSMImporter() : noSkeletonMesh(){
  65. // empty
  66. }
  67. // ------------------------------------------------------------------------------------------------
  68. // Returns whether the class can handle the format of the given file.
  69. bool CSMImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool /*checkSig*/) const {
  70. static const char* tokens[] = {"$Filename"};
  71. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,AI_COUNT_OF(tokens));
  72. }
  73. // ------------------------------------------------------------------------------------------------
  74. // Build a string of all file extensions supported
  75. const aiImporterDesc* CSMImporter::GetInfo () const {
  76. return &desc;
  77. }
  78. // ------------------------------------------------------------------------------------------------
  79. // Setup configuration properties for the loader
  80. void CSMImporter::SetupProperties(const Importer* pImp) {
  81. noSkeletonMesh = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_NO_SKELETON_MESHES,0) != 0;
  82. }
  83. // ------------------------------------------------------------------------------------------------
  84. // Imports the given file into the given scene structure.
  85. void CSMImporter::InternReadFile( const std::string& pFile,
  86. aiScene* pScene, IOSystem* pIOHandler)
  87. {
  88. std::unique_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  89. // Check whether we can read from the file
  90. if (file == nullptr) {
  91. throw DeadlyImportError( "Failed to open CSM file ", pFile, ".");
  92. }
  93. // allocate storage and copy the contents of the file to a memory buffer
  94. std::vector<char> mBuffer2;
  95. TextFileToBuffer(file.get(),mBuffer2);
  96. const char* buffer = &mBuffer2[0];
  97. const char *end = &mBuffer2[mBuffer2.size() - 1] + 1;
  98. std::unique_ptr<aiAnimation> anim(new aiAnimation());
  99. int first = 0, last = 0x00ffffff;
  100. // now process the file and look out for '$' sections
  101. while (true) {
  102. SkipSpaces(&buffer, end);
  103. if ('\0' == *buffer)
  104. break;
  105. if ('$' == *buffer) {
  106. ++buffer;
  107. if (TokenMatchI(buffer,"firstframe",10)) {
  108. SkipSpaces(&buffer, end);
  109. first = strtol10(buffer,&buffer);
  110. }
  111. else if (TokenMatchI(buffer,"lastframe",9)) {
  112. SkipSpaces(&buffer, end);
  113. last = strtol10(buffer,&buffer);
  114. }
  115. else if (TokenMatchI(buffer,"rate",4)) {
  116. SkipSpaces(&buffer, end);
  117. float d = { 0.0f };
  118. buffer = fast_atoreal_move<float>(buffer,d);
  119. anim->mTicksPerSecond = d;
  120. }
  121. else if (TokenMatchI(buffer,"order",5)) {
  122. std::vector< aiNodeAnim* > anims_temp;
  123. anims_temp.reserve(30);
  124. while (true) {
  125. SkipSpaces(&buffer, end);
  126. if (IsLineEnd(*buffer) && SkipSpacesAndLineEnd(&buffer, end) && *buffer == '$')
  127. break; // next section
  128. // Construct a new node animation channel and setup its name
  129. anims_temp.push_back(new aiNodeAnim());
  130. aiNodeAnim* nda = anims_temp.back();
  131. char* ot = nda->mNodeName.data;
  132. while (!IsSpaceOrNewLine(*buffer)) {
  133. *ot++ = *buffer++;
  134. }
  135. *ot = '\0';
  136. nda->mNodeName.length = static_cast<ai_uint32>(ot-nda->mNodeName.data);
  137. }
  138. anim->mNumChannels = static_cast<unsigned int>(anims_temp.size());
  139. if (!anim->mNumChannels) {
  140. throw DeadlyImportError("CSM: Empty $order section");
  141. }
  142. // copy over to the output animation
  143. anim->mChannels = new aiNodeAnim*[anim->mNumChannels];
  144. ::memcpy(anim->mChannels,&anims_temp[0],sizeof(aiNodeAnim*)*anim->mNumChannels);
  145. } else if (TokenMatchI(buffer,"points",6)) {
  146. if (!anim->mNumChannels) {
  147. throw DeadlyImportError("CSM: \'$order\' section is required to appear prior to \'$points\'");
  148. }
  149. // If we know how many frames we'll read, we can preallocate some storage
  150. unsigned int alloc = 100;
  151. if (last != 0x00ffffff) {
  152. alloc = last-first;
  153. alloc += alloc>>2u; // + 25%
  154. for (unsigned int i = 0; i < anim->mNumChannels; ++i) {
  155. anim->mChannels[i]->mPositionKeys = new aiVectorKey[alloc];
  156. }
  157. }
  158. unsigned int filled = 0;
  159. // Now read all point data.
  160. while (true) {
  161. SkipSpaces(&buffer, end);
  162. if (IsLineEnd(*buffer) && (!SkipSpacesAndLineEnd(&buffer, end) || *buffer == '$')) {
  163. break; // next section
  164. }
  165. // read frame
  166. const int frame = ::strtoul10(buffer,&buffer);
  167. last = std::max(frame,last);
  168. first = std::min(frame,last);
  169. for (unsigned int i = 0; i < anim->mNumChannels;++i) {
  170. aiNodeAnim* s = anim->mChannels[i];
  171. if (s->mNumPositionKeys == alloc) {
  172. // need to reallocate?
  173. aiVectorKey* old = s->mPositionKeys;
  174. s->mPositionKeys = new aiVectorKey[s->mNumPositionKeys = alloc*2];
  175. ::memcpy(s->mPositionKeys,old,sizeof(aiVectorKey)*alloc);
  176. delete[] old;
  177. }
  178. // read x,y,z
  179. if (!SkipSpacesAndLineEnd(&buffer, end)) {
  180. throw DeadlyImportError("CSM: Unexpected EOF occurred reading sample x coord");
  181. }
  182. if (TokenMatchI(buffer, "DROPOUT", 7)) {
  183. // seems this is invalid marker data; at least the doc says it's possible
  184. ASSIMP_LOG_WARN("CSM: Encountered invalid marker data (DROPOUT)");
  185. } else {
  186. aiVectorKey* sub = s->mPositionKeys + s->mNumPositionKeys;
  187. sub->mTime = (double)frame;
  188. buffer = fast_atoreal_move<float>(buffer, (float&)sub->mValue.x);
  189. if (!SkipSpacesAndLineEnd(&buffer, end)) {
  190. throw DeadlyImportError("CSM: Unexpected EOF occurred reading sample y coord");
  191. }
  192. buffer = fast_atoreal_move<float>(buffer, (float&)sub->mValue.y);
  193. if (!SkipSpacesAndLineEnd(&buffer, end)) {
  194. throw DeadlyImportError("CSM: Unexpected EOF occurred reading sample z coord");
  195. }
  196. buffer = fast_atoreal_move<float>(buffer, (float&)sub->mValue.z);
  197. ++s->mNumPositionKeys;
  198. }
  199. }
  200. // update allocation granularity
  201. if (filled == alloc) {
  202. alloc *= 2;
  203. }
  204. ++filled;
  205. }
  206. // all channels must be complete in order to continue safely.
  207. for (unsigned int i = 0; i < anim->mNumChannels;++i) {
  208. if (!anim->mChannels[i]->mNumPositionKeys) {
  209. throw DeadlyImportError("CSM: Invalid marker track");
  210. }
  211. }
  212. }
  213. } else {
  214. // advance to the next line
  215. SkipLine(&buffer, end);
  216. }
  217. }
  218. // Setup a proper animation duration
  219. anim->mDuration = last - std::min( first, 0 );
  220. // build a dummy root node with the tiny markers as children
  221. pScene->mRootNode = new aiNode();
  222. pScene->mRootNode->mName.Set("$CSM_DummyRoot");
  223. pScene->mRootNode->mNumChildren = anim->mNumChannels;
  224. pScene->mRootNode->mChildren = new aiNode* [anim->mNumChannels];
  225. for (unsigned int i = 0; i < anim->mNumChannels;++i) {
  226. aiNodeAnim* na = anim->mChannels[i];
  227. aiNode* nd = pScene->mRootNode->mChildren[i] = new aiNode();
  228. nd->mName = anim->mChannels[i]->mNodeName;
  229. nd->mParent = pScene->mRootNode;
  230. aiMatrix4x4::Translation(na->mPositionKeys[0].mValue, nd->mTransformation);
  231. }
  232. // Store the one and only animation in the scene
  233. pScene->mAnimations = new aiAnimation*[pScene->mNumAnimations=1];
  234. anim->mName.Set("$CSM_MasterAnim");
  235. pScene->mAnimations[0] = anim.release();
  236. // mark the scene as incomplete and run SkeletonMeshBuilder on it
  237. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  238. if (!noSkeletonMesh) {
  239. SkeletonMeshBuilder maker(pScene,pScene->mRootNode,true);
  240. }
  241. }
  242. #endif // !! ASSIMP_BUILD_NO_CSM_IMPORTER