C4DImporter.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2020, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. /** @file C4DImporter.cpp
  34. * @brief Implementation of the Cinema4D importer class.
  35. */
  36. #ifndef ASSIMP_BUILD_NO_C4D_IMPORTER
  37. // no #ifdefing here, Cinema4D support is carried out in a branch of assimp
  38. // where it is turned on in the CMake settings.
  39. #ifndef _MSC_VER
  40. # error C4D support is currently MSVC only
  41. #endif
  42. #include "C4DImporter.h"
  43. #include <assimp/TinyFormatter.h>
  44. #include <memory>
  45. #include <assimp/IOSystem.hpp>
  46. #include <assimp/scene.h>
  47. #include <assimp/ai_assert.h>
  48. #if defined(_M_X64) || defined(__amd64__)
  49. # define __C4D_64BIT
  50. #endif
  51. #define __PC
  52. #include "c4d_file.h"
  53. #include "default_alien_overloads.h"
  54. using namespace melange;
  55. // overload this function and fill in your own unique data
  56. void GetWriterInfo(int &id, String &appname) {
  57. id = 2424226;
  58. appname = "Open Asset Import Library";
  59. }
  60. using namespace Assimp;
  61. using namespace Assimp::Formatter;
  62. namespace Assimp {
  63. template<> const char* LogFunctions<C4DImporter>::Prefix() {
  64. static auto prefix = "C4D: ";
  65. return prefix;
  66. }
  67. }
  68. static const aiImporterDesc desc = {
  69. "Cinema4D Importer",
  70. "",
  71. "",
  72. "",
  73. aiImporterFlags_SupportBinaryFlavour,
  74. 0,
  75. 0,
  76. 0,
  77. 0,
  78. "c4d"
  79. };
  80. // ------------------------------------------------------------------------------------------------
  81. C4DImporter::C4DImporter()
  82. : BaseImporter() {
  83. // empty
  84. }
  85. // ------------------------------------------------------------------------------------------------
  86. C4DImporter::~C4DImporter() {
  87. // empty
  88. }
  89. // ------------------------------------------------------------------------------------------------
  90. bool C4DImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const {
  91. const std::string& extension = GetExtension(pFile);
  92. if (extension == "c4d") {
  93. return true;
  94. } else if ((!extension.length() || checkSig) && pIOHandler) {
  95. // TODO
  96. }
  97. return false;
  98. }
  99. // ------------------------------------------------------------------------------------------------
  100. const aiImporterDesc* C4DImporter::GetInfo () const {
  101. return &desc;
  102. }
  103. // ------------------------------------------------------------------------------------------------
  104. void C4DImporter::SetupProperties(const Importer* /*pImp*/) {
  105. // nothing to be done for the moment
  106. }
  107. // ------------------------------------------------------------------------------------------------
  108. // Imports the given file into the given scene structure.
  109. void C4DImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler) {
  110. std::unique_ptr<IOStream> file( pIOHandler->Open( pFile));
  111. if( file.get() == nullptr ) {
  112. ThrowException("failed to open file " + pFile);
  113. }
  114. const size_t file_size = file->FileSize();
  115. std::vector<uint8_t> mBuffer(file_size);
  116. file->Read(&mBuffer[0], 1, file_size);
  117. Filename f;
  118. f.SetMemoryReadMode(&mBuffer[0], file_size);
  119. // open document first
  120. BaseDocument* doc = LoadDocument(f, SCENEFILTER_OBJECTS | SCENEFILTER_MATERIALS);
  121. if(doc == nullptr ) {
  122. ThrowException("failed to read document " + pFile);
  123. }
  124. pScene->mRootNode = new aiNode("<C4DRoot>");
  125. // first convert all materials
  126. ReadMaterials(doc->GetFirstMaterial());
  127. // process C4D scene-graph recursively
  128. try {
  129. RecurseHierarchy(doc->GetFirstObject(), pScene->mRootNode);
  130. } catch(...) {
  131. for(aiMesh* mesh : meshes) {
  132. delete mesh;
  133. }
  134. BaseDocument::Free(doc);
  135. throw;
  136. }
  137. BaseDocument::Free(doc);
  138. // copy meshes over
  139. pScene->mNumMeshes = static_cast<unsigned int>(meshes.size());
  140. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes]();
  141. std::copy(meshes.begin(), meshes.end(), pScene->mMeshes);
  142. // copy materials over, adding a default material if necessary
  143. unsigned int mat_count = static_cast<unsigned int>(materials.size());
  144. for(aiMesh* mesh : meshes) {
  145. ai_assert(mesh->mMaterialIndex <= mat_count);
  146. if(mesh->mMaterialIndex >= mat_count) {
  147. ++mat_count;
  148. std::unique_ptr<aiMaterial> def_material(new aiMaterial());
  149. const aiString name(AI_DEFAULT_MATERIAL_NAME);
  150. def_material->AddProperty(&name, AI_MATKEY_NAME);
  151. materials.push_back(def_material.release());
  152. break;
  153. }
  154. }
  155. pScene->mNumMaterials = static_cast<unsigned int>(materials.size());
  156. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials]();
  157. std::copy(materials.begin(), materials.end(), pScene->mMaterials);
  158. }
  159. // ------------------------------------------------------------------------------------------------
  160. bool C4DImporter::ReadShader(aiMaterial* out, melange::BaseShader* shader) {
  161. // based on Melange sample code (C4DImportExport.cpp)
  162. while(shader) {
  163. if(shader->GetType() == Xlayer) {
  164. BaseContainer* container = shader->GetDataInstance();
  165. GeData blend = container->GetData(SLA_LAYER_BLEND);
  166. iBlendDataType* blend_list = reinterpret_cast<iBlendDataType*>(blend.GetCustomDataType(CUSTOMDATA_BLEND_LIST));
  167. if (!blend_list)
  168. {
  169. LogWarn("ignoring XLayer shader: no blend list given");
  170. continue;
  171. }
  172. LayerShaderLayer *lsl = dynamic_cast<LayerShaderLayer*>(blend_list->m_BlendLayers.GetObject(0));
  173. // Ignore the actual layer blending - models for real-time rendering should not
  174. // use them in a non-trivial way. Just try to find textures that we can apply
  175. // to the model.
  176. while (lsl) {
  177. if (lsl->GetType() == TypeFolder) {
  178. BlendFolder* const folder = dynamic_cast<BlendFolder*>(lsl);
  179. LayerShaderLayer *subLsl = dynamic_cast<LayerShaderLayer*>(folder->m_Children.GetObject(0));
  180. while (subLsl) {
  181. if (subLsl->GetType() == TypeShader) {
  182. BlendShader* const shader = dynamic_cast<BlendShader*>(subLsl);
  183. if(ReadShader(out, static_cast<BaseShader*>(shader->m_pLink->GetLink()))) {
  184. return true;
  185. }
  186. }
  187. subLsl = subLsl->GetNext();
  188. }
  189. } else if (lsl->GetType() == TypeShader) {
  190. BlendShader* const shader = dynamic_cast<BlendShader*>(lsl);
  191. if(ReadShader(out, static_cast<BaseShader*>(shader->m_pLink->GetLink()))) {
  192. return true;
  193. }
  194. }
  195. lsl = lsl->GetNext();
  196. }
  197. } else if ( shader->GetType() == Xbitmap ) {
  198. aiString path;
  199. shader->GetFileName().GetString().GetCString(path.data, MAXLEN-1);
  200. path.length = ::strlen(path.data);
  201. out->AddProperty(&path, AI_MATKEY_TEXTURE_DIFFUSE(0));
  202. return true;
  203. } else {
  204. LogWarn("ignoring shader type: " + std::string(GetObjectTypeName(shader->GetType())));
  205. }
  206. shader = shader->GetNext();
  207. }
  208. return false;
  209. }
  210. // ------------------------------------------------------------------------------------------------
  211. void C4DImporter::ReadMaterials(melange::BaseMaterial* mat) {
  212. // based on Melange sample code
  213. while (mat) {
  214. const String& name = mat->GetName();
  215. if (mat->GetType() == Mmaterial) {
  216. aiMaterial* out = new aiMaterial();
  217. material_mapping[mat] = static_cast<unsigned int>(materials.size());
  218. materials.push_back(out);
  219. aiString ai_name;
  220. name.GetCString(ai_name.data, MAXLEN-1);
  221. ai_name.length = ::strlen(ai_name.data);
  222. out->AddProperty(&ai_name, AI_MATKEY_NAME);
  223. Material& m = dynamic_cast<Material&>(*mat);
  224. if (m.GetChannelState(CHANNEL_COLOR)) {
  225. GeData data;
  226. mat->GetParameter(MATERIAL_COLOR_COLOR, data);
  227. Vector color = data.GetVector();
  228. mat->GetParameter(MATERIAL_COLOR_BRIGHTNESS, data);
  229. const Float brightness = data.GetFloat();
  230. color *= brightness;
  231. aiVector3D v;
  232. v.x = color.x;
  233. v.y = color.y;
  234. v.z = color.z;
  235. out->AddProperty(&v, 1, AI_MATKEY_COLOR_DIFFUSE);
  236. }
  237. BaseShader* const shader = m.GetShader(MATERIAL_COLOR_SHADER);
  238. if(shader) {
  239. ReadShader(out, shader);
  240. }
  241. } else {
  242. LogWarn("ignoring plugin material: " + std::string(GetObjectTypeName(mat->GetType())));
  243. }
  244. mat = mat->GetNext();
  245. }
  246. }
  247. // ------------------------------------------------------------------------------------------------
  248. void C4DImporter::RecurseHierarchy(BaseObject* object, aiNode* parent) {
  249. ai_assert(parent != nullptr );
  250. std::vector<aiNode*> nodes;
  251. // based on Melange sample code
  252. while (object) {
  253. const String& name = object->GetName();
  254. const LONG type = object->GetType();
  255. const Matrix& ml = object->GetMl();
  256. aiString string;
  257. name.GetCString(string.data, MAXLEN-1);
  258. string.length = ::strlen(string.data);
  259. aiNode* const nd = new aiNode();
  260. nd->mParent = parent;
  261. nd->mName = string;
  262. nd->mTransformation.a1 = ml.v1.x;
  263. nd->mTransformation.b1 = ml.v1.y;
  264. nd->mTransformation.c1 = ml.v1.z;
  265. nd->mTransformation.a2 = ml.v2.x;
  266. nd->mTransformation.b2 = ml.v2.y;
  267. nd->mTransformation.c2 = ml.v2.z;
  268. nd->mTransformation.a3 = ml.v3.x;
  269. nd->mTransformation.b3 = ml.v3.y;
  270. nd->mTransformation.c3 = ml.v3.z;
  271. nd->mTransformation.a4 = ml.off.x;
  272. nd->mTransformation.b4 = ml.off.y;
  273. nd->mTransformation.c4 = ml.off.z;
  274. nodes.push_back(nd);
  275. GeData data;
  276. if (type == Ocamera) {
  277. object->GetParameter(CAMERAOBJECT_FOV, data);
  278. // TODO: read camera
  279. } else if (type == Olight) {
  280. // TODO: read light
  281. } else if (type == Opolygon) {
  282. aiMesh* const mesh = ReadMesh(object);
  283. if(mesh != nullptr) {
  284. nd->mNumMeshes = 1;
  285. nd->mMeshes = new unsigned int[1];
  286. nd->mMeshes[0] = static_cast<unsigned int>(meshes.size());
  287. meshes.push_back(mesh);
  288. }
  289. } else {
  290. LogWarn("ignoring object: " + std::string(GetObjectTypeName(type)));
  291. }
  292. RecurseHierarchy(object->GetDown(), nd);
  293. object = object->GetNext();
  294. }
  295. // copy nodes over to parent
  296. parent->mNumChildren = static_cast<unsigned int>(nodes.size());
  297. parent->mChildren = new aiNode*[parent->mNumChildren]();
  298. std::copy(nodes.begin(), nodes.end(), parent->mChildren);
  299. }
  300. // ------------------------------------------------------------------------------------------------
  301. aiMesh* C4DImporter::ReadMesh(BaseObject* object) {
  302. ai_assert(object != nullptr);
  303. ai_assert( object->GetType() == Opolygon );
  304. // based on Melange sample code
  305. PolygonObject* const polyObject = dynamic_cast<PolygonObject*>(object);
  306. ai_assert(polyObject != nullptr);
  307. const LONG pointCount = polyObject->GetPointCount();
  308. const LONG polyCount = polyObject->GetPolygonCount();
  309. if(!polyObject || !pointCount) {
  310. LogWarn("ignoring mesh with zero vertices or faces");
  311. return nullptr;
  312. }
  313. const Vector* points = polyObject->GetPointR();
  314. ai_assert(points != nullptr);
  315. const CPolygon* polys = polyObject->GetPolygonR();
  316. ai_assert(polys != nullptr);
  317. std::unique_ptr<aiMesh> mesh(new aiMesh());
  318. mesh->mNumFaces = static_cast<unsigned int>(polyCount);
  319. aiFace* face = mesh->mFaces = new aiFace[mesh->mNumFaces]();
  320. mesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  321. mesh->mMaterialIndex = 0;
  322. unsigned int vcount = 0;
  323. // first count vertices
  324. for (LONG i = 0; i < polyCount; i++)
  325. {
  326. vcount += 3;
  327. // TODO: do we also need to handle lines or points with similar checks?
  328. if (polys[i].c != polys[i].d)
  329. {
  330. mesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  331. ++vcount;
  332. }
  333. }
  334. ai_assert(vcount > 0);
  335. mesh->mNumVertices = vcount;
  336. aiVector3D* verts = mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  337. aiVector3D* normals, *uvs, *tangents, *bitangents;
  338. unsigned int n = 0;
  339. // check if there are normals, tangents or UVW coordinates
  340. BaseTag* tag = object->GetTag(Tnormal);
  341. NormalTag* normals_src = nullptr;
  342. if(tag) {
  343. normals_src = dynamic_cast<NormalTag*>(tag);
  344. normals = mesh->mNormals = new aiVector3D[mesh->mNumVertices]();
  345. }
  346. tag = object->GetTag(Ttangent);
  347. TangentTag* tangents_src = nullptr;
  348. if(tag) {
  349. tangents_src = dynamic_cast<TangentTag*>(tag);
  350. tangents = mesh->mTangents = new aiVector3D[mesh->mNumVertices]();
  351. bitangents = mesh->mBitangents = new aiVector3D[mesh->mNumVertices]();
  352. }
  353. tag = object->GetTag(Tuvw);
  354. UVWTag* uvs_src = nullptr;
  355. if(tag) {
  356. uvs_src = dynamic_cast<UVWTag*>(tag);
  357. uvs = mesh->mTextureCoords[0] = new aiVector3D[mesh->mNumVertices]();
  358. }
  359. // copy vertices and extra channels over and populate faces
  360. for (LONG i = 0; i < polyCount; ++i, ++face) {
  361. ai_assert(polys[i].a < pointCount && polys[i].a >= 0);
  362. const Vector& pointA = points[polys[i].a];
  363. verts->x = pointA.x;
  364. verts->y = pointA.y;
  365. verts->z = pointA.z;
  366. ++verts;
  367. ai_assert(polys[i].b < pointCount && polys[i].b >= 0);
  368. const Vector& pointB = points[polys[i].b];
  369. verts->x = pointB.x;
  370. verts->y = pointB.y;
  371. verts->z = pointB.z;
  372. ++verts;
  373. ai_assert(polys[i].c < pointCount && polys[i].c >= 0);
  374. const Vector& pointC = points[polys[i].c];
  375. verts->x = pointC.x;
  376. verts->y = pointC.y;
  377. verts->z = pointC.z;
  378. ++verts;
  379. // TODO: do we also need to handle lines or points with similar checks?
  380. if (polys[i].c != polys[i].d) {
  381. ai_assert(polys[i].d < pointCount && polys[i].d >= 0);
  382. face->mNumIndices = 4;
  383. mesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  384. const Vector& pointD = points[polys[i].d];
  385. verts->x = pointD.x;
  386. verts->y = pointD.y;
  387. verts->z = pointD.z;
  388. ++verts;
  389. } else {
  390. face->mNumIndices = 3;
  391. }
  392. face->mIndices = new unsigned int[face->mNumIndices];
  393. for(unsigned int j = 0; j < face->mNumIndices; ++j) {
  394. face->mIndices[j] = n++;
  395. }
  396. // copy normals
  397. if (normals_src) {
  398. if(i >= normals_src->GetDataCount()) {
  399. LogError("unexpected number of normals, ignoring");
  400. } else {
  401. ConstNormalHandle normal_handle = normals_src->GetDataAddressR();
  402. NormalStruct nor;
  403. NormalTag::Get(normal_handle, i, nor);
  404. normals->x = nor.a.x;
  405. normals->y = nor.a.y;
  406. normals->z = nor.a.z;
  407. ++normals;
  408. normals->x = nor.b.x;
  409. normals->y = nor.b.y;
  410. normals->z = nor.b.z;
  411. ++normals;
  412. normals->x = nor.c.x;
  413. normals->y = nor.c.y;
  414. normals->z = nor.c.z;
  415. ++normals;
  416. if(face->mNumIndices == 4) {
  417. normals->x = nor.d.x;
  418. normals->y = nor.d.y;
  419. normals->z = nor.d.z;
  420. ++normals;
  421. }
  422. }
  423. }
  424. // copy tangents and bitangents
  425. if (tangents_src) {
  426. for(unsigned int k = 0; k < face->mNumIndices; ++k) {
  427. LONG l;
  428. switch(k) {
  429. case 0:
  430. l = polys[i].a;
  431. break;
  432. case 1:
  433. l = polys[i].b;
  434. break;
  435. case 2:
  436. l = polys[i].c;
  437. break;
  438. case 3:
  439. l = polys[i].d;
  440. break;
  441. default:
  442. ai_assert(false);
  443. }
  444. if(l >= tangents_src->GetDataCount()) {
  445. LogError("unexpected number of tangents, ignoring");
  446. break;
  447. }
  448. Tangent tan = tangents_src->GetDataR()[l];
  449. tangents->x = tan.vl.x;
  450. tangents->y = tan.vl.y;
  451. tangents->z = tan.vl.z;
  452. ++tangents;
  453. bitangents->x = tan.vr.x;
  454. bitangents->y = tan.vr.y;
  455. bitangents->z = tan.vr.z;
  456. ++bitangents;
  457. }
  458. }
  459. // copy UVs
  460. if (uvs_src) {
  461. if(i >= uvs_src->GetDataCount()) {
  462. LogError("unexpected number of UV coordinates, ignoring");
  463. }
  464. else {
  465. UVWStruct uvw;
  466. uvs_src->Get(uvs_src->GetDataAddressR(),i,uvw);
  467. uvs->x = uvw.a.x;
  468. uvs->y = 1.0f-uvw.a.y;
  469. uvs->z = uvw.a.z;
  470. ++uvs;
  471. uvs->x = uvw.b.x;
  472. uvs->y = 1.0f-uvw.b.y;
  473. uvs->z = uvw.b.z;
  474. ++uvs;
  475. uvs->x = uvw.c.x;
  476. uvs->y = 1.0f-uvw.c.y;
  477. uvs->z = uvw.c.z;
  478. ++uvs;
  479. if(face->mNumIndices == 4) {
  480. uvs->x = uvw.d.x;
  481. uvs->y = 1.0f-uvw.d.y;
  482. uvs->z = uvw.d.z;
  483. ++uvs;
  484. }
  485. }
  486. }
  487. }
  488. mesh->mMaterialIndex = ResolveMaterial(polyObject);
  489. return mesh.release();
  490. }
  491. // ------------------------------------------------------------------------------------------------
  492. unsigned int C4DImporter::ResolveMaterial(PolygonObject* obj) {
  493. ai_assert(obj != nullptr);
  494. const unsigned int mat_count = static_cast<unsigned int>(materials.size());
  495. BaseTag* tag = obj->GetTag(Ttexture);
  496. if(tag == nullptr) {
  497. return mat_count;
  498. }
  499. TextureTag& ttag = dynamic_cast<TextureTag&>(*tag);
  500. BaseMaterial* const mat = ttag.GetMaterial();
  501. ai_assert(mat != nullptr);
  502. const MaterialMap::const_iterator it = material_mapping.find(mat);
  503. if(it == material_mapping.end()) {
  504. return mat_count;
  505. }
  506. ai_assert((*it).second < mat_count);
  507. return (*it).second;
  508. }
  509. #endif // ASSIMP_BUILD_NO_C4D_IMPORTER