C4DImporter.cpp 20 KB

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