GltfImporterMaterial.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. // Copyright (C) 2009-present, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <AnKi/Importer/GltfImporter.h>
  6. #include <AnKi/Importer/ImageImporter.h>
  7. #include <AnKi/Resource/ImageLoader.h>
  8. #include <AnKi/Util/WeakArray.h>
  9. #include <AnKi/Util/Xml.h>
  10. #include <AnKi/Util/Filesystem.h>
  11. namespace anki {
  12. inline constexpr const Char* kMaterialTemplate = R"(<!-- This file is auto generated by ImporterMaterial.cpp -->
  13. <material shadows="%shadowEnabled%">
  14. <shaderProgram name="GBufferGeneric">
  15. <mutation>
  16. <mutator name="DIFFUSE_TEX" value="%diffTexMutator%"/>
  17. <mutator name="SPECULAR_TEX" value="%specTexMutator%"/>
  18. <mutator name="ROUGHNESS_METALNESS_TEX" value="%roughnessMetalnessTexMutator%"/>
  19. <mutator name="NORMAL_TEX" value="%normalTexMutator%"/>
  20. <mutator name="EMISSIVE_TEX" value="%emissiveTexMutator%"/>
  21. <mutator name="ALPHA_TEST" value="%alphaTestMutator%"/>
  22. </mutation>
  23. </shaderProgram>
  24. <inputs>
  25. %diff%
  26. %spec%
  27. %roughnessMetalness%
  28. %normal%
  29. %emission%
  30. %subsurface%
  31. </inputs>
  32. </material>
  33. )";
  34. static ImporterString getTextureUri(const cgltf_texture_view& view)
  35. {
  36. ANKI_ASSERT(view.texture);
  37. ANKI_ASSERT(view.texture->image);
  38. ANKI_ASSERT(view.texture->image->uri);
  39. ImporterString out = view.texture->image->uri;
  40. out.replaceAll("%20", " ");
  41. return out;
  42. }
  43. /// Read the texture and find out if it has constant color. If a component is not constant return -1
  44. static Error findConstantColorsInImage(CString fname, Vec4& constantColor)
  45. {
  46. ImageLoader iloader(&ImporterMemoryPool::getSingleton());
  47. ANKI_CHECK(iloader.load(fname));
  48. ANKI_ASSERT(iloader.getColorFormat() == ImageBinaryColorFormat::kRgba8);
  49. ANKI_ASSERT(iloader.getCompression() == ImageBinaryDataCompression::kRaw);
  50. const U8Vec4* data = reinterpret_cast<const U8Vec4*>(&iloader.getSurface(0, 0, 0).m_data[0]);
  51. ConstWeakArray<U8Vec4> pixels(data, iloader.getWidth() * iloader.getHeight());
  52. const F32 epsilon = 1.0f / 255.0f;
  53. for(U32 y = 0; y < iloader.getHeight(); ++y)
  54. {
  55. for(U32 x = 0; x < iloader.getWidth(); ++x)
  56. {
  57. const U8Vec4& pixel = pixels[y * iloader.getWidth() + x];
  58. const Vec4 pixelf = Vec4(pixel) / 255.0f;
  59. if(x == 0 && y == 0)
  60. {
  61. // Initialize
  62. constantColor = pixelf;
  63. }
  64. else
  65. {
  66. for(U32 i = 0; i < 4; ++i)
  67. {
  68. if(absolute(pixelf[i] - constantColor[i]) > epsilon)
  69. {
  70. constantColor[i] = -1.0f;
  71. }
  72. }
  73. }
  74. }
  75. }
  76. return Error::kNone;
  77. }
  78. static Error importImage(CString in, CString out, Bool alpha)
  79. {
  80. ImageImporterConfig config;
  81. Array<CString, 1> inputFnames = {in};
  82. config.m_inputFilenames = inputFnames;
  83. config.m_outFilename = out;
  84. config.m_compressions = ImageBinaryDataCompression::kS3tc | ImageBinaryDataCompression::kAstc;
  85. config.m_minMipmapDimension = 8;
  86. config.m_noAlpha = !alpha;
  87. String tmp;
  88. if(getTempDirectory(tmp))
  89. {
  90. ANKI_IMPORTER_LOGE("getTempDirectory() failed");
  91. return 1;
  92. }
  93. config.m_tempDirectory = tmp;
  94. #if ANKI_OS_WINDOWS
  95. config.m_compressonatorFilename = ANKI_SOURCE_DIRECTORY "/ThirdParty/Bin/Windows64/Compressonator/compressonatorcli.exe";
  96. config.m_astcencFilename = ANKI_SOURCE_DIRECTORY "/ThirdParty/Bin/Windows64/astcenc-avx2.exe";
  97. #elif ANKI_OS_LINUX
  98. config.m_compressonatorFilename = ANKI_SOURCE_DIRECTORY "/ThirdParty/Bin/Linux64/Compressonator/compressonatorcli";
  99. config.m_astcencFilename = ANKI_SOURCE_DIRECTORY "/ThirdParty/Bin/Linux64/astcenc-avx2";
  100. #else
  101. # error "Unupported"
  102. #endif
  103. config.m_flipImage = false;
  104. ANKI_IMPORTER_LOGV("Importing image \"%s\" as \"%s\"", in.cstr(), out.cstr());
  105. ANKI_CHECK(importImage(config));
  106. return Error::kNone;
  107. }
  108. static void fixImageUri(ImporterString& uri)
  109. {
  110. uri.replaceAll(".tga", ".ankitex");
  111. uri.replaceAll(".png", ".ankitex");
  112. uri.replaceAll(".jpg", ".ankitex");
  113. uri.replaceAll(".jpeg", ".ankitex");
  114. }
  115. Error GltfImporter::writeMaterial(const cgltf_material& mtl, Bool writeRayTracing) const
  116. {
  117. const Error err = writeMaterialInternal(mtl, writeRayTracing);
  118. if(err)
  119. {
  120. ANKI_IMPORTER_LOGE("Failed to import material: %s", mtl.name);
  121. }
  122. return err;
  123. }
  124. Error GltfImporter::writeMaterialInternal(const cgltf_material& mtl, Bool writeRayTracing) const
  125. {
  126. if(!writeRayTracing)
  127. {
  128. ANKI_IMPORTER_LOGW("Skipping ray tracing is ignored");
  129. }
  130. ImporterString fname;
  131. fname.sprintf("%s%s", m_outDir.cstr(), computeMaterialResourceFilename(mtl).cstr());
  132. ANKI_IMPORTER_LOGV("Importing material %s", fname.cstr());
  133. if(!mtl.has_pbr_metallic_roughness)
  134. {
  135. ANKI_IMPORTER_LOGE("Expecting PBR metallic roughness");
  136. return Error::kUserData;
  137. }
  138. ImporterHashMap<CString, ImporterString> extras;
  139. ANKI_CHECK(appendExtras(mtl.extras, extras));
  140. ImporterString xml;
  141. xml += XmlDocument<MemoryPoolPtrWrapper<BaseMemoryPool>>::kXmlHeader;
  142. xml += "\n";
  143. xml += kMaterialTemplate;
  144. // Diffuse
  145. if(mtl.pbr_metallic_roughness.base_color_texture.texture)
  146. {
  147. const ImporterString fname = getTextureUri(mtl.pbr_metallic_roughness.base_color_texture);
  148. ImporterString uri;
  149. uri.sprintf("%s%s", m_texrpath.cstr(), fname.cstr());
  150. const F32* diffCol = &mtl.pbr_metallic_roughness.base_color_factor[0];
  151. xml.replaceAll("%diff%", ImporterString().sprintf("<input name=\"m_diffuseTex\" value=\"%s\"/>\n"
  152. "\t\t<input name=\"m_diffuseScale\" value=\"%f %f %f %f\"/>",
  153. uri.cstr(), diffCol[0], diffCol[1], diffCol[2], diffCol[3]));
  154. xml.replaceAll("%diffTexMutator%", "1");
  155. Vec4 constantColor;
  156. ANKI_CHECK(findConstantColorsInImage(fname, constantColor));
  157. const Bool constantAlpha = constantColor.w >= 0.0f;
  158. xml.replaceAll("%alphaTestMutator%", (constantAlpha) ? "0" : "1");
  159. if(m_importTextures)
  160. {
  161. ImporterString out = m_outDir;
  162. out += fname;
  163. fixImageUri(out);
  164. ANKI_CHECK(importImage(fname, out, !constantAlpha));
  165. }
  166. }
  167. else
  168. {
  169. const F32* diffCol = &mtl.pbr_metallic_roughness.base_color_factor[0];
  170. xml.replaceAll("%diff%", ImporterString().sprintf("<input name=\"m_diffuseScale\" value=\"%f %f %f %f\"/>", diffCol[0], diffCol[1],
  171. diffCol[2], diffCol[3]));
  172. xml.replaceAll("%diffTexMutator%", "0");
  173. xml.replaceAll("%alphaTestMutator%", "0");
  174. }
  175. // Specular color (freshnel)
  176. {
  177. Vec3 specular;
  178. auto it = extras.find("specular");
  179. if(it != extras.getEnd())
  180. {
  181. ImporterStringList tokens;
  182. tokens.splitString(it->toCString(), ' ');
  183. if(tokens.getSize() != 3)
  184. {
  185. ANKI_IMPORTER_LOGE("Wrong specular: %s", it->cstr());
  186. return Error::kUserData;
  187. }
  188. auto token = tokens.getBegin();
  189. ANKI_CHECK(token->toNumber(specular.x));
  190. ++token;
  191. ANKI_CHECK(token->toNumber(specular.y));
  192. ++token;
  193. ANKI_CHECK(token->toNumber(specular.z));
  194. }
  195. else
  196. {
  197. specular = Vec3(0.04f);
  198. }
  199. xml.replaceAll("%spec%",
  200. ImporterString().sprintf("<input name=\"m_specularScale\" value=\"%f %f %f\"/>", specular.x, specular.y, specular.z));
  201. xml.replaceAll("%specTexMutator%", "0");
  202. }
  203. // Shadow
  204. {
  205. Bool shadow = true;
  206. auto it = extras.find("shadow");
  207. if(it != extras.getEnd())
  208. {
  209. const ImporterString val = *it;
  210. if(val == "false" || val == "0")
  211. {
  212. shadow = false;
  213. }
  214. else if(val == "true" || val == "1")
  215. {
  216. shadow = true;
  217. }
  218. else
  219. {
  220. ANKI_IMPORTER_LOGE("Wrong value for extra named shadow: %s", val.cstr());
  221. return Error::kUserData;
  222. }
  223. }
  224. xml.replaceAll("%shadowEnabled%", (shadow) ? "1" : "0");
  225. }
  226. // Identify metallic/roughness texture
  227. F32 constantMetaliness = -1.0f, constantRoughness = -1.0f;
  228. if(mtl.pbr_metallic_roughness.metallic_roughness_texture.texture)
  229. {
  230. const ImporterString fname = getTextureUri(mtl.pbr_metallic_roughness.metallic_roughness_texture);
  231. Vec4 constantColor;
  232. ANKI_CHECK(findConstantColorsInImage(fname, constantColor));
  233. constantRoughness = constantColor.y;
  234. constantMetaliness = constantColor.z;
  235. }
  236. // Roughness/metallic
  237. if(mtl.pbr_metallic_roughness.metallic_roughness_texture.texture && (constantRoughness < 0.0f || constantMetaliness < 0.0f))
  238. {
  239. ImporterString uri;
  240. uri.sprintf("%s%s", m_texrpath.cstr(), getTextureUri(mtl.pbr_metallic_roughness.metallic_roughness_texture).cstr());
  241. xml.replaceAll("%roughnessMetalness%",
  242. ImporterString().sprintf("<input name=\"m_roughnessMetalnessTex\" value=\"%s\"/>\n"
  243. "\t\t<input name=\"m_roughnessScale\" value=\"%f\"/>\n"
  244. "\t\t<input name=\"m_metalnessScale\" value=\"%f\"/>",
  245. uri.cstr(), mtl.pbr_metallic_roughness.roughness_factor, mtl.pbr_metallic_roughness.metallic_factor));
  246. xml.replaceAll("%roughnessMetalnessTexMutator%", "1");
  247. if(m_importTextures)
  248. {
  249. const ImporterString in = getTextureUri(mtl.pbr_metallic_roughness.metallic_roughness_texture);
  250. ImporterString out = m_outDir;
  251. out += in;
  252. fixImageUri(out);
  253. ANKI_CHECK(importImage(in, out, false));
  254. }
  255. }
  256. else
  257. {
  258. // No texture or both roughness and metalness are constant
  259. const F32 roughness = (constantRoughness >= 0.0f) ? constantRoughness * mtl.pbr_metallic_roughness.roughness_factor
  260. : mtl.pbr_metallic_roughness.roughness_factor;
  261. const F32 metalness = (constantMetaliness >= 0.0f) ? constantMetaliness * mtl.pbr_metallic_roughness.metallic_factor
  262. : mtl.pbr_metallic_roughness.metallic_factor;
  263. xml.replaceAll("%roughnessMetalness%", ImporterString().sprintf("<input name=\"m_roughnessScale\" value=\"%f\"/>\n"
  264. "\t\t<input name=\"m_metalnessScale\" value=\"%f\"/>",
  265. roughness, metalness));
  266. xml.replaceAll("%roughnessMetalnessTexMutator%", "0");
  267. }
  268. // Normal texture
  269. if(mtl.normal_texture.texture)
  270. {
  271. Vec4 constantColor;
  272. ANKI_CHECK(findConstantColorsInImage(getTextureUri(mtl.normal_texture).cstr(), constantColor));
  273. if(constantColor.xyz == -1.0f)
  274. {
  275. ImporterString uri;
  276. uri.sprintf("%s%s", m_texrpath.cstr(), getTextureUri(mtl.normal_texture).cstr());
  277. xml.replaceAll("%normal%", ImporterString().sprintf("<input name=\"m_normalTex\" value=\"%s\"/>", uri.cstr()));
  278. xml.replaceAll("%normalTexMutator%", "1");
  279. if(m_importTextures)
  280. {
  281. const ImporterString in = getTextureUri(mtl.normal_texture);
  282. ImporterString out = m_outDir;
  283. out += in;
  284. fixImageUri(out);
  285. ANKI_CHECK(importImage(in, out, false));
  286. }
  287. }
  288. else
  289. {
  290. xml.replaceAll("%normal%", "");
  291. xml.replaceAll("%normalTexMutator%", "0");
  292. }
  293. }
  294. else
  295. {
  296. xml.replaceAll("%normal%", "");
  297. xml.replaceAll("%normalTexMutator%", "0");
  298. }
  299. // Emissive texture
  300. if(mtl.emissive_texture.texture)
  301. {
  302. ImporterString uri;
  303. uri.sprintf("%s%s", m_texrpath.cstr(), getTextureUri(mtl.emissive_texture).cstr());
  304. xml.replaceAll("%emission%", ImporterString().sprintf("<input name=\"m_emissiveTex\" value=\"%s\"/>\n"
  305. "\t\t<input name=\"m_emissionScale\" value=\"%f %f %f\"/>",
  306. uri.cstr(), mtl.emissive_strength.emissive_strength,
  307. mtl.emissive_strength.emissive_strength, mtl.emissive_strength.emissive_strength));
  308. xml.replaceAll("%emissiveTexMutator%", "1");
  309. if(m_importTextures)
  310. {
  311. const ImporterString in = getTextureUri(mtl.emissive_texture);
  312. ImporterString out = m_outDir;
  313. out += in;
  314. fixImageUri(out);
  315. ANKI_CHECK(importImage(in, out, false));
  316. }
  317. }
  318. else
  319. {
  320. xml.replaceAll("%emission%", ImporterString().sprintf("<input name=\"m_emissionScale\" value=\"%f %f %f\"/>",
  321. mtl.emissive_factor[0] * mtl.emissive_strength.emissive_strength,
  322. mtl.emissive_factor[1] * mtl.emissive_strength.emissive_strength,
  323. mtl.emissive_factor[2] * mtl.emissive_strength.emissive_strength));
  324. xml.replaceAll("%emissiveTexMutator%", "0");
  325. }
  326. // Subsurface
  327. {
  328. F32 subsurface;
  329. auto it = extras.find("subsurface");
  330. if(it != extras.getEnd())
  331. {
  332. ANKI_CHECK(it->toNumber(subsurface));
  333. }
  334. else
  335. {
  336. subsurface = 0.0f;
  337. }
  338. xml.replaceAll("%subsurface%", ImporterString().sprintf("<input name=\"m_subsurface\" value=\"%f\"/>", subsurface));
  339. }
  340. // Replace texture extensions with .anki
  341. fixImageUri(xml);
  342. // Write file
  343. File file;
  344. ANKI_CHECK(file.open(fname.toCString(), FileOpenFlag::kWrite));
  345. ANKI_CHECK(file.writeText(xml));
  346. return Error::kNone;
  347. }
  348. } // end namespace anki