C4DImporter.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2025, 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. #include "C4DImporter.h"
  40. #include <memory>
  41. #include <assimp/IOSystem.hpp>
  42. #include <assimp/scene.h>
  43. #include <assimp/ai_assert.h>
  44. #if defined(_M_X64) || defined(__amd64__)
  45. # define __C4D_64BIT
  46. #endif
  47. #define __PC
  48. #include "c4d_file.h"
  49. #include "default_alien_overloads.h"
  50. namespace {
  51. aiString aiStringFrom(cineware::String const & cinestring) {
  52. aiString result;
  53. cinestring.GetCString(result.data, MAXLEN-1);
  54. result.length = static_cast<ai_uint32>(cinestring.GetLength());
  55. return result;
  56. }
  57. }
  58. using namespace Assimp;
  59. using namespace cineware;
  60. // overload this function and fill in your own unique data
  61. void GetWriterInfo(int &id, String &appname) {
  62. id = 2424226;
  63. appname = "Open Asset Import Library";
  64. }
  65. namespace Assimp {
  66. template<> const char* LogFunctions<C4DImporter>::Prefix() {
  67. return "C4D: ";
  68. }
  69. }
  70. static constexpr aiImporterDesc desc = {
  71. "Cinema4D Importer",
  72. "",
  73. "",
  74. "",
  75. aiImporterFlags_SupportBinaryFlavour,
  76. 0,
  77. 0,
  78. 0,
  79. 0,
  80. "c4d"
  81. };
  82. // ------------------------------------------------------------------------------------------------
  83. bool C4DImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const {
  84. const std::string& extension = GetExtension(pFile);
  85. if (extension == "c4d") {
  86. return true;
  87. } else if ((!extension.length() || checkSig) && pIOHandler) {
  88. // TODO
  89. }
  90. return false;
  91. }
  92. // ------------------------------------------------------------------------------------------------
  93. const aiImporterDesc* C4DImporter::GetInfo () const {
  94. return &desc;
  95. }
  96. // ------------------------------------------------------------------------------------------------
  97. // Imports the given file into the given scene structure.
  98. void C4DImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler) {
  99. std::unique_ptr<IOStream> file( pIOHandler->Open( pFile));
  100. if( file.get() == nullptr ) {
  101. ThrowException("failed to open file " + pFile);
  102. }
  103. const size_t file_size = file->FileSize();
  104. std::vector<uint8_t> mBuffer(file_size);
  105. file->Read(&mBuffer[0], 1, file_size);
  106. Filename f;
  107. f.SetMemoryReadMode(&mBuffer[0], file_size);
  108. // open document first
  109. BaseDocument* doc = LoadDocument(f, SCENEFILTER_OBJECTS | SCENEFILTER_MATERIALS);
  110. if(doc == nullptr ) {
  111. ThrowException("failed to read document " + pFile);
  112. }
  113. // Generate the root-node
  114. pScene->mRootNode = new aiNode("<C4DRoot>");
  115. // convert left-handed to right-handed
  116. pScene->mRootNode->mTransformation.a1 = 0.01f;
  117. pScene->mRootNode->mTransformation.b2 = 0.01f;
  118. pScene->mRootNode->mTransformation.c3 = -0.01f;
  119. // first convert all materials
  120. ReadMaterials(doc->GetFirstMaterial());
  121. // process C4D scene-graph recursively
  122. try {
  123. RecurseHierarchy(doc->GetFirstObject(), pScene->mRootNode);
  124. } catch(...) {
  125. for(aiMesh* mesh : meshes) {
  126. delete mesh;
  127. }
  128. BaseDocument::Free(doc);
  129. throw;
  130. }
  131. BaseDocument::Free(doc);
  132. // copy meshes over
  133. pScene->mNumMeshes = static_cast<unsigned int>(meshes.size());
  134. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes]();
  135. std::copy(meshes.begin(), meshes.end(), pScene->mMeshes);
  136. // copy materials over, adding a default material if necessary
  137. unsigned int mat_count = static_cast<unsigned int>(materials.size());
  138. for(aiMesh* mesh : meshes) {
  139. ai_assert(mesh->mMaterialIndex <= mat_count);
  140. if(mesh->mMaterialIndex >= mat_count) {
  141. ++mat_count;
  142. std::unique_ptr<aiMaterial> def_material(new aiMaterial());
  143. const aiString name(AI_DEFAULT_MATERIAL_NAME);
  144. def_material->AddProperty(&name, AI_MATKEY_NAME);
  145. materials.push_back(def_material.release());
  146. break;
  147. }
  148. }
  149. pScene->mNumMaterials = static_cast<unsigned int>(materials.size());
  150. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials]();
  151. std::copy(materials.begin(), materials.end(), pScene->mMaterials);
  152. }
  153. // ------------------------------------------------------------------------------------------------
  154. bool C4DImporter::ReadShader(aiMaterial* out, BaseShader* shader) {
  155. // based on Cineware sample code (C4DImportExport.cpp)
  156. while(shader) {
  157. if(shader->GetType() == Xlayer) {
  158. BaseContainer* container = shader->GetDataInstance();
  159. GeData blend = container->GetData(SLA_LAYER_BLEND);
  160. iBlendDataType* blend_list = reinterpret_cast<iBlendDataType*>(blend.GetCustomDataType(CUSTOMDATA_BLEND_LIST));
  161. if (!blend_list)
  162. {
  163. LogWarn("ignoring XLayer shader: no blend list given");
  164. continue;
  165. }
  166. LayerShaderLayer *lsl = dynamic_cast<LayerShaderLayer*>(blend_list->m_BlendLayers.GetObject(0));
  167. // Ignore the actual layer blending - models for real-time rendering should not
  168. // use them in a non-trivial way. Just try to find textures that we can apply
  169. // to the model.
  170. while (lsl) {
  171. if (lsl->GetType() == TypeFolder) {
  172. BlendFolder* const folder = dynamic_cast<BlendFolder*>(lsl);
  173. LayerShaderLayer *subLsl = dynamic_cast<LayerShaderLayer*>(folder->m_Children.GetObject(0));
  174. while (subLsl) {
  175. if (subLsl->GetType() == TypeShader) {
  176. BlendShader* const shader = dynamic_cast<BlendShader*>(subLsl);
  177. if(ReadShader(out, static_cast<BaseShader*>(shader->m_pLink->GetLink()))) {
  178. return true;
  179. }
  180. }
  181. subLsl = subLsl->GetNext();
  182. }
  183. } else if (lsl->GetType() == TypeShader) {
  184. BlendShader* const shader = dynamic_cast<BlendShader*>(lsl);
  185. if(ReadShader(out, static_cast<BaseShader*>(shader->m_pLink->GetLink()))) {
  186. return true;
  187. }
  188. }
  189. lsl = lsl->GetNext();
  190. }
  191. } else if ( shader->GetType() == Xbitmap ) {
  192. auto const path = aiStringFrom(shader->GetFileName().GetString());
  193. out->AddProperty(&path, AI_MATKEY_TEXTURE_DIFFUSE(0));
  194. return true;
  195. } else {
  196. LogWarn("ignoring shader type: ", GetObjectTypeName(shader->GetType()));
  197. }
  198. shader = shader->GetNext();
  199. }
  200. return false;
  201. }
  202. // ------------------------------------------------------------------------------------------------
  203. void C4DImporter::ReadMaterials(BaseMaterial* mat) {
  204. // based on Cineware sample code
  205. while (mat) {
  206. if (mat->GetType() == Mmaterial) {
  207. aiMaterial* out = new aiMaterial();
  208. material_mapping[mat] = static_cast<unsigned int>(materials.size());
  209. materials.push_back(out);
  210. auto const ai_name = aiStringFrom(mat->GetName());
  211. out->AddProperty(&ai_name, AI_MATKEY_NAME);
  212. Material& m = dynamic_cast<Material&>(*mat);
  213. if (m.GetChannelState(CHANNEL_COLOR)) {
  214. GeData data;
  215. mat->GetParameter(MATERIAL_COLOR_COLOR, data);
  216. Vector color = data.GetVector();
  217. mat->GetParameter(MATERIAL_COLOR_BRIGHTNESS, data);
  218. const Float brightness = data.GetFloat();
  219. color *= brightness;
  220. aiVector3D v;
  221. v.x = color.x;
  222. v.y = color.y;
  223. v.z = color.z;
  224. out->AddProperty(&v, 1, AI_MATKEY_COLOR_DIFFUSE);
  225. }
  226. BaseShader* const shader = m.GetShader(MATERIAL_COLOR_SHADER);
  227. if(shader) {
  228. ReadShader(out, shader);
  229. }
  230. } else {
  231. LogWarn("ignoring plugin material: ", GetObjectTypeName(mat->GetType()));
  232. }
  233. mat = mat->GetNext();
  234. }
  235. }
  236. // ------------------------------------------------------------------------------------------------
  237. void C4DImporter::RecurseHierarchy(BaseObject* object, aiNode* parent) {
  238. ai_assert(parent != nullptr );
  239. std::vector<aiNode*> nodes;
  240. // based on Cineware sample code
  241. while (object) {
  242. const Int32 type = object->GetType();
  243. const Matrix& ml = object->GetMl();
  244. aiNode* const nd = new aiNode();
  245. nd->mParent = parent;
  246. nd->mName = aiStringFrom(object->GetName());
  247. nd->mTransformation.a1 = ml.v1.x;
  248. nd->mTransformation.b1 = ml.v1.y;
  249. nd->mTransformation.c1 = ml.v1.z;
  250. nd->mTransformation.a2 = ml.v2.x;
  251. nd->mTransformation.b2 = ml.v2.y;
  252. nd->mTransformation.c2 = ml.v2.z;
  253. nd->mTransformation.a3 = ml.v3.x;
  254. nd->mTransformation.b3 = ml.v3.y;
  255. nd->mTransformation.c3 = ml.v3.z;
  256. nd->mTransformation.a4 = ml.off.x;
  257. nd->mTransformation.b4 = ml.off.y;
  258. nd->mTransformation.c4 = ml.off.z;
  259. nodes.push_back(nd);
  260. GeData data;
  261. if (type == Ocamera) {
  262. object->GetParameter(CAMERAOBJECT_FOV, data);
  263. // TODO: read camera
  264. } else if (type == Olight) {
  265. // TODO: read light
  266. } else if (type == Opolygon) {
  267. aiMesh* const mesh = ReadMesh(object);
  268. if(mesh != nullptr) {
  269. nd->mNumMeshes = 1;
  270. nd->mMeshes = new unsigned int[1];
  271. nd->mMeshes[0] = static_cast<unsigned int>(meshes.size());
  272. meshes.push_back(mesh);
  273. }
  274. } else {
  275. LogWarn("ignoring object: ", GetObjectTypeName(type));
  276. }
  277. RecurseHierarchy(object->GetDown(), nd);
  278. object = object->GetNext();
  279. }
  280. // copy nodes over to parent
  281. parent->mNumChildren = static_cast<unsigned int>(nodes.size());
  282. parent->mChildren = new aiNode*[parent->mNumChildren]();
  283. std::copy(nodes.begin(), nodes.end(), parent->mChildren);
  284. }
  285. // ------------------------------------------------------------------------------------------------
  286. aiMesh* C4DImporter::ReadMesh(BaseObject* object) {
  287. ai_assert(object != nullptr);
  288. ai_assert( object->GetType() == Opolygon );
  289. // based on Cineware sample code
  290. PolygonObject* const polyObject = dynamic_cast<PolygonObject*>(object);
  291. ai_assert(polyObject != nullptr);
  292. const Int32 pointCount = polyObject->GetPointCount();
  293. const Int32 polyCount = polyObject->GetPolygonCount();
  294. if(!polyObject || !pointCount) {
  295. LogWarn("ignoring mesh with zero vertices or faces");
  296. return nullptr;
  297. }
  298. const Vector* points = polyObject->GetPointR();
  299. ai_assert(points != nullptr);
  300. const CPolygon* polys = polyObject->GetPolygonR();
  301. ai_assert(polys != nullptr);
  302. std::unique_ptr<aiMesh> mesh(new aiMesh());
  303. mesh->mNumFaces = static_cast<unsigned int>(polyCount);
  304. aiFace* face = mesh->mFaces = new aiFace[mesh->mNumFaces]();
  305. mesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  306. mesh->mMaterialIndex = 0;
  307. unsigned int vcount = 0;
  308. // first count vertices
  309. for (Int32 i = 0; i < polyCount; i++)
  310. {
  311. vcount += 3;
  312. // TODO: do we also need to handle lines or points with similar checks?
  313. if (polys[i].c != polys[i].d)
  314. {
  315. mesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  316. ++vcount;
  317. }
  318. }
  319. ai_assert(vcount > 0);
  320. mesh->mNumVertices = vcount;
  321. aiVector3D* verts = mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  322. aiVector3D* normals, *uvs, *tangents, *bitangents;
  323. unsigned int n = 0;
  324. // check if there are normals, tangents or UVW coordinates
  325. BaseTag* tag = object->GetTag(Tnormal);
  326. NormalTag* normals_src = nullptr;
  327. if(tag) {
  328. normals_src = dynamic_cast<NormalTag*>(tag);
  329. normals = mesh->mNormals = new aiVector3D[mesh->mNumVertices]();
  330. }
  331. tag = object->GetTag(Ttangent);
  332. TangentTag* tangents_src = nullptr;
  333. if(tag) {
  334. tangents_src = dynamic_cast<TangentTag*>(tag);
  335. tangents = mesh->mTangents = new aiVector3D[mesh->mNumVertices]();
  336. bitangents = mesh->mBitangents = new aiVector3D[mesh->mNumVertices]();
  337. }
  338. tag = object->GetTag(Tuvw);
  339. UVWTag* uvs_src = nullptr;
  340. if(tag) {
  341. uvs_src = dynamic_cast<UVWTag*>(tag);
  342. uvs = mesh->mTextureCoords[0] = new aiVector3D[mesh->mNumVertices]();
  343. }
  344. // copy vertices and extra channels over and populate faces
  345. for (Int32 i = 0; i < polyCount; ++i, ++face) {
  346. ai_assert(polys[i].a < pointCount && polys[i].a >= 0);
  347. const Vector& pointA = points[polys[i].a];
  348. verts->x = pointA.x;
  349. verts->y = pointA.y;
  350. verts->z = pointA.z;
  351. ++verts;
  352. ai_assert(polys[i].b < pointCount && polys[i].b >= 0);
  353. const Vector& pointB = points[polys[i].b];
  354. verts->x = pointB.x;
  355. verts->y = pointB.y;
  356. verts->z = pointB.z;
  357. ++verts;
  358. ai_assert(polys[i].c < pointCount && polys[i].c >= 0);
  359. const Vector& pointC = points[polys[i].c];
  360. verts->x = pointC.x;
  361. verts->y = pointC.y;
  362. verts->z = pointC.z;
  363. ++verts;
  364. // TODO: do we also need to handle lines or points with similar checks?
  365. if (polys[i].c != polys[i].d) {
  366. ai_assert(polys[i].d < pointCount && polys[i].d >= 0);
  367. face->mNumIndices = 4;
  368. mesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  369. const Vector& pointD = points[polys[i].d];
  370. verts->x = pointD.x;
  371. verts->y = pointD.y;
  372. verts->z = pointD.z;
  373. ++verts;
  374. } else {
  375. face->mNumIndices = 3;
  376. }
  377. face->mIndices = new unsigned int[face->mNumIndices];
  378. for(unsigned int j = 0; j < face->mNumIndices; ++j) {
  379. face->mIndices[j] = n++;
  380. }
  381. // copy normals
  382. if (normals_src) {
  383. if(i >= normals_src->GetDataCount()) {
  384. LogError("unexpected number of normals, ignoring");
  385. } else {
  386. ConstNormalHandle normal_handle = normals_src->GetDataAddressR();
  387. NormalStruct nor;
  388. NormalTag::Get(normal_handle, i, nor);
  389. normals->x = nor.a.x;
  390. normals->y = nor.a.y;
  391. normals->z = nor.a.z;
  392. ++normals;
  393. normals->x = nor.b.x;
  394. normals->y = nor.b.y;
  395. normals->z = nor.b.z;
  396. ++normals;
  397. normals->x = nor.c.x;
  398. normals->y = nor.c.y;
  399. normals->z = nor.c.z;
  400. ++normals;
  401. if(face->mNumIndices == 4) {
  402. normals->x = nor.d.x;
  403. normals->y = nor.d.y;
  404. normals->z = nor.d.z;
  405. ++normals;
  406. }
  407. }
  408. }
  409. // copy tangents and bitangents
  410. if (tangents_src) {
  411. for(unsigned int k = 0; k < face->mNumIndices; ++k) {
  412. Int32 l;
  413. switch(k) {
  414. case 0:
  415. l = polys[i].a;
  416. break;
  417. case 1:
  418. l = polys[i].b;
  419. break;
  420. case 2:
  421. l = polys[i].c;
  422. break;
  423. case 3:
  424. l = polys[i].d;
  425. break;
  426. default:
  427. ai_assert(false);
  428. }
  429. if(l >= tangents_src->GetDataCount()) {
  430. LogError("unexpected number of tangents, ignoring");
  431. break;
  432. }
  433. Tangent tan = tangents_src->GetDataR()[l];
  434. tangents->x = tan.vl.x;
  435. tangents->y = tan.vl.y;
  436. tangents->z = tan.vl.z;
  437. ++tangents;
  438. bitangents->x = tan.vr.x;
  439. bitangents->y = tan.vr.y;
  440. bitangents->z = tan.vr.z;
  441. ++bitangents;
  442. }
  443. }
  444. // copy UVs
  445. if (uvs_src) {
  446. if(i >= uvs_src->GetDataCount()) {
  447. LogError("unexpected number of UV coordinates, ignoring");
  448. }
  449. else {
  450. UVWStruct uvw;
  451. uvs_src->Get(uvs_src->GetDataAddressR(),i,uvw);
  452. uvs->x = uvw.a.x;
  453. uvs->y = 1.0f-uvw.a.y;
  454. uvs->z = uvw.a.z;
  455. ++uvs;
  456. uvs->x = uvw.b.x;
  457. uvs->y = 1.0f-uvw.b.y;
  458. uvs->z = uvw.b.z;
  459. ++uvs;
  460. uvs->x = uvw.c.x;
  461. uvs->y = 1.0f-uvw.c.y;
  462. uvs->z = uvw.c.z;
  463. ++uvs;
  464. if(face->mNumIndices == 4) {
  465. uvs->x = uvw.d.x;
  466. uvs->y = 1.0f-uvw.d.y;
  467. uvs->z = uvw.d.z;
  468. ++uvs;
  469. }
  470. }
  471. }
  472. }
  473. mesh->mMaterialIndex = ResolveMaterial(polyObject);
  474. return mesh.release();
  475. }
  476. // ------------------------------------------------------------------------------------------------
  477. unsigned int C4DImporter::ResolveMaterial(PolygonObject* obj) {
  478. ai_assert(obj != nullptr);
  479. const unsigned int mat_count = static_cast<unsigned int>(materials.size());
  480. BaseTag* tag = obj->GetTag(Ttexture);
  481. if(tag == nullptr) {
  482. return mat_count;
  483. }
  484. TextureTag& ttag = dynamic_cast<TextureTag&>(*tag);
  485. BaseMaterial* const mat = ttag.GetMaterial();
  486. ai_assert(mat != nullptr);
  487. const MaterialMap::const_iterator it = material_mapping.find(mat);
  488. if(it == material_mapping.end()) {
  489. return mat_count;
  490. }
  491. ai_assert((*it).second < mat_count);
  492. return (*it).second;
  493. }
  494. #endif // ASSIMP_BUILD_NO_C4D_IMPORTER