BlenderLoader.cpp 31 KB

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