BlenderLoader.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  1. /*
  2. Open Asset Import Library (ASSIMP)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2010, ASSIMP Development 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 Development 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 BlenderLoader.cpp
  34. * @brief Implementation of the Blender3D importer class.
  35. */
  36. #include "AssimpPCH.h"
  37. #ifndef ASSIMP_BUILD_NO_BLEND_IMPORTER
  38. #include "BlenderLoader.h"
  39. #include "BlenderDNA.h"
  40. #include "BlenderScene.h"
  41. #include "BlenderSceneGen.h"
  42. #include "StreamReader.h"
  43. #include "TinyFormatter.h"
  44. //#include <boost/make_shared.hpp>
  45. using namespace Assimp;
  46. using namespace Assimp::Blender;
  47. using namespace Assimp::Formatter;
  48. #define for_each(x,y) BOOST_FOREACH(x,y)
  49. static const aiLoaderDesc blenderDesc = {
  50. "Blender 3D Importer \nhttp://www.blender3d.org",
  51. "Alexander Gessler <[email protected]>",
  52. "",
  53. "",
  54. aiLoaderFlags_SupportBinaryFlavour | aiLoaderFlags_Experimental,
  55. 0,
  56. 0,
  57. 2,
  58. 50
  59. };
  60. namespace Assimp {
  61. namespace Blender {
  62. // --------------------------------------------------------------------
  63. /** Mini smart-array to avoid pulling in even more boost stuff. usable with vector and deque */
  64. // --------------------------------------------------------------------
  65. template <template <typename,typename> class TCLASS, typename T>
  66. struct TempArray {
  67. typedef TCLASS< T*,std::allocator<T*> > mywrap;
  68. TempArray() {
  69. }
  70. ~TempArray () {
  71. for_each(T* elem, arr) {
  72. delete elem;
  73. }
  74. }
  75. void dismiss() {
  76. arr.clear();
  77. }
  78. mywrap* operator -> () {
  79. return &arr;
  80. }
  81. operator mywrap& () {
  82. return arr;
  83. }
  84. operator const mywrap& () const {
  85. return arr;
  86. }
  87. mywrap& get () {
  88. return arr;
  89. }
  90. const mywrap& get () const {
  91. return arr;
  92. }
  93. T* operator[] (size_t idx) const {
  94. return arr[idx];
  95. }
  96. private:
  97. // no copy semantics
  98. void operator= (const TempArray&) {
  99. }
  100. TempArray(const TempArray& arr) {
  101. }
  102. private:
  103. mywrap arr;
  104. };
  105. #ifdef _MSC_VER
  106. # pragma warning(disable:4351)
  107. #endif
  108. // --------------------------------------------------------------------
  109. /** ConversionData acts as intermediate storage location for
  110. * the various ConvertXXX routines in BlenderImporter.*/
  111. // --------------------------------------------------------------------
  112. struct ConversionData
  113. {
  114. ConversionData(const FileDatabase& db)
  115. : sentinel_cnt()
  116. , next_texture()
  117. , db(db)
  118. {}
  119. std::set<const Object*> objects;
  120. TempArray <std::vector, aiMesh> meshes;
  121. TempArray <std::vector, aiCamera> cameras;
  122. TempArray <std::vector, aiLight> lights;
  123. TempArray <std::vector, aiMaterial> materials;
  124. TempArray <std::vector, aiTexture> textures;
  125. // set of all materials referenced by at least one mesh in the scene
  126. std::deque< boost::shared_ptr< Material > > materials_raw;
  127. // counter to name sentinel textures inserted as substitutes for procedural textures.
  128. unsigned int sentinel_cnt;
  129. // next texture ID for each texture type, respectively
  130. unsigned int next_texture[aiTextureType_UNKNOWN+1];
  131. // original file data
  132. const FileDatabase& db;
  133. };
  134. #ifdef _MSC_VER
  135. # pragma warning(default:4351)
  136. #endif
  137. // ------------------------------------------------------------------------------------------------
  138. const char* GetTextureTypeDisplayString(Tex::Type t)
  139. {
  140. switch (t) {
  141. case Tex::Type_CLOUDS : return "Clouds";
  142. case Tex::Type_WOOD : return "Wood";
  143. case Tex::Type_MARBLE : return "Marble";
  144. case Tex::Type_MAGIC : return "Magic";
  145. case Tex::Type_BLEND : return "Blend";
  146. case Tex::Type_STUCCI : return "Stucci";
  147. case Tex::Type_NOISE : return "Noise";
  148. case Tex::Type_PLUGIN : return "Plugin";
  149. case Tex::Type_MUSGRAVE : return "Musgrave";
  150. case Tex::Type_VORONOI : return "Voronoi";
  151. case Tex::Type_DISTNOISE : return "DistortedNoise";
  152. case Tex::Type_ENVMAP : return "EnvMap";
  153. case Tex::Type_IMAGE : return "Image";
  154. default:
  155. break;
  156. }
  157. return "<Unknown>";
  158. }
  159. } // ! Blender
  160. } // ! Assimp
  161. // ------------------------------------------------------------------------------------------------
  162. // Constructor to be privately used by Importer
  163. BlenderImporter::BlenderImporter()
  164. {}
  165. // ------------------------------------------------------------------------------------------------
  166. // Destructor, private as well
  167. BlenderImporter::~BlenderImporter()
  168. {}
  169. // ------------------------------------------------------------------------------------------------
  170. // Returns whether the class can handle the format of the given file.
  171. bool BlenderImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  172. {
  173. const std::string& extension = GetExtension(pFile);
  174. if (extension == "blend") {
  175. return true;
  176. }
  177. else if ((!extension.length() || checkSig) && pIOHandler) {
  178. const char* tokens[] = {"BLENDER"};
  179. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1);
  180. }
  181. return false;
  182. }
  183. // ------------------------------------------------------------------------------------------------
  184. // List all extensions handled by this loader
  185. void BlenderImporter::GetExtensionList(std::set<std::string>& app)
  186. {
  187. app.insert("blend");
  188. }
  189. // ------------------------------------------------------------------------------------------------
  190. // Loader registry entry
  191. const aiLoaderDesc& BlenderImporter::GetInfo () const
  192. {
  193. return blenderDesc;
  194. }
  195. // ------------------------------------------------------------------------------------------------
  196. // Setup configuration properties for the loader
  197. void BlenderImporter::SetupProperties(const Importer* pImp)
  198. {
  199. // nothing to be done for the moment
  200. }
  201. // ------------------------------------------------------------------------------------------------
  202. // Imports the given file into the given scene structure.
  203. void BlenderImporter::InternReadFile( const std::string& pFile,
  204. aiScene* pScene, IOSystem* pIOHandler)
  205. {
  206. FileDatabase file;
  207. boost::shared_ptr<IOStream> stream(pIOHandler->Open(pFile,"rb"));
  208. if (!stream) {
  209. ThrowException("Could not open file for reading");
  210. }
  211. char magic[8] = {0};
  212. stream->Read(magic,7,1);
  213. if (strcmp(magic,"BLENDER")) {
  214. ThrowException("BLENDER magic bytes are missing");
  215. }
  216. file.i64bit = (stream->Read(magic,1,1),magic[0]=='-');
  217. file.little = (stream->Read(magic,1,1),magic[0]=='v');
  218. stream->Read(magic,3,1);
  219. magic[3] = '\0';
  220. LogInfo((format(),"Blender version is ",magic[0],".",magic+1,
  221. " (64bit: ",file.i64bit?"true":"false",
  222. ", little endian: ",file.little?"true":"false",")"
  223. ));
  224. ParseBlendFile(file,stream);
  225. Scene scene;
  226. ExtractScene(scene,file);
  227. ConvertBlendFile(pScene,scene,file);
  228. }
  229. // ------------------------------------------------------------------------------------------------
  230. void BlenderImporter::ParseBlendFile(FileDatabase& out, boost::shared_ptr<IOStream> stream)
  231. {
  232. out.reader = boost::shared_ptr<StreamReaderAny>(new StreamReaderAny(stream,out.little));
  233. DNAParser dna_reader(out);
  234. const DNA* dna = NULL;
  235. out.entries.reserve(128); { // even small BLEND files tend to consist of many file blocks
  236. SectionParser parser(*out.reader.get(),out.i64bit);
  237. // first parse the file in search for the DNA and insert all other sections into the database
  238. while ((parser.Next(),1)) {
  239. const FileBlockHead& head = parser.GetCurrent();
  240. if (head.id == "ENDB") {
  241. break; // only valid end of the file
  242. }
  243. else if (head.id == "DNA1") {
  244. dna_reader.Parse();
  245. dna = &dna_reader.GetDNA();
  246. continue;
  247. }
  248. out.entries.push_back(head);
  249. }
  250. }
  251. if (!dna) {
  252. ThrowException("SDNA not found");
  253. }
  254. std::sort(out.entries.begin(),out.entries.end());
  255. }
  256. // ------------------------------------------------------------------------------------------------
  257. void BlenderImporter::ExtractScene(Scene& out, const FileDatabase& file)
  258. {
  259. const FileBlockHead* block = NULL;
  260. std::map<std::string,size_t>::const_iterator it = file.dna.indices.find("Scene");
  261. if (it == file.dna.indices.end()) {
  262. ThrowException("There is no `Scene` structure record");
  263. }
  264. const Structure& ss = file.dna.structures[(*it).second];
  265. // we need a scene somewhere to start with.
  266. for_each(const FileBlockHead& bl,file.entries) {
  267. if (bl.id == "SC") {
  268. block = &bl;
  269. break;
  270. }
  271. }
  272. if (!block) {
  273. ThrowException("There is not a single `Scene` record to load");
  274. }
  275. file.reader->SetCurrentPos(block->start);
  276. ss.Convert(out,file);
  277. #ifndef ASSIMP_BUILD_BLENDER_NO_STATS
  278. DefaultLogger::get()->info((format(),
  279. "(Stats) Fields read: " ,file.stats().fields_read,
  280. ", pointers resolved: " ,file.stats().pointers_resolved,
  281. ", cache hits: " ,file.stats().cache_hits,
  282. ", cached objects: " ,file.stats().cached_objects
  283. ));
  284. #endif
  285. }
  286. // ------------------------------------------------------------------------------------------------
  287. void BlenderImporter::ConvertBlendFile(aiScene* out, const Scene& in,const FileDatabase& file)
  288. {
  289. ConversionData conv(file);
  290. // FIXME it must be possible to take the hierarchy directly from
  291. // the file. This is terrible. Here, we're first looking for
  292. // all objects which don't have parent objects at all -
  293. std::deque<const Object*> no_parents;
  294. for (boost::shared_ptr<Base> cur = boost::static_pointer_cast<Base> ( in.base.first ); cur; cur = cur->next) {
  295. if (cur->object) {
  296. if(!cur->object->parent) {
  297. no_parents.push_back(cur->object.get());
  298. }
  299. else conv.objects.insert(cur->object.get());
  300. }
  301. }
  302. for (boost::shared_ptr<Base> cur = in.basact; cur; cur = cur->next) {
  303. if (cur->object) {
  304. if(cur->object->parent) {
  305. conv.objects.insert(cur->object.get());
  306. }
  307. }
  308. }
  309. if (no_parents.empty()) {
  310. ThrowException("Expected at least one object with no parent");
  311. }
  312. aiNode* root = out->mRootNode = new aiNode("<BlenderRoot>");
  313. root->mNumChildren = static_cast<unsigned int>(no_parents.size());
  314. root->mChildren = new aiNode*[root->mNumChildren]();
  315. for (unsigned int i = 0; i < root->mNumChildren; ++i) {
  316. root->mChildren[i] = ConvertNode(in, no_parents[i], conv);
  317. root->mChildren[i]->mParent = root;
  318. }
  319. BuildMaterials(conv);
  320. if (conv.meshes->size()) {
  321. out->mMeshes = new aiMesh*[out->mNumMeshes = static_cast<unsigned int>( conv.meshes->size() )];
  322. std::copy(conv.meshes->begin(),conv.meshes->end(),out->mMeshes);
  323. conv.meshes.dismiss();
  324. }
  325. if (conv.lights->size()) {
  326. out->mLights = new aiLight*[out->mNumLights = static_cast<unsigned int>( conv.lights->size() )];
  327. std::copy(conv.lights->begin(),conv.lights->end(),out->mLights);
  328. conv.lights.dismiss();
  329. }
  330. if (conv.cameras->size()) {
  331. out->mCameras = new aiCamera*[out->mNumCameras = static_cast<unsigned int>( conv.cameras->size() )];
  332. std::copy(conv.cameras->begin(),conv.cameras->end(),out->mCameras);
  333. conv.cameras.dismiss();
  334. }
  335. if (conv.materials->size()) {
  336. out->mMaterials = new aiMaterial*[out->mNumMaterials = static_cast<unsigned int>( conv.materials->size() )];
  337. std::copy(conv.materials->begin(),conv.materials->end(),out->mMaterials);
  338. conv.materials.dismiss();
  339. }
  340. if (conv.textures->size()) {
  341. out->mTextures = new aiTexture*[out->mNumTextures = static_cast<unsigned int>( conv.textures->size() )];
  342. std::copy(conv.textures->begin(),conv.textures->end(),out->mTextures);
  343. conv.textures.dismiss();
  344. }
  345. // acknowledge that the scene might come out incomplete
  346. // by Assimps definition of `complete`: blender scenes
  347. // can consist of thousands of cameras or lights with
  348. // not a single mesh between them.
  349. if (!out->mNumMeshes) {
  350. out->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  351. }
  352. }
  353. // ------------------------------------------------------------------------------------------------
  354. void BlenderImporter::ResolveImage(MaterialHelper* out, const Material* mat, const MTex* tex, const Image* img, ConversionData& conv_data)
  355. {
  356. mat; tex; conv_data;
  357. aiString name;
  358. // check if the file contents are bundled with the BLEND file
  359. if (img->packedfile) {
  360. name.data[0] = '*';
  361. name.length = 1+ ASSIMP_itoa10(name.data+1,MAXLEN-1,conv_data.textures->size());
  362. conv_data.textures->push_back(new aiTexture());
  363. aiTexture* tex = conv_data.textures->back();
  364. // usually 'img->name' will be the original file name of the embedded textures,
  365. // so we can extract the file extension from it.
  366. const size_t nlen = strlen( img->name );
  367. const char* s = img->name+nlen, *e = s;
  368. while (s >= img->name && *s != '.')--s;
  369. tex->achFormatHint[0] = s+1>e ? '\0' : s[1];
  370. tex->achFormatHint[1] = s+2>e ? '\0' : s[2];
  371. tex->achFormatHint[2] = s+3>e ? '\0' : s[3];
  372. tex->achFormatHint[3] = '\0';
  373. // tex->mHeight = 0;
  374. tex->mWidth = img->packedfile->size;
  375. uint8_t* ch = new uint8_t[tex->mWidth];
  376. conv_data.db.reader->SetCurrentPos(img->packedfile->data->val);
  377. conv_data.db.reader->CopyAndAdvance(ch,tex->mWidth);
  378. tex->pcData = reinterpret_cast<aiTexel*>(ch);
  379. LogInfo("Reading embedded texture, original file was "+std::string(img->name));
  380. }
  381. else {
  382. name = aiString( img->name );
  383. }
  384. out->AddProperty(&name,AI_MATKEY_TEXTURE_DIFFUSE(
  385. conv_data.next_texture[aiTextureType_DIFFUSE]++)
  386. );
  387. }
  388. // ------------------------------------------------------------------------------------------------
  389. void BlenderImporter::AddSentinelTexture(MaterialHelper* out, const Material* mat, const MTex* tex, ConversionData& conv_data)
  390. {
  391. mat; tex; conv_data;
  392. aiString name;
  393. name.length = sprintf(name.data, "Procedural,num=%i,type=%s",conv_data.sentinel_cnt++,
  394. GetTextureTypeDisplayString(tex->tex->type)
  395. );
  396. out->AddProperty(&name,AI_MATKEY_TEXTURE_DIFFUSE(
  397. conv_data.next_texture[aiTextureType_DIFFUSE]++)
  398. );
  399. }
  400. // ------------------------------------------------------------------------------------------------
  401. void BlenderImporter::ResolveTexture(MaterialHelper* out, const Material* mat, const MTex* tex, ConversionData& conv_data)
  402. {
  403. const Tex* rtex = tex->tex.get();
  404. if(!rtex || !rtex->type) {
  405. return;
  406. }
  407. // We can't support most of the texture types because the're mostly procedural.
  408. // These are substituted by a dummy texture.
  409. const char* dispnam = "";
  410. switch( rtex->type )
  411. {
  412. // these are listed in blender's UI
  413. case Tex::Type_CLOUDS :
  414. case Tex::Type_WOOD :
  415. case Tex::Type_MARBLE :
  416. case Tex::Type_MAGIC :
  417. case Tex::Type_BLEND :
  418. case Tex::Type_STUCCI :
  419. case Tex::Type_NOISE :
  420. case Tex::Type_PLUGIN :
  421. case Tex::Type_MUSGRAVE :
  422. case Tex::Type_VORONOI :
  423. case Tex::Type_DISTNOISE :
  424. case Tex::Type_ENVMAP :
  425. // these do no appear in the UI, why?
  426. case Tex::Type_POINTDENSITY :
  427. case Tex::Type_VOXELDATA :
  428. LogWarn(std::string("Encountered a texture with an unsupported type: ")+dispnam);
  429. AddSentinelTexture(out, mat, tex, conv_data);
  430. break;
  431. case Tex::Type_IMAGE :
  432. if (!rtex->ima) {
  433. LogError("A texture claims to be an Image, but no image reference is given");
  434. break;
  435. }
  436. ResolveImage(out, mat, tex, rtex->ima.get(),conv_data);
  437. break;
  438. default:
  439. ai_assert(false);
  440. };
  441. }
  442. // ------------------------------------------------------------------------------------------------
  443. void BlenderImporter::BuildMaterials(ConversionData& conv_data)
  444. {
  445. conv_data.materials->reserve(conv_data.materials_raw.size());
  446. // add a default material if necessary
  447. unsigned int index = static_cast<unsigned int>( -1 );
  448. for_each( aiMesh* mesh, conv_data.meshes.get() ) {
  449. if (mesh->mMaterialIndex == static_cast<unsigned int>( -1 )) {
  450. if (index == static_cast<unsigned int>( -1 )) {
  451. // ok, we need to add a dedicated default material for some poor material-less meshes
  452. boost::shared_ptr<Material> p(new Material());
  453. strcpy( p->id.name, "$AssimpDefault" );
  454. p->r = p->g = p->b = 0.6f;
  455. p->specr = p->specg = p->specb = 0.6f;
  456. p->ambir = p->ambig = p->ambib = 0.0f;
  457. p->mirr = p->mirg = p->mirb = 0.0f;
  458. p->emit = 0.f;
  459. p->alpha = 0.f;
  460. // XXX add more / or add default c'tor to Material
  461. index = static_cast<unsigned int>( conv_data.materials_raw.size() );
  462. conv_data.materials_raw.push_back(p);
  463. LogInfo("Adding default material ...");
  464. }
  465. mesh->mMaterialIndex = index;
  466. }
  467. }
  468. for_each(boost::shared_ptr<Material> mat, conv_data.materials_raw) {
  469. // reset per material global counters
  470. for (size_t i = 0; i < sizeof(conv_data.next_texture)/sizeof(conv_data.next_texture[0]);++i) {
  471. conv_data.next_texture[i] = 0 ;
  472. }
  473. MaterialHelper* mout = new MaterialHelper();
  474. conv_data.materials->push_back(mout);
  475. // set material name
  476. aiString name = aiString(mat->id.name);
  477. mout->AddProperty(&name,AI_MATKEY_NAME);
  478. // basic material colors
  479. aiColor3D col(mat->r,mat->g,mat->b);
  480. mout->AddProperty(&col,1,AI_MATKEY_COLOR_DIFFUSE);
  481. col = aiColor3D(mat->specr,mat->specg,mat->specb);
  482. mout->AddProperty(&col,1,AI_MATKEY_COLOR_SPECULAR);
  483. col = aiColor3D(mat->ambir,mat->ambig,mat->ambib);
  484. mout->AddProperty(&col,1,AI_MATKEY_COLOR_AMBIENT);
  485. col = aiColor3D(mat->mirr,mat->mirg,mat->mirb);
  486. mout->AddProperty(&col,1,AI_MATKEY_COLOR_REFLECTIVE);
  487. for(size_t i = 0; i < sizeof(mat->mtex) / sizeof(mat->mtex[0]); ++i) {
  488. if (!mat->mtex[i]) {
  489. continue;
  490. }
  491. ResolveTexture(mout,mat.get(),mat->mtex[i].get(),conv_data);
  492. }
  493. }
  494. }
  495. // ------------------------------------------------------------------------------------------------
  496. void BlenderImporter::CheckActualType(const ElemBase* dt, const char* check)
  497. {
  498. ai_assert(dt);
  499. if (strcmp(dt->dna_type,check)) {
  500. ThrowException((format(),
  501. "Expected object at ",std::hex,dt," to be of type `",check,
  502. "`, but it claims to be a `",dt->dna_type,"`instead"
  503. ));
  504. }
  505. }
  506. // ------------------------------------------------------------------------------------------------
  507. void BlenderImporter::NotSupportedObjectType(const Object* obj, const char* type)
  508. {
  509. LogWarn((format(), "Object `",obj->id.name,"` - type is unsupported: `",type, "`, skipping" ));
  510. }
  511. // ------------------------------------------------------------------------------------------------
  512. void BlenderImporter::ConvertMesh(const Scene& in, const Object* obj, const Mesh* mesh,
  513. ConversionData& conv_data, TempArray<std::vector,aiMesh>& temp
  514. )
  515. {
  516. typedef std::pair<const int,size_t> MyPair;
  517. if (!mesh->totface || !mesh->totvert) {
  518. return;
  519. }
  520. // some sanity checks
  521. if (static_cast<size_t> ( mesh->totface ) > mesh->mface.size() ){
  522. ThrowException("Number of faces is larger than the corresponding array");
  523. }
  524. if (static_cast<size_t> ( mesh->totvert ) > mesh->mvert.size()) {
  525. ThrowException("Number of vertices is larger than the corresponding array");
  526. }
  527. // collect per-submesh numbers
  528. std::map<int,size_t> per_mat;
  529. for (int i = 0; i < mesh->totface; ++i) {
  530. const MFace& mf = mesh->mface[i];
  531. per_mat[ mf.mat_nr ]++;
  532. }
  533. // ... and allocate the corresponding meshes
  534. const size_t old = temp->size();
  535. temp->reserve(temp->size() + per_mat.size());
  536. std::map<size_t,size_t> mat_num_to_mesh_idx;
  537. for_each(MyPair& it, per_mat) {
  538. mat_num_to_mesh_idx[it.first] = temp->size();
  539. temp->push_back(new aiMesh());
  540. aiMesh* out = temp->back();
  541. out->mVertices = new aiVector3D[it.second*4];
  542. out->mNormals = new aiVector3D[it.second*4];
  543. //out->mNumFaces = 0
  544. //out->mNumVertices = 0
  545. out->mFaces = new aiFace[it.second]();
  546. // all submeshes created from this mesh are named equally. this allows
  547. // curious users to recover the original adjacency.
  548. out->mName = aiString(mesh->id.name);
  549. // resolve the material reference and add this material to the set of
  550. // output materials. The (temporary) material index is the index
  551. // of the material entry within the list of resolved materials.
  552. if (mesh->mat) {
  553. if (it.first >= mesh->mat.size() ) {
  554. ThrowException("Material index is out of range");
  555. }
  556. boost::shared_ptr<Material> mat = mesh->mat[it.first];
  557. const std::deque< boost::shared_ptr<Material> >::iterator has = std::find(
  558. conv_data.materials_raw.begin(),
  559. conv_data.materials_raw.end(),mat
  560. );
  561. if (has != conv_data.materials_raw.end()) {
  562. out->mMaterialIndex = static_cast<unsigned int>( std::distance(conv_data.materials_raw.begin(),has));
  563. }
  564. else {
  565. out->mMaterialIndex = static_cast<unsigned int>( conv_data.materials_raw.size() );
  566. conv_data.materials_raw.push_back(mat);
  567. }
  568. }
  569. else out->mMaterialIndex = static_cast<unsigned int>( -1 );
  570. }
  571. for (int i = 0; i < mesh->totface; ++i) {
  572. const MFace& mf = mesh->mface[i];
  573. aiMesh* const out = temp[ mat_num_to_mesh_idx[ mf.mat_nr ] ];
  574. aiFace& f = out->mFaces[out->mNumFaces++];
  575. f.mIndices = new unsigned int[ f.mNumIndices = mf.v4?4:3 ];
  576. aiVector3D* vo = out->mVertices + out->mNumVertices;
  577. aiVector3D* vn = out->mNormals + out->mNumVertices;
  578. // XXX we can't fold this easily, because we are restricted
  579. // to the member names from the BLEND file (v1,v2,v3,v4) ..
  580. if (mf.v1 >= mesh->totvert) {
  581. ThrowException("Vertex index v1 out of range");
  582. }
  583. const MVert* v = &mesh->mvert[mf.v1];
  584. vo->x = v->co[0];
  585. vo->y = v->co[1];
  586. vo->z = v->co[2];
  587. vn->x = v->no[0];
  588. vn->y = v->no[1];
  589. vn->z = v->no[2];
  590. f.mIndices[0] = out->mNumVertices++;
  591. ++vo;
  592. ++vn;
  593. // if (f.mNumIndices >= 2) {
  594. if (mf.v2 >= mesh->totvert) {
  595. ThrowException("Vertex index v2 out of range");
  596. }
  597. v = &mesh->mvert[mf.v2];
  598. vo->x = v->co[0];
  599. vo->y = v->co[1];
  600. vo->z = v->co[2];
  601. vn->x = v->no[0];
  602. vn->y = v->no[1];
  603. vn->z = v->no[2];
  604. f.mIndices[1] = out->mNumVertices++;
  605. ++vo;
  606. ++vn;
  607. if (mf.v3 >= mesh->totvert) {
  608. ThrowException("Vertex index v3 out of range");
  609. }
  610. // if (f.mNumIndices >= 3) {
  611. v = &mesh->mvert[mf.v3];
  612. vo->x = v->co[0];
  613. vo->y = v->co[1];
  614. vo->z = v->co[2];
  615. vn->x = v->no[0];
  616. vn->y = v->no[1];
  617. vn->z = v->no[2];
  618. f.mIndices[2] = out->mNumVertices++;
  619. ++vo;
  620. ++vn;
  621. if (mf.v4 >= mesh->totvert) {
  622. ThrowException("Vertex index v4 out of range");
  623. }
  624. // if (f.mNumIndices >= 4) {
  625. if (mf.v4) {
  626. v = &mesh->mvert[mf.v4];
  627. vo->x = v->co[0];
  628. vo->y = v->co[1];
  629. vo->z = v->co[2];
  630. vn->x = v->no[0];
  631. vn->y = v->no[1];
  632. vn->z = v->no[2];
  633. f.mIndices[3] = out->mNumVertices++;
  634. ++vo;
  635. ++vn;
  636. out->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  637. }
  638. else out->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  639. // }
  640. // }
  641. // }
  642. }
  643. // collect texture coordinates, they're stored in a separate per-face buffer
  644. if (mesh->mtface) {
  645. if (mesh->totface > mesh->mtface.size()) {
  646. ThrowException("Number of UV faces is larger than the corresponding UV face array (#1)");
  647. }
  648. for (std::vector<aiMesh*>::iterator it = temp->begin()+old; it != temp->end(); ++it) {
  649. ai_assert((*it)->mNumVertices && (*it)->mNumFaces);
  650. (*it)->mTextureCoords[0] = new aiVector3D[(*it)->mNumVertices];
  651. (*it)->mNumFaces = (*it)->mNumVertices = 0;
  652. }
  653. for (int i = 0; i < mesh->totface; ++i) {
  654. const MTFace* v = &mesh->mtface[i];
  655. aiMesh* const out = temp[ mat_num_to_mesh_idx[ mesh->mface[i].mat_nr ] ];
  656. const aiFace& f = out->mFaces[out->mNumFaces++];
  657. aiVector3D* vo = &out->mTextureCoords[0][out->mNumVertices];
  658. for (unsigned int i = 0; i < f.mNumIndices; ++i,++vo,++out->mNumVertices) {
  659. vo->x = v->uv[i][0];
  660. vo->y = v->uv[i][1];
  661. }
  662. }
  663. }
  664. // collect texture coordinates, old-style (marked as deprecated in current blender sources)
  665. if (mesh->tface) {
  666. if (mesh->totface > mesh->mtface.size()) {
  667. ThrowException("Number of faces is larger than the corresponding UV face array (#2)");
  668. }
  669. for (std::vector<aiMesh*>::iterator it = temp->begin()+old; it != temp->end(); ++it) {
  670. ai_assert((*it)->mNumVertices && (*it)->mNumFaces);
  671. (*it)->mTextureCoords[0] = new aiVector3D[(*it)->mNumVertices];
  672. (*it)->mNumFaces = (*it)->mNumVertices = 0;
  673. }
  674. for (int i = 0; i < mesh->totface; ++i) {
  675. const TFace* v = &mesh->tface[i];
  676. aiMesh* const out = temp[ mat_num_to_mesh_idx[ mesh->mface[i].mat_nr ] ];
  677. const aiFace& f = out->mFaces[out->mNumFaces++];
  678. aiVector3D* vo = &out->mTextureCoords[0][out->mNumVertices];
  679. for (unsigned int i = 0; i < f.mNumIndices; ++i,++vo,++out->mNumVertices) {
  680. vo->x = v->uv[i][0];
  681. vo->y = v->uv[i][1];
  682. }
  683. }
  684. }
  685. // collect vertex colors, stored separately as well
  686. if (mesh->mcol) {
  687. if (mesh->totface > (mesh->mcol.size()/4)) {
  688. ThrowException("Number of faces is larger than the corresponding color face array");
  689. }
  690. for (std::vector<aiMesh*>::iterator it = temp->begin()+old; it != temp->end(); ++it) {
  691. ai_assert((*it)->mNumVertices && (*it)->mNumFaces);
  692. (*it)->mColors[0] = new aiColor4D[(*it)->mNumVertices];
  693. (*it)->mNumFaces = (*it)->mNumVertices = 0;
  694. }
  695. for (int i = 0; i < mesh->totface; ++i) {
  696. aiMesh* const out = temp[ mat_num_to_mesh_idx[ mesh->mface[i].mat_nr ] ];
  697. const aiFace& f = out->mFaces[out->mNumFaces++];
  698. aiColor4D* vo = &out->mColors[0][out->mNumVertices];
  699. for (unsigned int n = 0; n < f.mNumIndices; ++n, ++vo,++out->mNumVertices) {
  700. const MCol* col = &mesh->mcol[(i<<2)+n];
  701. vo->r = col->r;
  702. vo->g = col->g;
  703. vo->b = col->b;
  704. vo->a = col->a;
  705. }
  706. for (unsigned int n = f.mNumIndices; n < 4; ++n);
  707. }
  708. }
  709. return;
  710. }
  711. // ------------------------------------------------------------------------------------------------
  712. aiCamera* BlenderImporter::ConvertCamera(const Scene& in, const Object* obj, const Camera* mesh, ConversionData& conv_data)
  713. {
  714. ScopeGuard<aiCamera> out(new aiCamera());
  715. return NULL ; //out.dismiss();
  716. }
  717. // ------------------------------------------------------------------------------------------------
  718. aiLight* BlenderImporter::ConvertLight(const Scene& in, const Object* obj, const Lamp* mesh, ConversionData& conv_data)
  719. {
  720. ScopeGuard<aiLight> out(new aiLight());
  721. return NULL ; //out.dismiss();
  722. }
  723. // ------------------------------------------------------------------------------------------------
  724. aiNode* BlenderImporter::ConvertNode(const Scene& in, const Object* obj, ConversionData& conv_data)
  725. {
  726. std::deque<const Object*> children;
  727. for(std::set<const Object*>::iterator it = conv_data.objects.begin(); it != conv_data.objects.end() ;) {
  728. const Object* object = *it;
  729. if (object->parent.get() == obj) {
  730. children.push_back(object);
  731. conv_data.objects.erase(it++);
  732. continue;
  733. }
  734. ++it;
  735. }
  736. ScopeGuard<aiNode> node(new aiNode(obj->id.name));
  737. if (obj->data) {
  738. switch (obj->type)
  739. {
  740. case Object :: Type_EMPTY:
  741. break; // do nothing
  742. // supported object types
  743. case Object :: Type_MESH: {
  744. const size_t old = conv_data.meshes->size();
  745. CheckActualType(obj->data.get(),"Mesh");
  746. ConvertMesh(in,obj,static_cast<const Mesh*>(obj->data.get()),conv_data,conv_data.meshes);
  747. if (conv_data.meshes->size() > old) {
  748. node->mMeshes = new unsigned int[node->mNumMeshes = static_cast<unsigned int>(conv_data.meshes->size()-old)];
  749. for (unsigned int i = 0; i < node->mNumMeshes; ++i) {
  750. node->mMeshes[i] = i + old;
  751. }
  752. }}
  753. break;
  754. case Object :: Type_LAMP: {
  755. CheckActualType(obj->data.get(),"Lamp");
  756. aiLight* mesh = ConvertLight(in,obj,static_cast<const Lamp*>(
  757. obj->data.get()),conv_data);
  758. if (mesh) {
  759. conv_data.lights->push_back(mesh);
  760. }}
  761. break;
  762. case Object :: Type_CAMERA: {
  763. CheckActualType(obj->data.get(),"Camera");
  764. aiCamera* mesh = ConvertCamera(in,obj,static_cast<const Camera*>(
  765. obj->data.get()),conv_data);
  766. if (mesh) {
  767. conv_data.cameras->push_back(mesh);
  768. }}
  769. break;
  770. // unsupported object types / log, but do not break
  771. case Object :: Type_CURVE:
  772. NotSupportedObjectType(obj,"Curve");
  773. break;
  774. case Object :: Type_SURF:
  775. NotSupportedObjectType(obj,"Surface");
  776. break;
  777. case Object :: Type_FONT:
  778. NotSupportedObjectType(obj,"Font");
  779. break;
  780. case Object :: Type_MBALL:
  781. NotSupportedObjectType(obj,"MetaBall");
  782. break;
  783. case Object :: Type_WAVE:
  784. NotSupportedObjectType(obj,"Wave");
  785. break;
  786. case Object :: Type_LATTICE:
  787. NotSupportedObjectType(obj,"Lattice");
  788. break;
  789. // invalid or unknown type
  790. default:
  791. break;
  792. }
  793. }
  794. for(unsigned int x = 0; x < 4; ++x) {
  795. for(unsigned int y = 0; y < 4; ++y) {
  796. node->mTransformation[y][x] = obj->parentinv[x][y];
  797. }
  798. }
  799. aiMatrix4x4 m;
  800. for(unsigned int x = 0; x < 4; ++x) {
  801. for(unsigned int y = 0; y < 4; ++y) {
  802. m[y][x] = obj->obmat[x][y];
  803. }
  804. }
  805. node->mTransformation = m*node->mTransformation;
  806. if (children.size()) {
  807. node->mNumChildren = static_cast<unsigned int>(children.size());
  808. aiNode** nd = node->mChildren = new aiNode*[node->mNumChildren]();
  809. for_each (const Object* nobj,children) {
  810. *nd = ConvertNode(in,nobj,conv_data);
  811. (*nd++)->mParent = node;
  812. }
  813. }
  814. return node.dismiss();
  815. }
  816. // ------------------------------------------------------------------------------------------------
  817. /*static*/ void BlenderImporter::ThrowException(const std::string& msg)
  818. {
  819. throw DeadlyImportError("BLEND: "+msg);
  820. }
  821. // ------------------------------------------------------------------------------------------------
  822. /*static*/ void BlenderImporter::LogWarn(const Formatter::format& message) {
  823. DefaultLogger::get()->warn(std::string("BLEND: ")+=message);
  824. }
  825. // ------------------------------------------------------------------------------------------------
  826. /*static*/ void BlenderImporter::LogError(const Formatter::format& message) {
  827. DefaultLogger::get()->error(std::string("BLEND: ")+=message);
  828. }
  829. // ------------------------------------------------------------------------------------------------
  830. /*static*/ void BlenderImporter::LogInfo(const Formatter::format& message) {
  831. DefaultLogger::get()->info(std::string("BLEND: ")+=message);
  832. }
  833. // ------------------------------------------------------------------------------------------------
  834. /*static*/ void BlenderImporter::LogDebug(const Formatter::format& message) {
  835. DefaultLogger::get()->debug(std::string("BLEND: ")+=message);
  836. }
  837. #endif