BlenderLoader.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2025, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. /** @file BlenderLoader.cpp
  34. * @brief Implementation of the Blender3D importer class.
  35. */
  36. //#define ASSIMP_BUILD_NO_COMPRESSED_BLEND
  37. // Uncomment this to disable support for (gzip)compressed .BLEND files
  38. #ifndef ASSIMP_BUILD_NO_BLEND_IMPORTER
  39. #include "BlenderBMesh.h"
  40. #include "BlenderCustomData.h"
  41. #include "BlenderIntermediate.h"
  42. #include "BlenderModifier.h"
  43. #include <assimp/StringUtils.h>
  44. #include <assimp/importerdesc.h>
  45. #include <assimp/scene.h>
  46. #include <assimp/MemoryIOWrapper.h>
  47. #include <assimp/StreamReader.h>
  48. #include <assimp/StringComparison.h>
  49. #include <cctype>
  50. #include <memory>
  51. #include <utility>
  52. // zlib is needed for compressed blend files
  53. #ifndef ASSIMP_BUILD_NO_COMPRESSED_BLEND
  54. #include "Common/Compression.h"
  55. #endif
  56. namespace Assimp {
  57. template <>
  58. const char *LogFunctions<BlenderImporter>::Prefix() {
  59. return "BLEND: ";
  60. }
  61. } // namespace Assimp
  62. using namespace Assimp;
  63. using namespace Assimp::Blender;
  64. using namespace Assimp::Formatter;
  65. static constexpr aiImporterDesc blenderDesc = {
  66. "Blender 3D Importer (http://www.blender3d.org)",
  67. "",
  68. "",
  69. "No animation support yet",
  70. aiImporterFlags_SupportBinaryFlavour,
  71. 0,
  72. 0,
  73. 2,
  74. 50,
  75. "blend"
  76. };
  77. // ------------------------------------------------------------------------------------------------
  78. // Constructor to be privately used by Importer
  79. BlenderImporter::BlenderImporter() :
  80. modifier_cache(new BlenderModifierShowcase()) {
  81. // empty
  82. }
  83. // ------------------------------------------------------------------------------------------------
  84. // Destructor, private as well
  85. BlenderImporter::~BlenderImporter() {
  86. delete modifier_cache;
  87. }
  88. static const char Token[] = "BLENDER";
  89. // ------------------------------------------------------------------------------------------------
  90. // Returns whether the class can handle the format of the given file.
  91. bool BlenderImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool /*checkSig*/) const {
  92. return ParseMagicToken(pFile, pIOHandler).error.empty();
  93. }
  94. // ------------------------------------------------------------------------------------------------
  95. // Loader registry entry
  96. const aiImporterDesc *BlenderImporter::GetInfo() const {
  97. return &blenderDesc;
  98. }
  99. // ------------------------------------------------------------------------------------------------
  100. // Setup configuration properties for the loader
  101. void BlenderImporter::SetupProperties(const Importer * /*pImp*/) {
  102. // nothing to be done for the moment
  103. }
  104. // ------------------------------------------------------------------------------------------------
  105. // Imports the given file into the given scene structure.
  106. void BlenderImporter::InternReadFile(const std::string &pFile,
  107. aiScene *pScene, IOSystem *pIOHandler) {
  108. FileDatabase file;
  109. StreamOrError streamOrError = ParseMagicToken(pFile, pIOHandler);
  110. if (!streamOrError.error.empty()) {
  111. ThrowException(streamOrError.error);
  112. }
  113. std::shared_ptr<IOStream> stream = std::move(streamOrError.stream);
  114. char version[4] = { 0 };
  115. file.i64bit = (stream->Read(version, 1, 1), version[0] == '-');
  116. file.little = (stream->Read(version, 1, 1), version[0] == 'v');
  117. stream->Read(version, 3, 1);
  118. version[3] = '\0';
  119. LogInfo("Blender version is ", version[0], ".", version + 1,
  120. " (64bit: ", file.i64bit ? "true" : "false",
  121. ", little endian: ", file.little ? "true" : "false", ")");
  122. ParseBlendFile(file, std::move(stream));
  123. Scene scene;
  124. ExtractScene(scene, file);
  125. ConvertBlendFile(pScene, scene, file);
  126. }
  127. // ------------------------------------------------------------------------------------------------
  128. void BlenderImporter::ParseBlendFile(FileDatabase &out, std::shared_ptr<IOStream> stream) {
  129. out.reader = std::make_shared<StreamReaderAny>(stream, out.little);
  130. DNAParser dna_reader(out);
  131. const DNA *dna = nullptr;
  132. out.entries.reserve(128);
  133. { // even small BLEND files tend to consist of many file blocks
  134. SectionParser parser(*out.reader, out.i64bit);
  135. // first parse the file in search for the DNA and insert all other sections into the database
  136. while ((parser.Next(), 1)) {
  137. const FileBlockHead &head = parser.GetCurrent();
  138. if (head.id == "ENDB") {
  139. break; // only valid end of the file
  140. } else if (head.id == "DNA1") {
  141. dna_reader.Parse();
  142. dna = &dna_reader.GetDNA();
  143. continue;
  144. }
  145. out.entries.push_back(head);
  146. }
  147. }
  148. if (!dna) {
  149. ThrowException("SDNA not found");
  150. }
  151. std::sort(out.entries.begin(), out.entries.end());
  152. }
  153. // ------------------------------------------------------------------------------------------------
  154. void BlenderImporter::ExtractScene(Scene &out, const FileDatabase &file) {
  155. const FileBlockHead *block = nullptr;
  156. std::map<std::string, size_t>::const_iterator it = file.dna.indices.find("Scene");
  157. if (it == file.dna.indices.end()) {
  158. ThrowException("There is no `Scene` structure record");
  159. }
  160. const Structure &ss = file.dna.structures[(*it).second];
  161. // we need a scene somewhere to start with.
  162. for (const FileBlockHead &bl : file.entries) {
  163. // Fix: using the DNA index is more reliable to locate scenes
  164. //if (bl.id == "SC") {
  165. if (bl.dna_index == (*it).second) {
  166. block = &bl;
  167. break;
  168. }
  169. }
  170. if (!block) {
  171. ThrowException("There is not a single `Scene` record to load");
  172. }
  173. file.reader->SetCurrentPos(block->start);
  174. ss.Convert(out, file);
  175. #ifndef ASSIMP_BUILD_BLENDER_NO_STATS
  176. ASSIMP_LOG_INFO(
  177. "(Stats) Fields read: ", file.stats().fields_read,
  178. ", pointers resolved: ", file.stats().pointers_resolved,
  179. ", cache hits: ", file.stats().cache_hits,
  180. ", cached objects: ", file.stats().cached_objects);
  181. #endif
  182. }
  183. // ------------------------------------------------------------------------------------------------
  184. void BlenderImporter::ParseSubCollection(const Blender::Scene &in, aiNode *root, const std::shared_ptr<Collection>& collection, ConversionData &conv_data) {
  185. std::deque<Object *> root_objects;
  186. // Count number of objects
  187. for (std::shared_ptr<CollectionObject> cur = std::static_pointer_cast<CollectionObject>(collection->gobject.first); cur; cur = cur->next) {
  188. if (cur->ob) {
  189. root_objects.push_back(cur->ob);
  190. }
  191. }
  192. std::deque<Collection *> root_children;
  193. // Count number of child nodes
  194. for (std::shared_ptr<CollectionChild> cur = std::static_pointer_cast<CollectionChild>(collection->children.first); cur; cur = cur->next) {
  195. if (cur->collection) {
  196. root_children.push_back(cur->collection.get());
  197. }
  198. }
  199. root->mNumChildren = static_cast<unsigned int>(root_objects.size() + root_children.size());
  200. root->mChildren = new aiNode *[root->mNumChildren]();
  201. for (unsigned int i = 0; i < static_cast<unsigned int>(root_objects.size()); ++i) {
  202. root->mChildren[i] = ConvertNode(in, root_objects[i], conv_data, aiMatrix4x4());
  203. root->mChildren[i]->mParent = root;
  204. }
  205. // For each subcollection create a new node to represent it
  206. unsigned int iterator = static_cast<unsigned int>(root_objects.size());
  207. for (std::shared_ptr<CollectionChild> cur = std::static_pointer_cast<CollectionChild>(collection->children.first); cur; cur = cur->next) {
  208. if (cur->collection) {
  209. root->mChildren[iterator] = new aiNode(cur->collection->id.name + 2); // skip over the name prefix 'OB'
  210. root->mChildren[iterator]->mParent = root;
  211. ParseSubCollection(in, root->mChildren[iterator], cur->collection, conv_data);
  212. }
  213. iterator += 1;
  214. }
  215. }
  216. // ------------------------------------------------------------------------------------------------
  217. void BlenderImporter::ConvertBlendFile(aiScene *out, const Scene &in, const FileDatabase &file) {
  218. ConversionData conv(file);
  219. aiNode *root = out->mRootNode = new aiNode("<BlenderRoot>");
  220. // Iterate over all objects directly under master_collection,
  221. // If in.master_collection == null, then we're parsing something older.
  222. if (in.master_collection) {
  223. ParseSubCollection(in, root, in.master_collection, conv);
  224. } else {
  225. std::deque<const Object *> no_parents;
  226. for (std::shared_ptr<Base> cur = std::static_pointer_cast<Base>(in.base.first); cur; cur = cur->next) {
  227. if (cur->object) {
  228. if (!cur->object->parent) {
  229. no_parents.push_back(cur->object.get());
  230. } else {
  231. conv.objects.insert(cur->object.get());
  232. }
  233. }
  234. }
  235. for (std::shared_ptr<Base> cur = in.basact; cur; cur = cur->next) {
  236. if (cur->object) {
  237. if (cur->object->parent) {
  238. conv.objects.insert(cur->object.get());
  239. }
  240. }
  241. }
  242. if (no_parents.empty()) {
  243. ThrowException("Expected at least one object with no parent");
  244. }
  245. root->mNumChildren = static_cast<unsigned int>(no_parents.size());
  246. root->mChildren = new aiNode *[root->mNumChildren]();
  247. for (unsigned int i = 0; i < root->mNumChildren; ++i) {
  248. root->mChildren[i] = ConvertNode(in, no_parents[i], conv, aiMatrix4x4());
  249. root->mChildren[i]->mParent = root;
  250. }
  251. }
  252. BuildMaterials(conv);
  253. if (conv.meshes->size()) {
  254. out->mMeshes = new aiMesh *[out->mNumMeshes = static_cast<unsigned int>(conv.meshes->size())];
  255. std::copy(conv.meshes->begin(), conv.meshes->end(), out->mMeshes);
  256. conv.meshes.dismiss();
  257. }
  258. if (conv.lights->size()) {
  259. out->mLights = new aiLight *[out->mNumLights = static_cast<unsigned int>(conv.lights->size())];
  260. std::copy(conv.lights->begin(), conv.lights->end(), out->mLights);
  261. conv.lights.dismiss();
  262. }
  263. if (conv.cameras->size()) {
  264. out->mCameras = new aiCamera *[out->mNumCameras = static_cast<unsigned int>(conv.cameras->size())];
  265. std::copy(conv.cameras->begin(), conv.cameras->end(), out->mCameras);
  266. conv.cameras.dismiss();
  267. }
  268. if (conv.materials->size()) {
  269. out->mMaterials = new aiMaterial *[out->mNumMaterials = static_cast<unsigned int>(conv.materials->size())];
  270. std::copy(conv.materials->begin(), conv.materials->end(), out->mMaterials);
  271. conv.materials.dismiss();
  272. }
  273. if (conv.textures->size()) {
  274. out->mTextures = new aiTexture *[out->mNumTextures = static_cast<unsigned int>(conv.textures->size())];
  275. std::copy(conv.textures->begin(), conv.textures->end(), out->mTextures);
  276. conv.textures.dismiss();
  277. }
  278. // acknowledge that the scene might come out incomplete
  279. // by Assimp's definition of `complete`: blender scenes
  280. // can consist of thousands of cameras or lights with
  281. // not a single mesh between them.
  282. if (!out->mNumMeshes) {
  283. out->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  284. }
  285. }
  286. // ------------------------------------------------------------------------------------------------
  287. void BlenderImporter::ResolveImage(aiMaterial *out, const Material *mat, const MTex *tex, const Image *img, ConversionData &conv_data) {
  288. (void)mat;
  289. (void)tex;
  290. (void)conv_data;
  291. aiString name;
  292. // check if the file contents are bundled with the BLEND file
  293. if (img->packedfile) {
  294. name.data[0] = '*';
  295. name.length = 1 + ASSIMP_itoa10(name.data + 1, static_cast<unsigned int>(AI_MAXLEN - 1), static_cast<int32_t>(conv_data.textures->size()));
  296. conv_data.textures->push_back(new aiTexture());
  297. aiTexture *curTex = conv_data.textures->back();
  298. // usually 'img->name' will be the original file name of the embedded textures,
  299. // so we can extract the file extension from it.
  300. const size_t nlen = strlen(img->name);
  301. const char *s = img->name + nlen, *e = s;
  302. while (s >= img->name && *s != '.') {
  303. --s;
  304. }
  305. curTex->achFormatHint[0] = s + 1 > e ? '\0' : (char)::tolower((unsigned char)s[1]);
  306. curTex->achFormatHint[1] = s + 2 > e ? '\0' : (char)::tolower((unsigned char)s[2]);
  307. curTex->achFormatHint[2] = s + 3 > e ? '\0' : (char)::tolower((unsigned char)s[3]);
  308. curTex->achFormatHint[3] = '\0';
  309. // tex->mHeight = 0;
  310. curTex->mWidth = img->packedfile->size;
  311. uint8_t *ch = new uint8_t[curTex->mWidth];
  312. conv_data.db.reader->SetCurrentPos(static_cast<size_t>(img->packedfile->data->val));
  313. conv_data.db.reader->CopyAndAdvance(ch, curTex->mWidth);
  314. curTex->pcData = reinterpret_cast<aiTexel *>(ch);
  315. LogInfo("Reading embedded texture, original file was ", img->name);
  316. } else {
  317. name = aiString(img->name);
  318. }
  319. aiTextureType texture_type = aiTextureType_UNKNOWN;
  320. MTex::MapType map_type = tex->mapto;
  321. if (map_type & MTex::MapType_COL)
  322. texture_type = aiTextureType_DIFFUSE;
  323. else if (map_type & MTex::MapType_NORM) {
  324. if (tex->tex->imaflag & Tex::ImageFlags_NORMALMAP) {
  325. texture_type = aiTextureType_NORMALS;
  326. } else {
  327. texture_type = aiTextureType_HEIGHT;
  328. }
  329. out->AddProperty(&tex->norfac, 1, AI_MATKEY_BUMPSCALING);
  330. } else if (map_type & MTex::MapType_COLSPEC)
  331. texture_type = aiTextureType_SPECULAR;
  332. else if (map_type & MTex::MapType_COLMIR)
  333. texture_type = aiTextureType_REFLECTION;
  334. //else if (map_type & MTex::MapType_REF)
  335. else if (map_type & MTex::MapType_SPEC)
  336. texture_type = aiTextureType_SHININESS;
  337. else if (map_type & MTex::MapType_EMIT)
  338. texture_type = aiTextureType_EMISSIVE;
  339. //else if (map_type & MTex::MapType_ALPHA)
  340. //else if (map_type & MTex::MapType_HAR)
  341. //else if (map_type & MTex::MapType_RAYMIRR)
  342. //else if (map_type & MTex::MapType_TRANSLU)
  343. else if (map_type & MTex::MapType_AMB)
  344. texture_type = aiTextureType_AMBIENT;
  345. else if (map_type & MTex::MapType_DISPLACE)
  346. texture_type = aiTextureType_DISPLACEMENT;
  347. //else if (map_type & MTex::MapType_WARP)
  348. out->AddProperty(&name, AI_MATKEY_TEXTURE(texture_type,
  349. conv_data.next_texture[texture_type]++));
  350. }
  351. // ------------------------------------------------------------------------------------------------
  352. void BlenderImporter::AddSentinelTexture(aiMaterial *out, const Material *mat, const MTex *tex, ConversionData &conv_data) {
  353. (void)mat;
  354. (void)tex;
  355. (void)conv_data;
  356. aiString name;
  357. name.length = ai_snprintf(name.data, AI_MAXLEN, "Procedural,num=%i,type=%s", conv_data.sentinel_cnt++,
  358. GetTextureTypeDisplayString(tex->tex->type));
  359. out->AddProperty(&name, AI_MATKEY_TEXTURE_DIFFUSE(
  360. conv_data.next_texture[aiTextureType_DIFFUSE]++));
  361. }
  362. // ------------------------------------------------------------------------------------------------
  363. void BlenderImporter::ResolveTexture(aiMaterial *out, const Material *mat, const MTex *tex, ConversionData &conv_data) {
  364. const Tex *rtex = tex->tex.get();
  365. if (!rtex || !rtex->type) {
  366. return;
  367. }
  368. // We can't support most of the texture types because they're mostly procedural.
  369. // These are substituted by a dummy texture.
  370. const char *dispnam = "";
  371. switch (rtex->type) {
  372. // these are listed in blender's UI
  373. case Tex::Type_CLOUDS:
  374. case Tex::Type_WOOD:
  375. case Tex::Type_MARBLE:
  376. case Tex::Type_MAGIC:
  377. case Tex::Type_BLEND:
  378. case Tex::Type_STUCCI:
  379. case Tex::Type_NOISE:
  380. case Tex::Type_PLUGIN:
  381. case Tex::Type_MUSGRAVE:
  382. case Tex::Type_VORONOI:
  383. case Tex::Type_DISTNOISE:
  384. case Tex::Type_ENVMAP:
  385. // these do no appear in the UI, why?
  386. case Tex::Type_POINTDENSITY:
  387. case Tex::Type_VOXELDATA:
  388. LogWarn("Encountered a texture with an unsupported type: ", dispnam);
  389. AddSentinelTexture(out, mat, tex, conv_data);
  390. break;
  391. case Tex::Type_IMAGE:
  392. if (!rtex->ima) {
  393. LogError("A texture claims to be an Image, but no image reference is given");
  394. break;
  395. }
  396. ResolveImage(out, mat, tex, rtex->ima.get(), conv_data);
  397. break;
  398. default:
  399. ai_assert(false);
  400. };
  401. }
  402. // ------------------------------------------------------------------------------------------------
  403. void BlenderImporter::BuildDefaultMaterial(Blender::ConversionData &conv_data) {
  404. // add a default material if necessary
  405. unsigned int index = static_cast<unsigned int>(-1);
  406. for (aiMesh *mesh : conv_data.meshes.get()) {
  407. if (mesh->mMaterialIndex == static_cast<unsigned int>(-1)) {
  408. if (index == static_cast<unsigned int>(-1)) {
  409. // Setup a default material.
  410. std::shared_ptr<Material> p(new Material());
  411. const size_t len = ::strlen(AI_DEFAULT_MATERIAL_NAME);
  412. ai_assert(len < sizeof(p->id.name) - 2);
  413. memcpy(p->id.name + 2, AI_DEFAULT_MATERIAL_NAME, len);
  414. // Note: MSVC11 does not zero-initialize Material here, although it should.
  415. // Thus all relevant fields should be explicitly initialized. We cannot add
  416. // a default constructor to Material since the DNA codegen does not support
  417. // parsing it.
  418. p->r = p->g = p->b = 0.6f;
  419. p->specr = p->specg = p->specb = 0.6f;
  420. p->ambr = p->ambg = p->ambb = 0.0f;
  421. p->mirr = p->mirg = p->mirb = 0.0f;
  422. p->emit = 0.f;
  423. p->alpha = 0.f;
  424. p->har = 0;
  425. index = static_cast<unsigned int>(conv_data.materials_raw.size());
  426. conv_data.materials_raw.push_back(p);
  427. LogInfo("Adding default material");
  428. }
  429. mesh->mMaterialIndex = index;
  430. }
  431. }
  432. }
  433. void BlenderImporter::AddBlendParams(aiMaterial *result, const Material *source) {
  434. aiColor3D diffuseColor(source->r, source->g, source->b);
  435. result->AddProperty(&diffuseColor, 1, "$mat.blend.diffuse.color", 0, 0);
  436. float diffuseIntensity = source->ref;
  437. result->AddProperty(&diffuseIntensity, 1, "$mat.blend.diffuse.intensity", 0, 0);
  438. int diffuseShader = source->diff_shader;
  439. result->AddProperty(&diffuseShader, 1, "$mat.blend.diffuse.shader", 0, 0);
  440. int diffuseRamp = 0;
  441. result->AddProperty(&diffuseRamp, 1, "$mat.blend.diffuse.ramp", 0, 0);
  442. aiColor3D specularColor(source->specr, source->specg, source->specb);
  443. result->AddProperty(&specularColor, 1, "$mat.blend.specular.color", 0, 0);
  444. float specularIntensity = source->spec;
  445. result->AddProperty(&specularIntensity, 1, "$mat.blend.specular.intensity", 0, 0);
  446. int specularShader = source->spec_shader;
  447. result->AddProperty(&specularShader, 1, "$mat.blend.specular.shader", 0, 0);
  448. int specularRamp = 0;
  449. result->AddProperty(&specularRamp, 1, "$mat.blend.specular.ramp", 0, 0);
  450. int specularHardness = source->har;
  451. result->AddProperty(&specularHardness, 1, "$mat.blend.specular.hardness", 0, 0);
  452. int transparencyUse = source->mode & MA_TRANSPARENCY ? 1 : 0;
  453. result->AddProperty(&transparencyUse, 1, "$mat.blend.transparency.use", 0, 0);
  454. int transparencyMethod = source->mode & MA_RAYTRANSP ? 2 : (source->mode & MA_ZTRANSP ? 1 : 0);
  455. result->AddProperty(&transparencyMethod, 1, "$mat.blend.transparency.method", 0, 0);
  456. float transparencyAlpha = source->alpha;
  457. result->AddProperty(&transparencyAlpha, 1, "$mat.blend.transparency.alpha", 0, 0);
  458. float transparencySpecular = source->spectra;
  459. result->AddProperty(&transparencySpecular, 1, "$mat.blend.transparency.specular", 0, 0);
  460. float transparencyFresnel = source->fresnel_tra;
  461. result->AddProperty(&transparencyFresnel, 1, "$mat.blend.transparency.fresnel", 0, 0);
  462. float transparencyBlend = source->fresnel_tra_i;
  463. result->AddProperty(&transparencyBlend, 1, "$mat.blend.transparency.blend", 0, 0);
  464. float transparencyIor = source->ang;
  465. result->AddProperty(&transparencyIor, 1, "$mat.blend.transparency.ior", 0, 0);
  466. float transparencyFilter = source->filter;
  467. result->AddProperty(&transparencyFilter, 1, "$mat.blend.transparency.filter", 0, 0);
  468. float transparencyFalloff = source->tx_falloff;
  469. result->AddProperty(&transparencyFalloff, 1, "$mat.blend.transparency.falloff", 0, 0);
  470. float transparencyLimit = source->tx_limit;
  471. result->AddProperty(&transparencyLimit, 1, "$mat.blend.transparency.limit", 0, 0);
  472. int transparencyDepth = source->ray_depth_tra;
  473. result->AddProperty(&transparencyDepth, 1, "$mat.blend.transparency.depth", 0, 0);
  474. float transparencyGlossAmount = source->gloss_tra;
  475. result->AddProperty(&transparencyGlossAmount, 1, "$mat.blend.transparency.glossAmount", 0, 0);
  476. float transparencyGlossThreshold = source->adapt_thresh_tra;
  477. result->AddProperty(&transparencyGlossThreshold, 1, "$mat.blend.transparency.glossThreshold", 0, 0);
  478. int transparencyGlossSamples = source->samp_gloss_tra;
  479. result->AddProperty(&transparencyGlossSamples, 1, "$mat.blend.transparency.glossSamples", 0, 0);
  480. int mirrorUse = source->mode & MA_RAYMIRROR ? 1 : 0;
  481. result->AddProperty(&mirrorUse, 1, "$mat.blend.mirror.use", 0, 0);
  482. float mirrorReflectivity = source->ray_mirror;
  483. result->AddProperty(&mirrorReflectivity, 1, "$mat.blend.mirror.reflectivity", 0, 0);
  484. aiColor3D mirrorColor(source->mirr, source->mirg, source->mirb);
  485. result->AddProperty(&mirrorColor, 1, "$mat.blend.mirror.color", 0, 0);
  486. float mirrorFresnel = source->fresnel_mir;
  487. result->AddProperty(&mirrorFresnel, 1, "$mat.blend.mirror.fresnel", 0, 0);
  488. float mirrorBlend = source->fresnel_mir_i;
  489. result->AddProperty(&mirrorBlend, 1, "$mat.blend.mirror.blend", 0, 0);
  490. int mirrorDepth = source->ray_depth;
  491. result->AddProperty(&mirrorDepth, 1, "$mat.blend.mirror.depth", 0, 0);
  492. float mirrorMaxDist = source->dist_mir;
  493. result->AddProperty(&mirrorMaxDist, 1, "$mat.blend.mirror.maxDist", 0, 0);
  494. int mirrorFadeTo = source->fadeto_mir;
  495. result->AddProperty(&mirrorFadeTo, 1, "$mat.blend.mirror.fadeTo", 0, 0);
  496. float mirrorGlossAmount = source->gloss_mir;
  497. result->AddProperty(&mirrorGlossAmount, 1, "$mat.blend.mirror.glossAmount", 0, 0);
  498. float mirrorGlossThreshold = source->adapt_thresh_mir;
  499. result->AddProperty(&mirrorGlossThreshold, 1, "$mat.blend.mirror.glossThreshold", 0, 0);
  500. int mirrorGlossSamples = source->samp_gloss_mir;
  501. result->AddProperty(&mirrorGlossSamples, 1, "$mat.blend.mirror.glossSamples", 0, 0);
  502. float mirrorGlossAnisotropic = source->aniso_gloss_mir;
  503. result->AddProperty(&mirrorGlossAnisotropic, 1, "$mat.blend.mirror.glossAnisotropic", 0, 0);
  504. }
  505. void BlenderImporter::BuildMaterials(ConversionData &conv_data) {
  506. conv_data.materials->reserve(conv_data.materials_raw.size());
  507. BuildDefaultMaterial(conv_data);
  508. for (const std::shared_ptr<Material> &mat : conv_data.materials_raw) {
  509. // reset per material global counters
  510. for (size_t i = 0; i < sizeof(conv_data.next_texture) / sizeof(conv_data.next_texture[0]); ++i) {
  511. conv_data.next_texture[i] = 0;
  512. }
  513. aiMaterial *mout = new aiMaterial();
  514. conv_data.materials->push_back(mout);
  515. // For any new material field handled here, the default material above must be updated with an appropriate default value.
  516. // set material name
  517. aiString name = aiString(mat->id.name + 2); // skip over the name prefix 'MA'
  518. mout->AddProperty(&name, AI_MATKEY_NAME);
  519. // basic material colors
  520. aiColor3D col(mat->r, mat->g, mat->b);
  521. if (mat->r || mat->g || mat->b) {
  522. // Usually, zero diffuse color means no diffuse color at all in the equation.
  523. // So we omit this member to express this intent.
  524. mout->AddProperty(&col, 1, AI_MATKEY_COLOR_DIFFUSE);
  525. if (mat->emit) {
  526. aiColor3D emit_col(mat->emit * mat->r, mat->emit * mat->g, mat->emit * mat->b);
  527. mout->AddProperty(&emit_col, 1, AI_MATKEY_COLOR_EMISSIVE);
  528. }
  529. }
  530. col = aiColor3D(mat->specr, mat->specg, mat->specb);
  531. mout->AddProperty(&col, 1, AI_MATKEY_COLOR_SPECULAR);
  532. // is hardness/shininess set?
  533. if (mat->har) {
  534. const float har = mat->har;
  535. mout->AddProperty(&har, 1, AI_MATKEY_SHININESS);
  536. }
  537. col = aiColor3D(mat->ambr, mat->ambg, mat->ambb);
  538. mout->AddProperty(&col, 1, AI_MATKEY_COLOR_AMBIENT);
  539. // is mirror enabled?
  540. if (mat->mode & MA_RAYMIRROR) {
  541. const float ray_mirror = mat->ray_mirror;
  542. mout->AddProperty(&ray_mirror, 1, AI_MATKEY_REFLECTIVITY);
  543. }
  544. col = aiColor3D(mat->mirr, mat->mirg, mat->mirb);
  545. mout->AddProperty(&col, 1, AI_MATKEY_COLOR_REFLECTIVE);
  546. for (size_t i = 0; i < sizeof(mat->mtex) / sizeof(mat->mtex[0]); ++i) {
  547. if (!mat->mtex[i]) {
  548. continue;
  549. }
  550. ResolveTexture(mout, mat.get(), mat->mtex[i].get(), conv_data);
  551. }
  552. AddBlendParams(mout, mat.get());
  553. }
  554. }
  555. // ------------------------------------------------------------------------------------------------
  556. void BlenderImporter::CheckActualType(const ElemBase *dt, const char *check) {
  557. ai_assert(dt);
  558. if (strcmp(dt->dna_type, check)) {
  559. ThrowException("Expected object at ", std::hex, dt, " to be of type `", check,
  560. "`, but it claims to be a `", dt->dna_type, "`instead");
  561. }
  562. }
  563. // ------------------------------------------------------------------------------------------------
  564. void BlenderImporter::NotSupportedObjectType(const Object *obj, const char *type) {
  565. LogWarn("Object `", obj->id.name, "` - type is unsupported: `", type, "`, skipping");
  566. }
  567. // ------------------------------------------------------------------------------------------------
  568. void BlenderImporter::ConvertMesh(const Scene & /*in*/, const Object * /*obj*/, const Mesh *mesh,
  569. ConversionData &conv_data, TempArray<std::vector, aiMesh> &temp) {
  570. // TODO: Resolve various problems with BMesh triangulation before re-enabling.
  571. // See issues #400, #373, #318 #315 and #132.
  572. #if defined(TODO_FIX_BMESH_CONVERSION)
  573. BlenderBMeshConverter BMeshConverter(mesh);
  574. if (BMeshConverter.ContainsBMesh()) {
  575. mesh = BMeshConverter.TriangulateBMesh();
  576. }
  577. #endif
  578. typedef std::pair<const int, size_t> MyPair;
  579. if ((!mesh->totface && !mesh->totloop) || !mesh->totvert) {
  580. return;
  581. }
  582. // some sanity checks
  583. if (static_cast<size_t>(mesh->totface) > mesh->mface.size()) {
  584. ThrowException("Number of faces is larger than the corresponding array");
  585. }
  586. if (static_cast<size_t>(mesh->totvert) > mesh->mvert.size()) {
  587. ThrowException("Number of vertices is larger than the corresponding array");
  588. }
  589. if (static_cast<size_t>(mesh->totloop) > mesh->mloop.size()) {
  590. ThrowException("Number of vertices is larger than the corresponding array");
  591. }
  592. // collect per-submesh numbers
  593. std::map<int, size_t> per_mat;
  594. std::map<int, size_t> per_mat_verts;
  595. for (int i = 0; i < mesh->totface; ++i) {
  596. const MFace &mf = mesh->mface[i];
  597. per_mat[mf.mat_nr]++;
  598. per_mat_verts[mf.mat_nr] += mf.v4 ? 4 : 3;
  599. }
  600. for (int i = 0; i < mesh->totpoly; ++i) {
  601. const MPoly &mp = mesh->mpoly[i];
  602. per_mat[mp.mat_nr]++;
  603. per_mat_verts[mp.mat_nr] += mp.totloop;
  604. }
  605. // ... and allocate the corresponding meshes
  606. const size_t old = temp->size();
  607. temp->reserve(temp->size() + per_mat.size());
  608. std::map<size_t, size_t> mat_num_to_mesh_idx;
  609. for (MyPair &it : per_mat) {
  610. mat_num_to_mesh_idx[it.first] = temp->size();
  611. temp->push_back(new aiMesh());
  612. aiMesh *out = temp->back();
  613. out->mVertices = new aiVector3D[per_mat_verts[it.first]];
  614. out->mNormals = new aiVector3D[per_mat_verts[it.first]];
  615. //out->mNumFaces = 0
  616. //out->mNumVertices = 0
  617. out->mFaces = new aiFace[it.second]();
  618. // all sub-meshes created from this mesh are named equally. this allows
  619. // curious users to recover the original adjacency.
  620. out->mName = aiString(mesh->id.name + 2);
  621. // skip over the name prefix 'ME'
  622. // resolve the material reference and add this material to the set of
  623. // output materials. The (temporary) material index is the index
  624. // of the material entry within the list of resolved materials.
  625. if (mesh->mat) {
  626. if (static_cast<size_t>(it.first) >= mesh->mat.size()) {
  627. ThrowException("Material index is out of range");
  628. }
  629. std::shared_ptr<Material> mat = mesh->mat[it.first];
  630. const std::deque<std::shared_ptr<Material>>::iterator has = std::find(
  631. conv_data.materials_raw.begin(),
  632. conv_data.materials_raw.end(), mat);
  633. if (has != conv_data.materials_raw.end()) {
  634. out->mMaterialIndex = static_cast<unsigned int>(std::distance(conv_data.materials_raw.begin(), has));
  635. } else {
  636. out->mMaterialIndex = static_cast<unsigned int>(conv_data.materials_raw.size());
  637. conv_data.materials_raw.push_back(mat);
  638. }
  639. } else
  640. out->mMaterialIndex = static_cast<unsigned int>(-1);
  641. }
  642. for (int i = 0; i < mesh->totface; ++i) {
  643. const MFace &mf = mesh->mface[i];
  644. aiMesh *const out = temp[mat_num_to_mesh_idx[mf.mat_nr]];
  645. aiFace &f = out->mFaces[out->mNumFaces++];
  646. f.mIndices = new unsigned int[f.mNumIndices = mf.v4 ? 4 : 3];
  647. aiVector3D *vo = out->mVertices + out->mNumVertices;
  648. aiVector3D *vn = out->mNormals + out->mNumVertices;
  649. // XXX we can't fold this easily, because we are restricted
  650. // to the member names from the BLEND file (v1,v2,v3,v4)
  651. // which are assigned by the genblenddna.py script and
  652. // cannot be changed without breaking the entire
  653. // import process.
  654. if (mf.v1 >= mesh->totvert) {
  655. ThrowException("Vertex index v1 out of range");
  656. }
  657. const MVert *v = &mesh->mvert[mf.v1];
  658. vo->x = v->co[0];
  659. vo->y = v->co[1];
  660. vo->z = v->co[2];
  661. vn->x = v->no[0];
  662. vn->y = v->no[1];
  663. vn->z = v->no[2];
  664. f.mIndices[0] = out->mNumVertices++;
  665. ++vo;
  666. ++vn;
  667. // if (f.mNumIndices >= 2) {
  668. if (mf.v2 >= mesh->totvert) {
  669. ThrowException("Vertex index v2 out of range");
  670. }
  671. v = &mesh->mvert[mf.v2];
  672. vo->x = v->co[0];
  673. vo->y = v->co[1];
  674. vo->z = v->co[2];
  675. vn->x = v->no[0];
  676. vn->y = v->no[1];
  677. vn->z = v->no[2];
  678. f.mIndices[1] = out->mNumVertices++;
  679. ++vo;
  680. ++vn;
  681. if (mf.v3 >= mesh->totvert) {
  682. ThrowException("Vertex index v3 out of range");
  683. }
  684. // if (f.mNumIndices >= 3) {
  685. v = &mesh->mvert[mf.v3];
  686. vo->x = v->co[0];
  687. vo->y = v->co[1];
  688. vo->z = v->co[2];
  689. vn->x = v->no[0];
  690. vn->y = v->no[1];
  691. vn->z = v->no[2];
  692. f.mIndices[2] = out->mNumVertices++;
  693. ++vo;
  694. ++vn;
  695. if (mf.v4 >= mesh->totvert) {
  696. ThrowException("Vertex index v4 out of range");
  697. }
  698. // if (f.mNumIndices >= 4) {
  699. if (mf.v4) {
  700. v = &mesh->mvert[mf.v4];
  701. vo->x = v->co[0];
  702. vo->y = v->co[1];
  703. vo->z = v->co[2];
  704. vn->x = v->no[0];
  705. vn->y = v->no[1];
  706. vn->z = v->no[2];
  707. f.mIndices[3] = out->mNumVertices++;
  708. ++vo;
  709. ++vn;
  710. out->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  711. } else
  712. out->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  713. // }
  714. // }
  715. // }
  716. }
  717. for (int i = 0; i < mesh->totpoly; ++i) {
  718. const MPoly &mf = mesh->mpoly[i];
  719. aiMesh *const out = temp[mat_num_to_mesh_idx[mf.mat_nr]];
  720. aiFace &f = out->mFaces[out->mNumFaces++];
  721. f.mIndices = new unsigned int[f.mNumIndices = mf.totloop];
  722. aiVector3D *vo = out->mVertices + out->mNumVertices;
  723. aiVector3D *vn = out->mNormals + out->mNumVertices;
  724. // XXX we can't fold this easily, because we are restricted
  725. // to the member names from the BLEND file (v1,v2,v3,v4)
  726. // which are assigned by the genblenddna.py script and
  727. // cannot be changed without breaking the entire
  728. // import process.
  729. for (int j = 0; j < mf.totloop; ++j) {
  730. const MLoop &loop = mesh->mloop[mf.loopstart + j];
  731. if (loop.v >= mesh->totvert) {
  732. ThrowException("Vertex index out of range");
  733. }
  734. const MVert &v = mesh->mvert[loop.v];
  735. vo->x = v.co[0];
  736. vo->y = v.co[1];
  737. vo->z = v.co[2];
  738. vn->x = v.no[0];
  739. vn->y = v.no[1];
  740. vn->z = v.no[2];
  741. f.mIndices[j] = out->mNumVertices++;
  742. ++vo;
  743. ++vn;
  744. }
  745. if (mf.totloop == 3) {
  746. out->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  747. } else {
  748. out->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  749. }
  750. }
  751. // TODO should we create the TextureUVMapping map in Convert<Material> to prevent redundant processing?
  752. // create texture <-> uvname mapping for all materials
  753. // key is texture number, value is data *
  754. typedef std::map<uint32_t, const MLoopUV *> TextureUVMapping;
  755. // key is material number, value is the TextureUVMapping for the material
  756. typedef std::map<uint32_t, TextureUVMapping> MaterialTextureUVMappings;
  757. MaterialTextureUVMappings matTexUvMappings;
  758. const uint32_t maxMat = static_cast<uint32_t>(mesh->mat.size());
  759. for (uint32_t m = 0; m < maxMat; ++m) {
  760. // get material by index
  761. const std::shared_ptr<Material> pMat = mesh->mat[m];
  762. TextureUVMapping texuv;
  763. const uint32_t maxTex = sizeof(pMat->mtex) / sizeof(pMat->mtex[0]);
  764. for (uint32_t t = 0; t < maxTex; ++t) {
  765. if (pMat->mtex[t] && pMat->mtex[t]->uvname[0]) {
  766. // get the CustomData layer for given uvname and correct type
  767. const ElemBase *pLoop = getCustomDataLayerData(mesh->ldata, CD_MLOOPUV, pMat->mtex[t]->uvname);
  768. if (pLoop) {
  769. texuv.insert(std::make_pair(t, dynamic_cast<const MLoopUV *>(pLoop)));
  770. }
  771. }
  772. }
  773. if (texuv.size()) {
  774. matTexUvMappings.insert(std::make_pair(m, texuv));
  775. }
  776. }
  777. // collect texture coordinates, they're stored in a separate per-face buffer
  778. if (mesh->mtface || mesh->mloopuv) {
  779. if (mesh->totface > static_cast<int>(mesh->mtface.size())) {
  780. ThrowException("Number of UV faces is larger than the corresponding UV face array (#1)");
  781. }
  782. for (std::vector<aiMesh *>::iterator it = temp->begin() + old; it != temp->end(); ++it) {
  783. ai_assert(0 != (*it)->mNumVertices);
  784. ai_assert(0 != (*it)->mNumFaces);
  785. const auto itMatTexUvMapping = matTexUvMappings.find((*it)->mMaterialIndex);
  786. if (itMatTexUvMapping == matTexUvMappings.end()) {
  787. // default behaviour like before
  788. (*it)->mTextureCoords[0] = new aiVector3D[(*it)->mNumVertices];
  789. } else {
  790. // create texture coords for every mapped tex
  791. for (uint32_t i = 0; i < itMatTexUvMapping->second.size(); ++i) {
  792. (*it)->mTextureCoords[i] = new aiVector3D[(*it)->mNumVertices];
  793. }
  794. }
  795. (*it)->mNumFaces = (*it)->mNumVertices = 0;
  796. }
  797. for (int i = 0; i < mesh->totface; ++i) {
  798. const MTFace *v = &mesh->mtface[i];
  799. aiMesh *const out = temp[mat_num_to_mesh_idx[mesh->mface[i].mat_nr]];
  800. const aiFace &f = out->mFaces[out->mNumFaces++];
  801. aiVector3D *vo = &out->mTextureCoords[0][out->mNumVertices];
  802. for (unsigned int j = 0; j < f.mNumIndices; ++j, ++vo, ++out->mNumVertices) {
  803. vo->x = v->uv[j][0];
  804. vo->y = v->uv[j][1];
  805. }
  806. }
  807. for (int i = 0; i < mesh->totpoly; ++i) {
  808. const MPoly &v = mesh->mpoly[i];
  809. aiMesh *const out = temp[mat_num_to_mesh_idx[v.mat_nr]];
  810. const aiFace &f = out->mFaces[out->mNumFaces++];
  811. const auto itMatTexUvMapping = matTexUvMappings.find(v.mat_nr);
  812. if (itMatTexUvMapping == matTexUvMappings.end()) {
  813. // old behavior
  814. aiVector3D *vo = &out->mTextureCoords[0][out->mNumVertices];
  815. for (unsigned int j = 0; j < f.mNumIndices; ++j, ++vo, ++out->mNumVertices) {
  816. const MLoopUV &uv = mesh->mloopuv[v.loopstart + j];
  817. vo->x = uv.uv[0];
  818. vo->y = uv.uv[1];
  819. }
  820. } else {
  821. // create textureCoords for every mapped tex
  822. for (uint32_t m = 0; m < itMatTexUvMapping->second.size(); ++m) {
  823. const MLoopUV *tm = itMatTexUvMapping->second[m];
  824. aiVector3D *vo = &out->mTextureCoords[m][out->mNumVertices];
  825. uint32_t j = 0;
  826. for (; j < f.mNumIndices; ++j, ++vo) {
  827. const MLoopUV &uv = tm[v.loopstart + j];
  828. vo->x = uv.uv[0];
  829. vo->y = uv.uv[1];
  830. }
  831. // only update written mNumVertices in last loop
  832. // TODO why must the numVertices be incremented here?
  833. if (m == itMatTexUvMapping->second.size() - 1) {
  834. out->mNumVertices += j;
  835. }
  836. }
  837. }
  838. }
  839. }
  840. // collect texture coordinates, old-style (marked as deprecated in current blender sources)
  841. if (mesh->tface) {
  842. if (mesh->totface > static_cast<int>(mesh->tface.size())) {
  843. ThrowException("Number of faces is larger than the corresponding UV face array (#2)");
  844. }
  845. for (std::vector<aiMesh *>::iterator it = temp->begin() + old; it != temp->end(); ++it) {
  846. ai_assert(0 != (*it)->mNumVertices);
  847. ai_assert(0 != (*it)->mNumFaces);
  848. (*it)->mTextureCoords[0] = new aiVector3D[(*it)->mNumVertices];
  849. (*it)->mNumFaces = (*it)->mNumVertices = 0;
  850. }
  851. for (int i = 0; i < mesh->totface; ++i) {
  852. const TFace *v = &mesh->tface[i];
  853. aiMesh *const out = temp[mat_num_to_mesh_idx[mesh->mface[i].mat_nr]];
  854. const aiFace &f = out->mFaces[out->mNumFaces++];
  855. aiVector3D *vo = &out->mTextureCoords[0][out->mNumVertices];
  856. for (unsigned int j = 0; j < f.mNumIndices; ++j, ++vo, ++out->mNumVertices) {
  857. vo->x = v->uv[j][0];
  858. vo->y = v->uv[j][1];
  859. }
  860. }
  861. }
  862. // collect vertex colors, stored separately as well
  863. if (mesh->mcol || mesh->mloopcol) {
  864. if (mesh->totface > static_cast<int>((mesh->mcol.size() / 4))) {
  865. ThrowException("Number of faces is larger than the corresponding color face array");
  866. }
  867. for (std::vector<aiMesh *>::iterator it = temp->begin() + old; it != temp->end(); ++it) {
  868. ai_assert(0 != (*it)->mNumVertices);
  869. ai_assert(0 != (*it)->mNumFaces);
  870. (*it)->mColors[0] = new aiColor4D[(*it)->mNumVertices];
  871. (*it)->mNumFaces = (*it)->mNumVertices = 0;
  872. }
  873. for (int i = 0; i < mesh->totface; ++i) {
  874. aiMesh *const out = temp[mat_num_to_mesh_idx[mesh->mface[i].mat_nr]];
  875. const aiFace &f = out->mFaces[out->mNumFaces++];
  876. aiColor4D *vo = &out->mColors[0][out->mNumVertices];
  877. for (unsigned int n = 0; n < f.mNumIndices; ++n, ++vo, ++out->mNumVertices) {
  878. const MCol *col = &mesh->mcol[(i << 2) + n];
  879. vo->r = col->r;
  880. vo->g = col->g;
  881. vo->b = col->b;
  882. vo->a = col->a;
  883. }
  884. for (unsigned int n = f.mNumIndices; n < 4; ++n)
  885. ;
  886. }
  887. for (int i = 0; i < mesh->totpoly; ++i) {
  888. const MPoly &v = mesh->mpoly[i];
  889. aiMesh *const out = temp[mat_num_to_mesh_idx[v.mat_nr]];
  890. const aiFace &f = out->mFaces[out->mNumFaces++];
  891. aiColor4D *vo = &out->mColors[0][out->mNumVertices];
  892. const ai_real scaleZeroToOne = 1.f / 255.f;
  893. for (unsigned int j = 0; j < f.mNumIndices; ++j, ++vo, ++out->mNumVertices) {
  894. const MLoopCol &col = mesh->mloopcol[v.loopstart + j];
  895. vo->r = ai_real(col.r) * scaleZeroToOne;
  896. vo->g = ai_real(col.g) * scaleZeroToOne;
  897. vo->b = ai_real(col.b) * scaleZeroToOne;
  898. vo->a = ai_real(col.a) * scaleZeroToOne;
  899. }
  900. }
  901. }
  902. return;
  903. }
  904. // ------------------------------------------------------------------------------------------------
  905. aiCamera *BlenderImporter::ConvertCamera(const Scene & /*in*/, const Object *obj, const Camera *cam, ConversionData & /*conv_data*/) {
  906. std::unique_ptr<aiCamera> out(new aiCamera());
  907. out->mName = obj->id.name + 2;
  908. out->mPosition = aiVector3D(0.f, 0.f, 0.f);
  909. out->mUp = aiVector3D(0.f, 1.f, 0.f);
  910. out->mLookAt = aiVector3D(0.f, 0.f, -1.f);
  911. if (cam->sensor_x && cam->lens) {
  912. out->mHorizontalFOV = 2.f * std::atan2(cam->sensor_x, 2.f * cam->lens);
  913. }
  914. out->mClipPlaneNear = cam->clipsta;
  915. out->mClipPlaneFar = cam->clipend;
  916. return out.release();
  917. }
  918. // ------------------------------------------------------------------------------------------------
  919. aiLight *BlenderImporter::ConvertLight(const Scene & /*in*/, const Object *obj, const Lamp *lamp, ConversionData & /*conv_data*/) {
  920. std::unique_ptr<aiLight> out(new aiLight());
  921. out->mName = obj->id.name + 2;
  922. switch (lamp->type) {
  923. case Lamp::Type_Local:
  924. out->mType = aiLightSource_POINT;
  925. break;
  926. case Lamp::Type_Spot:
  927. out->mType = aiLightSource_SPOT;
  928. // blender orients directional lights as facing toward -z
  929. out->mDirection = aiVector3D(0.f, 0.f, -1.f);
  930. out->mUp = aiVector3D(0.f, 1.f, 0.f);
  931. out->mAngleInnerCone = lamp->spotsize * (1.0f - lamp->spotblend);
  932. out->mAngleOuterCone = lamp->spotsize;
  933. break;
  934. case Lamp::Type_Sun:
  935. out->mType = aiLightSource_DIRECTIONAL;
  936. // blender orients directional lights as facing toward -z
  937. out->mDirection = aiVector3D(0.f, 0.f, -1.f);
  938. out->mUp = aiVector3D(0.f, 1.f, 0.f);
  939. break;
  940. case Lamp::Type_Area:
  941. out->mType = aiLightSource_AREA;
  942. if (lamp->area_shape == 0) {
  943. out->mSize = aiVector2D(lamp->area_size, lamp->area_size);
  944. } else {
  945. out->mSize = aiVector2D(lamp->area_size, lamp->area_sizey);
  946. }
  947. // blender orients directional lights as facing toward -z
  948. out->mDirection = aiVector3D(0.f, 0.f, -1.f);
  949. out->mUp = aiVector3D(0.f, 1.f, 0.f);
  950. break;
  951. default:
  952. break;
  953. }
  954. out->mColorAmbient = aiColor3D(lamp->r, lamp->g, lamp->b) * lamp->energy;
  955. out->mColorSpecular = aiColor3D(lamp->r, lamp->g, lamp->b) * lamp->energy;
  956. out->mColorDiffuse = aiColor3D(lamp->r, lamp->g, lamp->b) * lamp->energy;
  957. // If default values are supplied, compute the coefficients from light's max distance
  958. // Read this: https://imdoingitwrong.wordpress.com/2011/01/31/light-attenuation/
  959. //
  960. if (lamp->constant_coefficient == 1.0f && lamp->linear_coefficient == 0.0f && lamp->quadratic_coefficient == 0.0f && lamp->dist > 0.0f) {
  961. out->mAttenuationConstant = 1.0f;
  962. out->mAttenuationLinear = 2.0f / lamp->dist;
  963. out->mAttenuationQuadratic = 1.0f / (lamp->dist * lamp->dist);
  964. } else {
  965. out->mAttenuationConstant = lamp->constant_coefficient;
  966. out->mAttenuationLinear = lamp->linear_coefficient;
  967. out->mAttenuationQuadratic = lamp->quadratic_coefficient;
  968. }
  969. return out.release();
  970. }
  971. // ------------------------------------------------------------------------------------------------
  972. aiNode *BlenderImporter::ConvertNode(const Scene &in, const Object *obj, ConversionData &conv_data, const aiMatrix4x4 &parentTransform) {
  973. std::deque<const Object *> children;
  974. for (ObjectSet::iterator it = conv_data.objects.begin(); it != conv_data.objects.end();) {
  975. const Object *object = *it;
  976. if (object->parent == obj) {
  977. children.push_back(object);
  978. conv_data.objects.erase(it++);
  979. continue;
  980. }
  981. ++it;
  982. }
  983. std::unique_ptr<aiNode> node(new aiNode(obj->id.name + 2)); // skip over the name prefix 'OB'
  984. if (obj->data) {
  985. switch (obj->type) {
  986. case Object ::Type_EMPTY:
  987. break; // do nothing
  988. // supported object types
  989. case Object ::Type_MESH: {
  990. const size_t old = conv_data.meshes->size();
  991. CheckActualType(obj->data.get(), "Mesh");
  992. ConvertMesh(in, obj, static_cast<const Mesh *>(obj->data.get()), conv_data, conv_data.meshes);
  993. if (conv_data.meshes->size() > old) {
  994. node->mMeshes = new unsigned int[node->mNumMeshes = static_cast<unsigned int>(conv_data.meshes->size() - old)];
  995. for (unsigned int i = 0; i < node->mNumMeshes; ++i) {
  996. node->mMeshes[i] = static_cast<unsigned int>(i + old);
  997. }
  998. }
  999. } break;
  1000. case Object ::Type_LAMP: {
  1001. CheckActualType(obj->data.get(), "Lamp");
  1002. aiLight *mesh = ConvertLight(in, obj, static_cast<const Lamp *>(obj->data.get()), conv_data);
  1003. if (mesh) {
  1004. conv_data.lights->push_back(mesh);
  1005. }
  1006. } break;
  1007. case Object ::Type_CAMERA: {
  1008. CheckActualType(obj->data.get(), "Camera");
  1009. aiCamera *mesh = ConvertCamera(in, obj, static_cast<const Camera *>(obj->data.get()), conv_data);
  1010. if (mesh) {
  1011. conv_data.cameras->push_back(mesh);
  1012. }
  1013. } break;
  1014. // unsupported object types / log, but do not break
  1015. case Object ::Type_CURVE:
  1016. NotSupportedObjectType(obj, "Curve");
  1017. break;
  1018. case Object ::Type_SURF:
  1019. NotSupportedObjectType(obj, "Surface");
  1020. break;
  1021. case Object ::Type_FONT:
  1022. NotSupportedObjectType(obj, "Font");
  1023. break;
  1024. case Object ::Type_MBALL:
  1025. NotSupportedObjectType(obj, "MetaBall");
  1026. break;
  1027. case Object ::Type_WAVE:
  1028. NotSupportedObjectType(obj, "Wave");
  1029. break;
  1030. case Object ::Type_LATTICE:
  1031. NotSupportedObjectType(obj, "Lattice");
  1032. break;
  1033. // invalid or unknown type
  1034. default:
  1035. break;
  1036. }
  1037. }
  1038. for (unsigned int x = 0; x < 4; ++x) {
  1039. for (unsigned int y = 0; y < 4; ++y) {
  1040. node->mTransformation[y][x] = obj->obmat[x][y];
  1041. }
  1042. }
  1043. aiMatrix4x4 m = parentTransform;
  1044. m = m.Inverse();
  1045. node->mTransformation = m * node->mTransformation;
  1046. if (children.size()) {
  1047. node->mNumChildren = static_cast<unsigned int>(children.size());
  1048. aiNode **nd = node->mChildren = new aiNode *[node->mNumChildren]();
  1049. for (const Object *nobj : children) {
  1050. *nd = ConvertNode(in, nobj, conv_data, node->mTransformation * parentTransform);
  1051. (*nd++)->mParent = node.get();
  1052. }
  1053. }
  1054. // apply modifiers
  1055. modifier_cache->ApplyModifiers(*node, conv_data, in, *obj);
  1056. return node.release();
  1057. }
  1058. BlenderImporter::StreamOrError BlenderImporter::ParseMagicToken(const std::string &pFile, IOSystem *pIOHandler) const {
  1059. std::shared_ptr<IOStream> stream(pIOHandler->Open(pFile, "rb"));
  1060. if (stream == nullptr) {
  1061. return {{}, {}, "Could not open file for reading"};
  1062. }
  1063. char magic[8] = { 0 };
  1064. stream->Read(magic, 7, 1);
  1065. if (strcmp(magic, Token) == 0) {
  1066. return {stream, {}, {}};
  1067. }
  1068. // Check for presence of the gzip header. If yes, assume it is a
  1069. // compressed blend file and try uncompressing it, else fail. This is to
  1070. // avoid uncompressing random files which our loader might end up with.
  1071. #ifdef ASSIMP_BUILD_NO_COMPRESSED_BLEND
  1072. return {{}, {}, "BLENDER magic bytes are missing, is this file compressed (Assimp was built without decompression support)?"};
  1073. #else
  1074. if (magic[0] != 0x1f || static_cast<uint8_t>(magic[1]) != 0x8b) {
  1075. return {{}, {}, "BLENDER magic bytes are missing, couldn't find GZIP header either"};
  1076. }
  1077. LogDebug("Found no BLENDER magic word but a GZIP header, might be a compressed file");
  1078. if (magic[2] != 8) {
  1079. return {{}, {}, "Unsupported GZIP compression method"};
  1080. }
  1081. // http://www.gzip.org/zlib/rfc-gzip.html#header-trailer
  1082. stream->Seek(0L, aiOrigin_SET);
  1083. std::shared_ptr<StreamReaderLE> reader = std::shared_ptr<StreamReaderLE>(new StreamReaderLE(stream));
  1084. size_t total = 0;
  1085. Compression compression;
  1086. auto uncompressed = std::make_shared<std::vector<char>>();
  1087. if (compression.open(Compression::Format::Binary, Compression::FlushMode::NoFlush, 16 + Compression::MaxWBits)) {
  1088. total = compression.decompress((unsigned char *)reader->GetPtr(), reader->GetRemainingSize(), *uncompressed);
  1089. compression.close();
  1090. }
  1091. // replace the input stream with a memory stream
  1092. stream = std::make_shared<MemoryIOStream>(reinterpret_cast<uint8_t *>(uncompressed->data()), total);
  1093. // .. and retry
  1094. stream->Read(magic, 7, 1);
  1095. if (strcmp(magic, Token) == 0) {
  1096. return {stream, uncompressed, {}};
  1097. }
  1098. return {{}, {}, "Found no BLENDER magic word in decompressed GZIP file"};
  1099. #endif
  1100. }
  1101. #endif // ASSIMP_BUILD_NO_BLEND_IMPORTER