PbrtExporter.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2020, 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. /* TODO:
  34. Material improvements:
  35. - don't export embedded textures that we're not going to use
  36. - diffuse roughness
  37. - what is with the uv mapping, uv transform not coming through??
  38. - metal? glass? mirror? detect these better?
  39. - eta/k from RGB?
  40. - emissive textures: warn at least
  41. Other:
  42. - use aiProcess_GenUVCoords if needed to handle spherical/planar uv mapping?
  43. - don't build up a big string in memory but write directly to a file
  44. - aiProcess_Triangulate meshes to get triangles only?
  45. - animation (allow specifying a time)
  46. */
  47. #ifndef ASSIMP_BUILD_NO_EXPORT
  48. #ifndef ASSIMP_BUILD_NO_PBRT_EXPORTER
  49. #include "PbrtExporter.h"
  50. #include <assimp/version.h>
  51. #include <assimp/DefaultIOSystem.h>
  52. #include <assimp/IOSystem.hpp>
  53. #include <assimp/Exporter.hpp>
  54. #include <assimp/DefaultLogger.hpp>
  55. #include <assimp/StreamWriter.h>
  56. #include <assimp/Exceptional.h>
  57. #include <assimp/material.h>
  58. #include <assimp/scene.h>
  59. #include <assimp/mesh.h>
  60. #include <algorithm>
  61. #include <cctype>
  62. #include <cmath>
  63. #include <fstream>
  64. #include <functional>
  65. #include <iostream>
  66. #include <memory>
  67. #include <sstream>
  68. #include <string>
  69. #define STB_IMAGE_IMPLEMENTATION
  70. #include "stb_image.h"
  71. using namespace Assimp;
  72. namespace Assimp {
  73. void ExportScenePbrt (
  74. const char* pFile,
  75. IOSystem* pIOSystem,
  76. const aiScene* pScene,
  77. const ExportProperties* /*pProperties*/
  78. ){
  79. std::string path = DefaultIOSystem::absolutePath(std::string(pFile));
  80. std::string file = DefaultIOSystem::completeBaseName(std::string(pFile));
  81. // initialize the exporter
  82. PbrtExporter exporter(pScene, pIOSystem, path, file);
  83. }
  84. } // end of namespace Assimp
  85. // Constructor
  86. PbrtExporter::PbrtExporter (
  87. const aiScene* pScene, IOSystem* pIOSystem,
  88. const std::string path, const std::string file)
  89. : mScene(pScene),
  90. mIOSystem(pIOSystem),
  91. mPath(path),
  92. mFile(file)
  93. {
  94. // Export embedded textures.
  95. if (mScene->mNumTextures > 0)
  96. if (!mIOSystem->CreateDirectory("textures"))
  97. throw DeadlyExportError("Could not create textures/ directory.");
  98. for (unsigned int i = 0; i < mScene->mNumTextures; ++i) {
  99. aiTexture* tex = mScene->mTextures[i];
  100. std::string fn = CleanTextureFilename(tex->mFilename, false);
  101. std::cerr << "Writing embedded texture: " << tex->mFilename.C_Str() << " -> "
  102. << fn << "\n";
  103. std::unique_ptr<IOStream> outfile(mIOSystem->Open(fn, "wb"));
  104. if (!outfile) {
  105. throw DeadlyExportError("could not open output texture file: " + fn);
  106. }
  107. if (tex->mHeight == 0) {
  108. // It's binary data
  109. outfile->Write(tex->pcData, tex->mWidth, 1);
  110. } else {
  111. std::cerr << fn << ": TODO handle uncompressed embedded textures.\n";
  112. }
  113. }
  114. #if 0
  115. // Debugging: print the full node hierarchy
  116. std::function<void(aiNode*, int)> visitNode;
  117. visitNode = [&](aiNode* node, int depth) {
  118. for (int i = 0; i < depth; ++i) std::cerr << " ";
  119. std::cerr << node->mName.C_Str() << "\n";
  120. for (int i = 0; i < node->mNumChildren; ++i)
  121. visitNode(node->mChildren[i], depth + 1);
  122. };
  123. visitNode(mScene->mRootNode, 0);
  124. #endif
  125. mOutput.precision(ASSIMP_AI_REAL_TEXT_PRECISION);
  126. // Write everything out
  127. WriteMetaData();
  128. WriteCameras();
  129. WriteWorldDefinition();
  130. // And write the file to disk...
  131. std::unique_ptr<IOStream> outfile(mIOSystem->Open(mPath,"wt"));
  132. if (!outfile) {
  133. throw DeadlyExportError("could not open output .pbrt file: " + std::string(mFile));
  134. }
  135. outfile->Write(mOutput.str().c_str(), mOutput.str().length(), 1);
  136. }
  137. // Destructor
  138. PbrtExporter::~PbrtExporter() {
  139. // Empty
  140. }
  141. void PbrtExporter::WriteMetaData() {
  142. mOutput << "#############################\n";
  143. mOutput << "# Scene metadata:\n";
  144. aiMetadata* pMetaData = mScene->mMetaData;
  145. for (unsigned int i = 0; i < pMetaData->mNumProperties; i++) {
  146. mOutput << "# - ";
  147. mOutput << pMetaData->mKeys[i].C_Str() << " :";
  148. switch(pMetaData->mValues[i].mType) {
  149. case AI_BOOL : {
  150. mOutput << " ";
  151. if (*static_cast<bool*>(pMetaData->mValues[i].mData))
  152. mOutput << "TRUE\n";
  153. else
  154. mOutput << "FALSE\n";
  155. break;
  156. }
  157. case AI_INT32 : {
  158. mOutput << " " <<
  159. *static_cast<int32_t*>(pMetaData->mValues[i].mData) <<
  160. std::endl;
  161. break;
  162. }
  163. case AI_UINT64 :
  164. mOutput << " " <<
  165. *static_cast<uint64_t*>(pMetaData->mValues[i].mData) <<
  166. std::endl;
  167. break;
  168. case AI_FLOAT :
  169. mOutput << " " <<
  170. *static_cast<float*>(pMetaData->mValues[i].mData) <<
  171. std::endl;
  172. break;
  173. case AI_DOUBLE :
  174. mOutput << " " <<
  175. *static_cast<double*>(pMetaData->mValues[i].mData) <<
  176. std::endl;
  177. break;
  178. case AI_AISTRING : {
  179. aiString* value =
  180. static_cast<aiString*>(pMetaData->mValues[i].mData);
  181. std::string svalue = value->C_Str();
  182. std::size_t found = svalue.find_first_of("\n");
  183. mOutput << "\n";
  184. while (found != std::string::npos) {
  185. mOutput << "# " << svalue.substr(0, found) << "\n";
  186. svalue = svalue.substr(found + 1);
  187. found = svalue.find_first_of("\n");
  188. }
  189. mOutput << "# " << svalue << "\n";
  190. break;
  191. }
  192. case AI_AIVECTOR3D :
  193. // TODO
  194. mOutput << " Vector3D (unable to print)\n";
  195. break;
  196. default:
  197. // AI_META_MAX and FORCE_32BIT
  198. mOutput << " META_MAX or FORCE_32Bit (unable to print)\n";
  199. break;
  200. }
  201. }
  202. }
  203. void PbrtExporter::WriteCameras() {
  204. mOutput << "\n";
  205. mOutput << "###############################\n";
  206. mOutput << "# Cameras (" << mScene->mNumCameras << ") total\n\n";
  207. if (mScene->mNumCameras == 0) {
  208. std::cerr << "Warning: No cameras found in scene file.\n";
  209. return;
  210. }
  211. if (mScene->mNumCameras > 1) {
  212. std::cerr << "Multiple cameras found in scene file; defaulting to first one specified.\n";
  213. }
  214. for (unsigned int i = 0; i < mScene->mNumCameras; i++) {
  215. WriteCamera(i);
  216. }
  217. }
  218. aiMatrix4x4 PbrtExporter::GetNodeTransform(const aiString &name) const {
  219. aiMatrix4x4 m;
  220. auto node = mScene->mRootNode->FindNode(name);
  221. if (!node) {
  222. std::cerr << '"' << name.C_Str() << "\": node not found in scene tree.\n";
  223. throw DeadlyExportError("Could not find node");
  224. }
  225. else {
  226. while (node) {
  227. m = node->mTransformation * m;
  228. node = node->mParent;
  229. }
  230. }
  231. return m;
  232. }
  233. std::string PbrtExporter::TransformAsString(const aiMatrix4x4 &m) {
  234. // Transpose on the way out to match pbrt's expected layout (sanity
  235. // check: the translation component should be the last 3 entries
  236. // before a '1' as the final entry in the matrix, assuming it's
  237. // non-projective.)
  238. std::stringstream s;
  239. s << m.a1 << " " << m.b1 << " " << m.c1 << " " << m.d1 << " "
  240. << m.a2 << " " << m.b2 << " " << m.c2 << " " << m.d2 << " "
  241. << m.a3 << " " << m.b3 << " " << m.c3 << " " << m.d3 << " "
  242. << m.a4 << " " << m.b4 << " " << m.c4 << " " << m.d4;
  243. return s.str();
  244. }
  245. void PbrtExporter::WriteCamera(int i) {
  246. auto camera = mScene->mCameras[i];
  247. bool cameraActive = i == 0;
  248. mOutput << "# - Camera " << i+1 << ": "
  249. << camera->mName.C_Str() << "\n";
  250. // Get camera aspect ratio
  251. float aspect = camera->mAspect;
  252. if (aspect == 0) {
  253. aspect = 4.f/3.f;
  254. mOutput << "# - Aspect ratio : 1.33333 (no aspect found, defaulting to 4/3)\n";
  255. } else {
  256. mOutput << "# - Aspect ratio : " << aspect << "\n";
  257. }
  258. // Get Film xres and yres
  259. int xres = 1920;
  260. int yres = (int)round(xres/aspect);
  261. // Print Film for this camera
  262. if (!cameraActive)
  263. mOutput << "# ";
  264. mOutput << "Film \"rgb\" \"string filename\" \"" << mFile << ".exr\"\n";
  265. if (!cameraActive)
  266. mOutput << "# ";
  267. mOutput << " \"integer xresolution\" [" << xres << "]\n";
  268. if (!cameraActive)
  269. mOutput << "# ";
  270. mOutput << " \"integer yresolution\" [" << yres << "]\n";
  271. // Get camera fov
  272. float hfov = AI_RAD_TO_DEG(camera->mHorizontalFOV);
  273. float fov = (aspect >= 1.0) ? hfov : (hfov * aspect);
  274. if (fov < 5) {
  275. std::cerr << fov << ": suspiciously low field of view specified by camera. Setting to 45 degrees.\n";
  276. fov = 45;
  277. }
  278. // Get camera transform
  279. aiMatrix4x4 worldFromCamera = GetNodeTransform(camera->mName);
  280. // Print Camera LookAt
  281. auto position = worldFromCamera * camera->mPosition;
  282. auto lookAt = worldFromCamera * (camera->mPosition + camera->mLookAt);
  283. aiMatrix3x3 worldFromCamera3(worldFromCamera);
  284. auto up = worldFromCamera3 * camera->mUp;
  285. up.Normalize();
  286. if (!cameraActive)
  287. mOutput << "# ";
  288. mOutput << "Scale -1 1 1\n"; // right handed -> left handed
  289. if (!cameraActive)
  290. mOutput << "# ";
  291. mOutput << "LookAt "
  292. << position.x << " " << position.y << " " << position.z << "\n";
  293. if (!cameraActive)
  294. mOutput << "# ";
  295. mOutput << " "
  296. << lookAt.x << " " << lookAt.y << " " << lookAt.z << "\n";
  297. if (!cameraActive)
  298. mOutput << "# ";
  299. mOutput << " "
  300. << up.x << " " << up.y << " " << up.z << "\n";
  301. // Print camera descriptor
  302. if (!cameraActive)
  303. mOutput << "# ";
  304. mOutput << "Camera \"perspective\" \"float fov\" " << "[" << fov << "]\n\n";
  305. }
  306. void PbrtExporter::WriteWorldDefinition() {
  307. // Figure out which meshes are referenced multiple times; those will be
  308. // emitted as object instances and the rest will be emitted directly.
  309. std::map<int, int> meshUses;
  310. std::function<void(aiNode*)> visitNode;
  311. visitNode = [&](aiNode* node) {
  312. for (unsigned int i = 0; i < node->mNumMeshes; ++i)
  313. ++meshUses[node->mMeshes[i]];
  314. for (unsigned int i = 0; i < node->mNumChildren; ++i)
  315. visitNode(node->mChildren[i]);
  316. };
  317. visitNode(mScene->mRootNode);
  318. int nInstanced = 0, nUnused = 0;
  319. for (const auto &u : meshUses) {
  320. if (u.second == 0) ++nUnused;
  321. else if (u.second > 1) ++nInstanced;
  322. }
  323. std::cerr << nInstanced << " / " << mScene->mNumMeshes << " meshes instanced.\n";
  324. if (nUnused)
  325. std::cerr << nUnused << " meshes defined but not used in scene.\n";
  326. mOutput << "WorldBegin\n";
  327. WriteLights();
  328. WriteTextures();
  329. WriteMaterials();
  330. // Object instance definitions
  331. mOutput << "# Object instance definitions\n\n";
  332. for (const auto &mu : meshUses) {
  333. if (mu.second > 1) {
  334. WriteInstanceDefinition(mu.first);
  335. }
  336. }
  337. mOutput << "# Geometry\n\n";
  338. aiMatrix4x4 worldFromObject;
  339. WriteGeometricObjects(mScene->mRootNode, worldFromObject, meshUses);
  340. }
  341. void PbrtExporter::WriteTextures() {
  342. mOutput << "###################\n";
  343. mOutput << "# Textures\n\n";
  344. C_STRUCT aiString path;
  345. aiTextureMapping mapping;
  346. unsigned int uvIndex;
  347. ai_real blend;
  348. aiTextureOp op;
  349. aiTextureMapMode mapMode[3];
  350. // For every material in the scene,
  351. for (unsigned int m = 0 ; m < mScene->mNumMaterials; m++) {
  352. auto material = mScene->mMaterials[m];
  353. // Parse through all texture types,
  354. for (int tt = 1; tt <= aiTextureType_UNKNOWN; tt++) {
  355. int ttCount = material->GetTextureCount(aiTextureType(tt));
  356. // ... and get every texture
  357. for (int t = 0; t < ttCount; t++) {
  358. // TODO write out texture specifics
  359. // TODO UV transforms may be material specific
  360. // so those may need to be baked into unique tex name
  361. if (material->GetTexture(aiTextureType(tt), t, &path, &mapping,
  362. &uvIndex, &blend, &op, mapMode) != AI_SUCCESS) {
  363. std::cerr << "Error getting texture! " << m << " " << tt << " " << t << "\n";
  364. continue;
  365. }
  366. std::string filename = CleanTextureFilename(path);
  367. if (uvIndex != 0)
  368. std::cerr << "Warning: texture \"" << filename << "\" uses uv set #" <<
  369. uvIndex << " but the pbrt converter only exports uv set 0.\n";
  370. #if 0
  371. if (op != aiTextureOp_Multiply)
  372. std::cerr << "Warning: unexpected texture op " << (int)op <<
  373. " encountered for texture \"" <<
  374. filename << "\". The resulting scene may have issues...\n";
  375. if (blend != 1)
  376. std::cerr << "Blend value of " << blend << " found for texture \"" << filename
  377. << "\" but not handled in converter.\n";
  378. #endif
  379. std::string mappingString;
  380. #if 0
  381. if (mapMode[0] != mapMode[1])
  382. std::cerr << "Different texture boundary mode for u and v for texture \"" <<
  383. filename << "\". Using u for both.\n";
  384. switch (mapMode[0]) {
  385. case aiTextureMapMode_Wrap:
  386. // pbrt's default
  387. break;
  388. case aiTextureMapMode_Clamp:
  389. mappingString = "\"string wrap\" \"clamp\"";
  390. break;
  391. case aiTextureMapMode_Decal:
  392. std::cerr << "Decal texture boundary mode not supported by pbrt for texture \"" <<
  393. filename << "\"\n";
  394. break;
  395. case aiTextureMapMode_Mirror:
  396. std::cerr << "Mirror texture boundary mode not supported by pbrt for texture \"" <<
  397. filename << "\"\n";
  398. break;
  399. default:
  400. std::cerr << "Unexpected map mode " << (int)mapMode[0] << " for texture \"" <<
  401. filename << "\"\n";
  402. //throw DeadlyExportError("Unexpected aiTextureMapMode");
  403. }
  404. #endif
  405. #if 0
  406. aiUVTransform uvTransform;
  407. if (material->Get(AI_MATKEY_TEXTURE(tt, t), uvTransform) == AI_SUCCESS) {
  408. mOutput << "# UV transform " << uvTransform.mTranslation.x << " "
  409. << uvTransform.mTranslation.y << " " << uvTransform.mScaling.x << " "
  410. << uvTransform.mScaling.y << " " << uvTransform.mRotation << "\n";
  411. }
  412. #endif
  413. std::string texName, texType, texOptions;
  414. if (aiTextureType(tt) == aiTextureType_SHININESS ||
  415. aiTextureType(tt) == aiTextureType_OPACITY ||
  416. aiTextureType(tt) == aiTextureType_HEIGHT ||
  417. aiTextureType(tt) == aiTextureType_DISPLACEMENT ||
  418. aiTextureType(tt) == aiTextureType_METALNESS ||
  419. aiTextureType(tt) == aiTextureType_DIFFUSE_ROUGHNESS) {
  420. texType = "float";
  421. texName = std::string("float:") + RemoveSuffix(filename);
  422. if (aiTextureType(tt) == aiTextureType_SHININESS) {
  423. texOptions = " \"bool invert\" true\n";
  424. texName += "_Roughness";
  425. }
  426. } else if (aiTextureType(tt) == aiTextureType_DIFFUSE ||
  427. aiTextureType(tt) == aiTextureType_BASE_COLOR) {
  428. texType = "spectrum";
  429. texName = std::string("rgb:") + RemoveSuffix(filename);
  430. }
  431. // Don't export textures we're not actually going to use...
  432. if (texName.empty())
  433. continue;
  434. if (mTextureSet.find(texName) == mTextureSet.end()) {
  435. mOutput << "Texture \"" << texName << "\" \"" << texType << "\" \"imagemap\"\n"
  436. << texOptions
  437. << " \"string filename\" \"" << filename << "\" " << mappingString << '\n';
  438. mTextureSet.insert(texName);
  439. }
  440. // Also emit a float version for use with alpha testing...
  441. if ((aiTextureType(tt) == aiTextureType_DIFFUSE ||
  442. aiTextureType(tt) == aiTextureType_BASE_COLOR) &&
  443. TextureHasAlphaMask(filename)) {
  444. texType = "float";
  445. texName = std::string("alpha:") + filename;
  446. if (mTextureSet.find(texName) == mTextureSet.end()) {
  447. mOutput << "Texture \"" << texName << "\" \"" << texType << "\" \"imagemap\"\n"
  448. << " \"string filename\" \"" << filename << "\" " << mappingString << '\n';
  449. mTextureSet.insert(texName);
  450. }
  451. }
  452. }
  453. }
  454. }
  455. }
  456. bool PbrtExporter::TextureHasAlphaMask(const std::string &filename) {
  457. // TODO: STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp);
  458. // quick return if it's 3
  459. int xSize, ySize, nComponents;
  460. unsigned char *data = stbi_load(filename.c_str(), &xSize, &ySize, &nComponents, 0);
  461. if (!data) {
  462. std::cerr << filename << ": unable to load texture and check for alpha mask in texture. "
  463. "Geometry will not be alpha masked with this texture.\n";
  464. return false;
  465. }
  466. bool hasMask = false;
  467. switch (nComponents) {
  468. case 1:
  469. for (int i = 0; i < xSize * ySize; ++i)
  470. if (data[i] != 255) {
  471. hasMask = true;
  472. break;
  473. }
  474. break;
  475. case 2:
  476. for (int y = 0; y < ySize; ++y)
  477. for (int x = 0; x < xSize; ++x)
  478. if (data[2 * (x + y * xSize) + 1] != 255) {
  479. hasMask = true;
  480. break;
  481. }
  482. break;
  483. case 3:
  484. break;
  485. case 4:
  486. for (int y = 0; y < ySize; ++y)
  487. for (int x = 0; x < xSize; ++x)
  488. if (data[4 * (x + y * xSize) + 3] != 255) {
  489. hasMask = true;
  490. break;
  491. }
  492. break;
  493. default:
  494. std::cerr << filename << ": unexpected number of image channels, " <<
  495. nComponents << ".\n";
  496. }
  497. stbi_image_free(data);
  498. return hasMask;
  499. }
  500. void PbrtExporter::WriteMaterials() {
  501. mOutput << "\n";
  502. mOutput << "####################\n";
  503. mOutput << "# Materials (" << mScene->mNumMaterials << ") total\n\n";
  504. for (unsigned int i = 0; i < mScene->mNumMaterials; i++) {
  505. WriteMaterial(i);
  506. }
  507. mOutput << "\n\n";
  508. }
  509. void PbrtExporter::WriteMaterial(int m) {
  510. aiMaterial* material = mScene->mMaterials[m];
  511. // get material name
  512. auto materialName = material->GetName();
  513. mOutput << std::endl << "# - Material " << m+1 << ": " << materialName.C_Str() << "\n";
  514. // Print out number of properties
  515. mOutput << "# - Number of Material Properties: " << material->mNumProperties << "\n";
  516. // Print out texture type counts
  517. mOutput << "# - Non-Zero Texture Type Counts: ";
  518. for (int i = 1; i <= aiTextureType_UNKNOWN; i++) {
  519. int count = material->GetTextureCount(aiTextureType(i));
  520. if (count > 0)
  521. mOutput << TextureTypeToString(aiTextureType(i)) << ": " << count << " ";
  522. }
  523. mOutput << "\n";
  524. auto White = [](aiColor3D c) { return c.r == 1 && c.g == 1 && c.b == 1; };
  525. auto Black = [](aiColor3D c) { return c.r == 0 && c.g == 0 && c.b == 0; };
  526. aiColor3D diffuse, specular, transparency;
  527. bool constantDiffuse = (material->Get(AI_MATKEY_COLOR_DIFFUSE, diffuse) == AI_SUCCESS &&
  528. !White(diffuse));
  529. bool constantSpecular = (material->Get(AI_MATKEY_COLOR_SPECULAR, specular) == AI_SUCCESS &&
  530. !White(specular));
  531. bool constantTransparency = (material->Get(AI_MATKEY_COLOR_TRANSPARENT, transparency) == AI_SUCCESS &&
  532. !Black(transparency));
  533. float opacity, shininess, shininessStrength, eta;
  534. bool constantOpacity = (material->Get(AI_MATKEY_OPACITY, opacity) == AI_SUCCESS &&
  535. opacity != 0);
  536. bool constantShininess = material->Get(AI_MATKEY_SHININESS, shininess) == AI_SUCCESS;
  537. bool constantShininessStrength = material->Get(AI_MATKEY_SHININESS_STRENGTH, shininessStrength) == AI_SUCCESS;
  538. bool constantEta = (material->Get(AI_MATKEY_REFRACTI, eta) == AI_SUCCESS &&
  539. eta != 1);
  540. mOutput << "# - Constants: diffuse " << constantDiffuse << " specular " << constantSpecular <<
  541. " transprency " << constantTransparency << " opacity " << constantOpacity <<
  542. " shininess " << constantShininess << " shininess strength " << constantShininessStrength <<
  543. " eta " << constantEta << "\n";
  544. aiString roughnessMap;
  545. if (material->Get(AI_MATKEY_TEXTURE_SHININESS(0), roughnessMap) == AI_SUCCESS) {
  546. std::string roughnessTexture = std::string("float:") +
  547. RemoveSuffix(CleanTextureFilename(roughnessMap)) + "_Roughness";
  548. mOutput << "MakeNamedMaterial \"" << materialName.C_Str() << "\""
  549. << " \"string type\" \"coateddiffuse\"\n"
  550. << " \"texture roughness\" \"" << roughnessTexture << "\"\n";
  551. } else if (constantShininess) {
  552. // Assume plastic for now at least
  553. float roughness = std::max(0.f, 1.f - shininess);
  554. mOutput << "MakeNamedMaterial \"" << materialName.C_Str() << "\""
  555. << " \"string type\" \"coateddiffuse\"\n"
  556. << " \"float roughness\" " << roughness << "\n";
  557. } else
  558. // Diffuse
  559. mOutput << "MakeNamedMaterial \"" << materialName.C_Str() << "\""
  560. << " \"string type\" \"diffuse\"\n";
  561. aiString diffuseTexture;
  562. if (material->Get(AI_MATKEY_TEXTURE_DIFFUSE(0), diffuseTexture) == AI_SUCCESS)
  563. mOutput << " \"texture reflectance\" \"rgb:" << RemoveSuffix(CleanTextureFilename(diffuseTexture)) << "\"\n";
  564. else
  565. mOutput << " \"rgb reflectance\" [ " << diffuse.r << " " << diffuse.g <<
  566. " " << diffuse.b << " ]\n";
  567. aiString displacementTexture, normalMap;
  568. if (material->Get(AI_MATKEY_TEXTURE_NORMALS(0), displacementTexture) == AI_SUCCESS)
  569. mOutput << " \"string normalmap\" \"" << CleanTextureFilename(displacementTexture) << "\"\n";
  570. else if (material->Get(AI_MATKEY_TEXTURE_HEIGHT(0), displacementTexture) == AI_SUCCESS)
  571. mOutput << " \"texture displacement\" \"float:" <<
  572. RemoveSuffix(CleanTextureFilename(displacementTexture)) << "\"\n";
  573. else if (material->Get(AI_MATKEY_TEXTURE_DISPLACEMENT(0), displacementTexture) == AI_SUCCESS)
  574. mOutput << " \"texture displacement\" \"float:" <<
  575. RemoveSuffix(CleanTextureFilename(displacementTexture)) << "\"\n";
  576. }
  577. std::string PbrtExporter::CleanTextureFilename(const aiString &f, bool rewriteExtension) const {
  578. std::string fn = f.C_Str();
  579. // Remove directory name
  580. size_t offset = fn.find_last_of("/\\");
  581. if (offset != std::string::npos) {
  582. fn.erase(0, offset + 1);
  583. }
  584. // Expect all textures in textures
  585. fn = std::string("textures") + mIOSystem->getOsSeparator() + fn;
  586. // Rewrite extension for unsupported file formats.
  587. if (rewriteExtension) {
  588. offset = fn.rfind('.');
  589. if (offset != std::string::npos) {
  590. std::string extension = fn;
  591. extension.erase(0, offset + 1);
  592. std::transform(extension.begin(), extension.end(), extension.begin(),
  593. [](unsigned char c) { return (char)std::tolower(c); });
  594. if (extension != "tga" && extension != "exr" && extension != "png" &&
  595. extension != "pfm" && extension != "hdr") {
  596. std::string orig = fn;
  597. fn.erase(offset + 1);
  598. fn += "png";
  599. // Does it already exist? Warn if not.
  600. std::ifstream filestream(fn);
  601. if (!filestream.good())
  602. std::cerr << orig << ": must convert this texture to PNG.\n";
  603. }
  604. }
  605. }
  606. return fn;
  607. }
  608. std::string PbrtExporter::RemoveSuffix(std::string filename) {
  609. size_t offset = filename.rfind('.');
  610. if (offset != std::string::npos)
  611. filename.erase(offset);
  612. return filename;
  613. }
  614. void PbrtExporter::WriteLights() {
  615. mOutput << "\n";
  616. mOutput << "#################\n";
  617. mOutput << "# Lights\n\n";
  618. if (mScene->mNumLights == 0) {
  619. // Skip the default light if no cameras and this is flat up geometry
  620. if (mScene->mNumCameras > 0) {
  621. std::cerr << "No lights specified. Using default infinite light.\n";
  622. mOutput << "AttributeBegin\n";
  623. mOutput << " # default light\n";
  624. mOutput << " LightSource \"infinite\" \"blackbody L\" [6000 1]\n";
  625. mOutput << "AttributeEnd\n\n";
  626. }
  627. } else {
  628. for (unsigned int i = 0; i < mScene->mNumLights; ++i) {
  629. const aiLight *light = mScene->mLights[i];
  630. mOutput << "# Light " << light->mName.C_Str() << "\n";
  631. mOutput << "AttributeBegin\n";
  632. aiMatrix4x4 worldFromLight = GetNodeTransform(light->mName);
  633. mOutput << " Transform [ " << TransformAsString(worldFromLight) << " ]\n";
  634. aiColor3D color = light->mColorDiffuse + light->mColorSpecular;
  635. if (light->mAttenuationConstant != 0)
  636. color = color * (ai_real)(1. / light->mAttenuationConstant);
  637. switch (light->mType) {
  638. case aiLightSource_DIRECTIONAL: {
  639. mOutput << " LightSource \"distant\"\n";
  640. mOutput << " \"point3 from\" [ " << light->mPosition.x << " " <<
  641. light->mPosition.y << " " << light->mPosition.z << " ]\n";
  642. aiVector3D to = light->mPosition + light->mDirection;
  643. mOutput << " \"point3 to\" [ " << to.x << " " << to.y << " " << to.z << " ]\n";
  644. mOutput << " \"rgb L\" [ " << color.r << " " << color.g << " " << color.b << " ]\n";
  645. break;
  646. } case aiLightSource_POINT:
  647. mOutput << " LightSource \"distant\"\n";
  648. mOutput << " \"point3 from\" [ " << light->mPosition.x << " " <<
  649. light->mPosition.y << " " << light->mPosition.z << " ]\n";
  650. mOutput << " \"rgb L\" [ " << color.r << " " << color.g << " " << color.b << " ]\n";
  651. break;
  652. case aiLightSource_SPOT: {
  653. mOutput << " LightSource \"spot\"\n";
  654. mOutput << " \"point3 from\" [ " << light->mPosition.x << " " <<
  655. light->mPosition.y << " " << light->mPosition.z << " ]\n";
  656. aiVector3D to = light->mPosition + light->mDirection;
  657. mOutput << " \"point3 to\" [ " << to.x << " " << to.y << " " << to.z << " ]\n";
  658. mOutput << " \"rgb L\" [ " << color.r << " " << color.g << " " << color.b << " ]\n";
  659. mOutput << " \"float coneangle\" [ " << AI_RAD_TO_DEG(light->mAngleOuterCone) << " ]\n";
  660. mOutput << " \"float conedeltaangle\" [ " << AI_RAD_TO_DEG(light->mAngleOuterCone -
  661. light->mAngleInnerCone) << " ]\n";
  662. break;
  663. } case aiLightSource_AMBIENT:
  664. mOutput << "# ignored ambient light source\n";
  665. break;
  666. case aiLightSource_AREA: {
  667. aiVector3D left = light->mDirection ^ light->mUp;
  668. // rectangle. center at position, direction is normal vector
  669. float dLeft = light->mSize.x / 2, dUp = light->mSize.y / 2;
  670. aiVector3D vertices[4] = {
  671. light->mPosition - dLeft * left - dUp * light->mUp,
  672. light->mPosition + dLeft * left - dUp * light->mUp,
  673. light->mPosition - dLeft * left + dUp * light->mUp,
  674. light->mPosition + dLeft * left + dUp * light->mUp };
  675. mOutput << " AreaLightSource \"diffuse\"\n";
  676. mOutput << " \"rgb L\" [ " << color.r << " " << color.g << " " << color.b << " ]\n";
  677. mOutput << " Shape \"bilinearmesh\"\n";
  678. mOutput << " \"point3 p\" [ ";
  679. for (int j = 0; j < 4; ++j)
  680. mOutput << vertices[j].x << " " << vertices[j].y << " " << vertices[j].z;
  681. mOutput << " ]\n";
  682. mOutput << " \"integer indices\" [ 0 1 2 3 ]\n";
  683. break;
  684. } default:
  685. mOutput << "# ignored undefined light source type\n";
  686. break;
  687. }
  688. mOutput << "AttributeEnd\n\n";
  689. }
  690. }
  691. }
  692. void PbrtExporter::WriteMesh(aiMesh* mesh) {
  693. mOutput << "# - Mesh: ";
  694. if (mesh->mName == aiString(""))
  695. mOutput << "<No Name>\n";
  696. else
  697. mOutput << mesh->mName.C_Str() << "\n";
  698. mOutput << "AttributeBegin\n";
  699. aiMaterial* material = mScene->mMaterials[mesh->mMaterialIndex];
  700. mOutput << " NamedMaterial \"" << material->GetName().C_Str() << "\"\n";
  701. // Handle area lights
  702. aiColor3D emission;
  703. if (material->Get(AI_MATKEY_COLOR_EMISSIVE, emission) == AI_SUCCESS &&
  704. (emission.r > 0 || emission.g > 0 || emission.b > 0))
  705. mOutput << " AreaLightSource \"diffuse\" \"rgb L\" [ " << emission.r <<
  706. " " << emission.g << " " << emission.b << " ]\n";
  707. // Check if any types other than tri
  708. if ( (mesh->mPrimitiveTypes & aiPrimitiveType_POINT)
  709. || (mesh->mPrimitiveTypes & aiPrimitiveType_LINE)
  710. || (mesh->mPrimitiveTypes & aiPrimitiveType_POLYGON)) {
  711. std::cerr << "Error: ignoring point / line / polygon mesh " << mesh->mName.C_Str() << ".\n";
  712. return;
  713. }
  714. // Alpha mask
  715. std::string alpha;
  716. aiString opacityTexture;
  717. if (material->Get(AI_MATKEY_TEXTURE_OPACITY(0), opacityTexture) == AI_SUCCESS ||
  718. material->Get(AI_MATKEY_TEXTURE_DIFFUSE(0), opacityTexture) == AI_SUCCESS) {
  719. // material->Get(AI_MATKEY_TEXTURE_BASE_COLOR(0), opacityTexture) == AI_SUCCESS)
  720. std::string texName = std::string("alpha:") + CleanTextureFilename(opacityTexture);
  721. if (mTextureSet.find(texName) != mTextureSet.end())
  722. alpha = std::string(" \"texture alpha\" \"") + texName + "\"\n";
  723. } else {
  724. float opacity = 1;
  725. if (material->Get(AI_MATKEY_OPACITY, opacity) == AI_SUCCESS && opacity < 1)
  726. alpha = std::string(" \"float alpha\" [ ") + std::to_string(opacity) + " ]\n";
  727. }
  728. // Output the shape specification
  729. mOutput << "Shape \"trianglemesh\"\n" <<
  730. alpha <<
  731. " \"integer indices\" [";
  732. // Start with faces (which hold indices)
  733. for (unsigned int i = 0; i < mesh->mNumFaces; i++) {
  734. auto face = mesh->mFaces[i];
  735. if (face.mNumIndices != 3) throw DeadlyExportError("oh no not a tri!");
  736. for (unsigned int j = 0; j < face.mNumIndices; j++) {
  737. mOutput << face.mIndices[j] << " ";
  738. }
  739. if ((i % 7) == 6) mOutput << "\n ";
  740. }
  741. mOutput << "]\n";
  742. // Then go to vertices
  743. mOutput << " \"point3 P\" [";
  744. for (unsigned int i = 0; i < mesh->mNumVertices; i++) {
  745. auto vector = mesh->mVertices[i];
  746. mOutput << vector.x << " " << vector.y << " " << vector.z << " ";
  747. if ((i % 4) == 3) mOutput << "\n ";
  748. }
  749. mOutput << "]\n";
  750. // Normals (if present)
  751. if (mesh->mNormals) {
  752. mOutput << " \"normal N\" [";
  753. for (unsigned int i = 0; i < mesh->mNumVertices; i++) {
  754. auto normal = mesh->mNormals[i];
  755. mOutput << normal.x << " " << normal.y << " " << normal.z << " ";
  756. if ((i % 4) == 3) mOutput << "\n ";
  757. }
  758. mOutput << "]\n";
  759. }
  760. // Tangents (if present)
  761. if (mesh->mTangents) {
  762. mOutput << " \"vector3 S\" [";
  763. for (unsigned int i = 0; i < mesh->mNumVertices; i++) {
  764. auto tangent = mesh->mTangents[i];
  765. mOutput << tangent.x << " " << tangent.y << " " << tangent.z << " ";
  766. if ((i % 4) == 3) mOutput << "\n ";
  767. }
  768. mOutput << "]\n";
  769. }
  770. // Texture Coords (if present)
  771. // Find the first set of 2D texture coordinates..
  772. for (int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  773. if (mesh->mNumUVComponents[i] == 2) {
  774. // assert(mesh->mTextureCoords[i] != nullptr);
  775. aiVector3D* uv = mesh->mTextureCoords[i];
  776. mOutput << " \"point2 uv\" [";
  777. for (unsigned int j = 0; j < mesh->mNumVertices; ++j) {
  778. mOutput << uv[j].x << " " << uv[j].y << " ";
  779. if ((j % 6) == 5) mOutput << "\n ";
  780. }
  781. mOutput << "]\n";
  782. break;
  783. }
  784. }
  785. // TODO: issue warning if there are additional UV sets?
  786. mOutput << "AttributeEnd\n";
  787. }
  788. void PbrtExporter::WriteInstanceDefinition(int i) {
  789. aiMesh* mesh = mScene->mMeshes[i];
  790. mOutput << "ObjectBegin \"";
  791. if (mesh->mName == aiString(""))
  792. mOutput << "mesh_" << i+1 << "\"\n";
  793. else
  794. mOutput << mesh->mName.C_Str() << "_" << i+1 << "\"\n";
  795. WriteMesh(mesh);
  796. mOutput << "ObjectEnd\n";
  797. }
  798. void PbrtExporter::WriteGeometricObjects(aiNode* node, aiMatrix4x4 worldFromObject,
  799. std::map<int, int> &meshUses) {
  800. // Sometimes interior nodes have degenerate matrices??
  801. if (node->mTransformation.Determinant() != 0)
  802. worldFromObject = worldFromObject * node->mTransformation;
  803. if (node->mNumMeshes > 0) {
  804. mOutput << "AttributeBegin\n";
  805. mOutput << " Transform [ " << TransformAsString(worldFromObject) << "]\n";
  806. for (unsigned int i = 0; i < node->mNumMeshes; i++) {
  807. aiMesh* mesh = mScene->mMeshes[node->mMeshes[i]];
  808. if (meshUses[node->mMeshes[i]] == 1) {
  809. // If it's only used once in the scene, emit it directly as
  810. // a triangle mesh.
  811. mOutput << " # " << mesh->mName.C_Str();
  812. WriteMesh(mesh);
  813. } else {
  814. // If it's used multiple times, there will be an object
  815. // instance for it, so emit a reference to that.
  816. mOutput << " ObjectInstance \"";
  817. if (mesh->mName == aiString(""))
  818. mOutput << "mesh_" << node->mMeshes[i] + 1 << "\"\n";
  819. else
  820. mOutput << mesh->mName.C_Str() << "_" << node->mMeshes[i] + 1 << "\"\n";
  821. }
  822. }
  823. mOutput << "AttributeEnd\n\n";
  824. }
  825. // Recurse through children
  826. for (unsigned int i = 0; i < node->mNumChildren; i++) {
  827. WriteGeometricObjects(node->mChildren[i], worldFromObject, meshUses);
  828. }
  829. }
  830. #endif // ASSIMP_BUILD_NO_PBRT_EXPORTER
  831. #endif // ASSIMP_BUILD_NO_EXPORT