SceneBuilder.Materials.cs 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using BabylonExport.Entities;
  7. using UnityEditor;
  8. using UnityEngine;
  9. namespace Unity3D2Babylon
  10. {
  11. partial class SceneBuilder
  12. {
  13. private void CopyTextureCube(string texturePath, Cubemap cubemap, BabylonTexture babylonTexture, bool hdr = false)
  14. {
  15. if (!babylonScene.AddTextureCube(texturePath))
  16. {
  17. return;
  18. }
  19. ExporterWindow.ReportProgress(1, "Parsing texture cube: " + texturePath);
  20. var srcTexturePath = AssetDatabase.GetAssetPath(cubemap);
  21. bool textureNotExistsMode = (SceneController != null && SceneController.skyboxOptions.textureFile == BabylonTextureExport.IfNotExists);
  22. bool png = (exportationOptions.DefaultImageFormat == (int)BabylonImageFormat.PNG);
  23. string fext = (png == true) ? ".png" : ".jpg";
  24. try
  25. {
  26. if (hdr)
  27. {
  28. var hdrTexturePath = Path.Combine(babylonScene.OutputPath, Path.GetFileName(texturePath));
  29. bool writeHdrTexture = true;
  30. string textureHdrName = Path.GetFileName(hdrTexturePath);
  31. if (textureNotExistsMode && File.Exists(hdrTexturePath))
  32. {
  33. writeHdrTexture = false;
  34. ExporterWindow.ReportProgress(1, "Texture hdr cube item exists: " + textureHdrName);
  35. }
  36. if (writeHdrTexture)
  37. {
  38. ExporterWindow.ReportProgress(1, "Copying hdr texture cube item: " + textureHdrName);
  39. File.Copy(srcTexturePath, hdrTexturePath, true);
  40. }
  41. }
  42. else
  43. {
  44. var importTool = new BabylonTextureImporter(srcTexturePath);
  45. bool isReadable = importTool.IsReadable();
  46. if (!isReadable) importTool.SetReadable();
  47. try
  48. {
  49. foreach (CubemapFace face in Enum.GetValues(typeof(CubemapFace)))
  50. {
  51. var faceTexturePath = Path.Combine(babylonScene.OutputPath, Path.GetFileNameWithoutExtension(texturePath));
  52. switch (face)
  53. {
  54. case CubemapFace.PositiveX:
  55. faceTexturePath += ("_px" + fext);
  56. break;
  57. case CubemapFace.NegativeX:
  58. faceTexturePath += ("_nx" + fext);
  59. break;
  60. case CubemapFace.PositiveY:
  61. faceTexturePath += ("_py" + fext);
  62. break;
  63. case CubemapFace.NegativeY:
  64. faceTexturePath += ("_ny" + fext);
  65. break;
  66. case CubemapFace.PositiveZ:
  67. faceTexturePath += ("_pz" + fext);
  68. break;
  69. case CubemapFace.NegativeZ:
  70. faceTexturePath += ("_nz" + fext);
  71. break;
  72. default:
  73. continue;
  74. }
  75. bool writeFaceTexture = true;
  76. string textureFaceName = Path.GetFileName(faceTexturePath);
  77. if (textureNotExistsMode && File.Exists(faceTexturePath))
  78. {
  79. writeFaceTexture = false;
  80. ExporterWindow.ReportProgress(1, "Texture cube item exists: " + textureFaceName);
  81. }
  82. if (writeFaceTexture)
  83. {
  84. ExporterWindow.ReportProgress(1, "Exporting texture cube item: " + textureFaceName);
  85. var tempTexture = new Texture2D(cubemap.width, cubemap.height, TextureFormat.ARGB32, false);
  86. Color[] pixels = cubemap.GetPixels(face);
  87. tempTexture.SetPixels(pixels);
  88. tempTexture.Apply();
  89. // Flip faces in cube texture.
  90. tempTexture = FlipTexture(tempTexture);
  91. // Encode cube face texture
  92. if (png)
  93. {
  94. File.WriteAllBytes(faceTexturePath, tempTexture.EncodeToPNG());
  95. }
  96. else
  97. {
  98. File.WriteAllBytes(faceTexturePath, tempTexture.EncodeToJPG(exportationOptions.DefaultQualityLevel));
  99. }
  100. }
  101. }
  102. }
  103. finally
  104. {
  105. if (!isReadable) importTool.ForceUpdate();
  106. }
  107. }
  108. }
  109. catch (Exception ex)
  110. {
  111. Debug.LogException(ex);
  112. }
  113. if (babylonTexture != null)
  114. {
  115. var textureName = Path.GetFileNameWithoutExtension(texturePath);
  116. if (hdr) textureName += ".hdr";
  117. babylonTexture.name = textureName;
  118. babylonTexture.isCube = true;
  119. babylonTexture.level = exportationOptions.ReflectionDefaultLevel;
  120. babylonTexture.coordinatesMode = 3;
  121. }
  122. }
  123. private Texture2D FlipTexture(Texture2D original)
  124. {
  125. Texture2D flipped = new Texture2D(original.width, original.height);
  126. for (int i = 0; i < original.width; i++)
  127. {
  128. for (int j = 0; j < original.height; j++)
  129. {
  130. flipped.SetPixel(i, original.height - j - 1, original.GetPixel(i, j));
  131. }
  132. }
  133. flipped.Apply();
  134. return flipped;
  135. }
  136. private void CopyTextureFace(string texturePath, string textureName, Texture2D textureFace)
  137. {
  138. if (!babylonScene.AddTextureCube(textureName))
  139. {
  140. return;
  141. }
  142. bool png = (exportationOptions.DefaultImageFormat == (int)BabylonImageFormat.PNG);
  143. bool textureNotExistsMode = (SceneController != null && SceneController.skyboxOptions.textureFile == BabylonTextureExport.IfNotExists);
  144. bool writeTextureFile = true;
  145. if (textureNotExistsMode && File.Exists(texturePath))
  146. {
  147. writeTextureFile = false;
  148. ExporterWindow.ReportProgress(1, "Texture cube item exists: " + textureName);
  149. }
  150. if (writeTextureFile)
  151. {
  152. var srcTexturePath = AssetDatabase.GetAssetPath(textureFace);
  153. if ((png && srcTexturePath.EndsWith(".png", StringComparison.OrdinalIgnoreCase)) || (!png && (srcTexturePath.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) || srcTexturePath.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase))))
  154. {
  155. ExporterWindow.ReportProgress(1, "Copying texture cube item: " + textureName);
  156. File.Copy(srcTexturePath, texturePath, true);
  157. }
  158. else
  159. {
  160. if (textureFace != null)
  161. {
  162. var importTool = new BabylonTextureImporter(srcTexturePath);
  163. bool isReadable = importTool.IsReadable();
  164. if (!isReadable) importTool.SetReadable();
  165. try
  166. {
  167. ExporterWindow.ReportProgress(1, "Exporting texture cube item: " + textureName);
  168. var tempTexture = new Texture2D(textureFace.width, textureFace.height, TextureFormat.ARGB32, false);
  169. Color[] pixels = textureFace.GetPixels();
  170. tempTexture.SetPixels(pixels);
  171. tempTexture.Apply();
  172. if (png)
  173. {
  174. File.WriteAllBytes(texturePath, tempTexture.EncodeToPNG());
  175. }
  176. else
  177. {
  178. File.WriteAllBytes(texturePath, tempTexture.EncodeToJPG(exportationOptions.DefaultQualityLevel));
  179. }
  180. }
  181. catch (Exception ex)
  182. {
  183. Debug.LogException(ex);
  184. }
  185. finally
  186. {
  187. if (!isReadable) importTool.ForceUpdate();
  188. }
  189. }
  190. }
  191. }
  192. }
  193. private void CopyTexture(string texturePath, Texture2D texture2D, BabylonTexture babylonTexture, bool isLightmap = false)
  194. {
  195. string rename = null;
  196. bool needToDelete = false;
  197. // Convert unsupported file extensions
  198. if (texturePath.EndsWith(".psd") || texturePath.EndsWith(".tif") || texturePath.EndsWith(".exr"))
  199. {
  200. string srcTexturePath = AssetDatabase.GetAssetPath(texture2D);
  201. var importTool = new BabylonTextureImporter(srcTexturePath);
  202. bool isReadable = importTool.IsReadable();
  203. if (!isReadable) importTool.SetReadable();
  204. try
  205. {
  206. var usePNG = texture2D.alphaIsTransparency;
  207. var tempTexture = new Texture2D(texture2D.width, texture2D.height, TextureFormat.ARGB32, false);
  208. if (isLightmap)
  209. {
  210. rename = SceneName + Path.GetFileName(texturePath);
  211. Color[] pixels = texture2D.GetPixels(0, 0, texture2D.width, texture2D.height);
  212. for (int index = 0; index < pixels.Length; index++)
  213. {
  214. pixels[index].r = pixels[index].r * pixels[index].a * 5;
  215. pixels[index].g = pixels[index].g * pixels[index].a * 5;
  216. pixels[index].b = pixels[index].b * pixels[index].a * 5;
  217. }
  218. tempTexture.SetPixels(pixels);
  219. }
  220. else
  221. {
  222. Color[] pixels = texture2D.GetPixels(0, 0, texture2D.width, texture2D.height);
  223. for (int index = 0; index < pixels.Length; index++)
  224. {
  225. usePNG |= pixels[index].a <= 0.99999f;
  226. }
  227. tempTexture.SetPixels32(texture2D.GetPixels32());
  228. }
  229. tempTexture.Apply();
  230. string outputfile = (!String.IsNullOrEmpty(rename)) ? rename : texturePath;
  231. texturePath = Path.Combine(Path.GetTempPath(), Path.GetFileName(outputfile));
  232. var extension = (usePNG || exportationOptions.DefaultImageFormat == (int)BabylonImageFormat.PNG) ? ".png" : ".jpg";
  233. texturePath = texturePath.Replace(".psd", extension).Replace(".tif", extension).Replace(".exr", extension);
  234. File.WriteAllBytes(texturePath, (usePNG || exportationOptions.DefaultImageFormat == (int)BabylonImageFormat.PNG) ? tempTexture.EncodeToPNG() : tempTexture.EncodeToJPG(exportationOptions.DefaultQualityLevel));
  235. needToDelete = true;
  236. }
  237. catch (Exception ex)
  238. {
  239. Debug.LogException(ex);
  240. }
  241. finally
  242. {
  243. if (!isReadable) importTool.ForceUpdate();
  244. }
  245. }
  246. else if (texture2D.alphaIsTransparency || texturePath.EndsWith(".png"))
  247. {
  248. babylonTexture.hasAlpha = true;
  249. }
  250. else
  251. {
  252. babylonTexture.hasAlpha = false;
  253. }
  254. var textureName = Path.GetFileName(texturePath);
  255. babylonTexture.name = textureName;
  256. babylonScene.AddTexture(texturePath);
  257. if (needToDelete) File.Delete(texturePath);
  258. }
  259. private static Color[] GetPixels(Texture2D texture)
  260. {
  261. Color[] pixels = null;
  262. string srcTexturePath = AssetDatabase.GetAssetPath(texture);
  263. var importTool = new BabylonTextureImporter(srcTexturePath);
  264. bool isReadable = importTool.IsReadable();
  265. if (!isReadable) importTool.SetReadable();
  266. try
  267. {
  268. pixels = texture.GetPixels();
  269. }
  270. catch (Exception ex)
  271. {
  272. Debug.LogException(ex);
  273. }
  274. finally
  275. {
  276. if (!isReadable) importTool.ForceUpdate();
  277. }
  278. return pixels;
  279. }
  280. private BabylonMaterial DumpMaterial(Material material, int lightmapIndex = -1, Vector4 lightmapScaleOffset = default(Vector4), int lightmapCoordIndex = -1)
  281. {
  282. if (material.shader.name == "Standard")
  283. {
  284. return DumpPBRMaterial(material, lightmapIndex, lightmapScaleOffset, true, lightmapCoordIndex);
  285. }
  286. else if (material.shader.name == "Standard (Specular setup)")
  287. {
  288. return DumpPBRMaterial(material, lightmapIndex, lightmapScaleOffset, false, lightmapCoordIndex);
  289. }
  290. else if (material.shader.name.Substring(0, 10) == "BabylonJS/")
  291. {
  292. return DumpShaderMaterial(material);
  293. }
  294. return DumpStandardMaterial(material, lightmapIndex, lightmapScaleOffset, lightmapCoordIndex);
  295. }
  296. private BabylonMaterial DumpStandardMaterial(Material material, int lightmapIndex = -1, Vector4 lightmapScaleOffset = default(Vector4), int lightmapCoordIndex = -1)
  297. {
  298. var materialNotSupported = false;
  299. if (!materialsDictionary.ContainsKey(material.name))
  300. {
  301. var bMat = new BabylonStandardMaterial
  302. {
  303. name = material.name,
  304. id = Guid.NewGuid().ToString(),
  305. diffuse = new float[4],
  306. specular = new float[4]
  307. };
  308. ExporterWindow.ReportProgress(1, "Exporting standard material: " + material.name);
  309. if (exportationOptions.DefaultLightmapMode == (int)BabylonLightmapMode.FullLightBaking)
  310. {
  311. bMat.disableLighting = true;
  312. bMat.useEmissiveAsIllumination = true;
  313. }
  314. // Default diffuse
  315. bMat.diffuse[0] = 1.0f;
  316. bMat.diffuse[1] = 1.0f;
  317. bMat.diffuse[2] = 1.0f;
  318. bMat.diffuse[3] = 1.0f;
  319. // Default specular
  320. bMat.specular[0] = 0.0f;
  321. bMat.specular[1] = 0.0f;
  322. bMat.specular[2] = 0.0f;
  323. bMat.specular[3] = 1.0f;
  324. if (material.mainTexture && material.mainTexture.GetType().FullName == "UnityEngine.ProceduralTexture")
  325. {
  326. materialNotSupported = true;
  327. Debug.LogWarning("ProceduralTexture: " + material.mainTexture.name + " not supported by Babylon.js");
  328. }
  329. if (material.HasProperty("_Shininess"))
  330. {
  331. var specShininess = material.GetFloat("_Shininess");
  332. bMat.specularPower = specShininess * 128;
  333. }
  334. if (material.HasProperty("_Color"))
  335. {
  336. bMat.diffuse = material.color.ToFloat();
  337. }
  338. if (material.HasProperty("_SpecColor"))
  339. {
  340. var specColor = material.GetColor("_SpecColor");
  341. bMat.specular = specColor.ToFloat();
  342. }
  343. if (material.HasProperty("_Emission"))
  344. {
  345. if (material.GetColorNames().IndexOf("_Emission") >= 0)
  346. {
  347. var emissiveColor = material.GetColor("_Emission");
  348. bMat.emissive = emissiveColor.ToFloat();
  349. }
  350. else if (material.GetFloatNames().IndexOf("_Emission") >= 0)
  351. {
  352. // TODO: Convert Lightmapper Emission Color
  353. UnityEngine.Debug.LogWarning("Material Emission Is Float Not Color: " + material.name);
  354. }
  355. }
  356. if (material.mainTexture && !materialNotSupported)
  357. {
  358. var mainTexture2D = material.mainTexture as Texture2D;
  359. var mainTexturePath = AssetDatabase.GetAssetPath(mainTexture2D);
  360. var alphaCuttOff = 0f;
  361. if (material.HasProperty("_Cutoff"))
  362. {
  363. alphaCuttOff = material.GetFloat("_Cutoff");
  364. }
  365. bMat.diffuseTexture = new BabylonTexture
  366. {
  367. uScale = material.mainTextureScale.x,
  368. vScale = material.mainTextureScale.y,
  369. uOffset = material.mainTextureOffset.x,
  370. vOffset = material.mainTextureOffset.y
  371. };
  372. CopyTexture(mainTexturePath, mainTexture2D, bMat.diffuseTexture);
  373. if ((mainTexture2D && mainTexture2D.alphaIsTransparency) || alphaCuttOff > 0)
  374. {
  375. bMat.diffuseTexture.hasAlpha = true;
  376. bMat.backFaceCulling = false;
  377. }
  378. }
  379. // Normal map
  380. bMat.bumpTexture = DumpTextureFromMaterial(material, "_BumpMap");
  381. if (bMat.bumpTexture != null && material.HasProperty("_BumpScale"))
  382. {
  383. bMat.bumpTexture.level = material.GetFloat("_BumpScale");
  384. }
  385. bMat.emissiveTexture = DumpTextureFromMaterial(material, "_Illum");
  386. bMat.ambientTexture = DumpTextureFromMaterial(material, "_LightMap");
  387. bMat.reflectionTexture = DumpTextureFromMaterial(material, "_Cube");
  388. // If no ambient texture already (ambientTexture manually set for lightmaps on standard material)
  389. bool hasLightmap = (exportationOptions.ExportLightmaps && lightmapIndex >= 0 && lightmapIndex != 65535 && LightmapSettings.lightmaps.Length > lightmapIndex);
  390. if (hasLightmap && bMat.ambientTexture == null)
  391. {
  392. var lightmap = LightmapSettings.lightmaps[lightmapIndex].lightmapLight;
  393. var texturePath = AssetDatabase.GetAssetPath(lightmap);
  394. if (!String.IsNullOrEmpty(texturePath))
  395. {
  396. ExporterWindow.ReportProgress(1, "Dumping std material lightmap: " + lightmap.name);
  397. bMat.lightmapTexture = DumpTexture(lightmap, isLightmap: true);
  398. bMat.lightmapTexture.coordinatesIndex = (lightmapCoordIndex >= 0) ? lightmapCoordIndex : exportationOptions.DefaultCoordinatesIndex;
  399. bMat.useLightmapAsShadowmap = true;
  400. bMat.lightmapTexture.uScale = lightmapScaleOffset.x;
  401. bMat.lightmapTexture.vScale = lightmapScaleOffset.y;
  402. bMat.lightmapTexture.uOffset = lightmapScaleOffset.z;
  403. bMat.lightmapTexture.vOffset = lightmapScaleOffset.w;
  404. }
  405. }
  406. materialsDictionary.Add(bMat.name, bMat);
  407. return bMat;
  408. }
  409. return materialsDictionary[material.name];
  410. }
  411. private BabylonMaterial DumpPBRMaterial(Material material, int lightmapIndex = -1, Vector4 lightmapScaleOffset = default(Vector4), bool metallic = true, int lightmapCoordIndex = -1)
  412. {
  413. var materialNotSupported = false;
  414. if (materialsDictionary.ContainsKey(material.name))
  415. {
  416. return materialsDictionary[material.name];
  417. }
  418. var babylonPbrMaterial = new BabylonPBRMaterial
  419. {
  420. name = material.name,
  421. id = Guid.NewGuid().ToString(),
  422. albedo = new float[4],
  423. useEmissiveAsIllumination = true,
  424. useSpecularOverAlpha = true,
  425. useRadianceOverAlpha = true,
  426. };
  427. ExporterWindow.ReportProgress(1, "Exporting physical material: " + material.name);
  428. babylonPbrMaterial.environmentIntensity = RenderSettings.ambientIntensity;
  429. if (exportationOptions.DefaultLightmapMode == (int)BabylonLightmapMode.FullLightBaking)
  430. {
  431. babylonPbrMaterial.disableLighting = true;
  432. babylonPbrMaterial.useEmissiveAsIllumination = true;
  433. }
  434. if (material.mainTexture && material.mainTexture.GetType().FullName == "UnityEngine.ProceduralTexture")
  435. {
  436. materialNotSupported = true;
  437. Debug.LogWarning("ProceduralTexture: " + material.mainTexture.name + " not supported by Babylon.js");
  438. }
  439. // Albedo
  440. if (material.HasProperty("_Color"))
  441. {
  442. babylonPbrMaterial.albedo = material.color.ToFloat();
  443. }
  444. babylonPbrMaterial.albedoTexture = DumpTextureFromMaterial(material, "_MainTex");
  445. if (material.mainTexture != null && !materialNotSupported)
  446. {
  447. var textureScale = material.mainTextureScale;
  448. babylonPbrMaterial.albedoTexture.uScale = textureScale.x;
  449. babylonPbrMaterial.albedoTexture.vScale = textureScale.y;
  450. var textureOffset = material.mainTextureOffset;
  451. babylonPbrMaterial.albedoTexture.uOffset = textureOffset.x;
  452. babylonPbrMaterial.albedoTexture.vOffset = textureOffset.y;
  453. }
  454. // Emissive
  455. if (material.HasProperty("_EmissionColor"))
  456. {
  457. babylonPbrMaterial.emissive = material.GetColor("_EmissionColor").ToFloat();
  458. }
  459. babylonPbrMaterial.emissiveTexture = DumpTextureFromMaterial(material, "_EmissionMap");
  460. // Transparency
  461. DumpTransparency(material, babylonPbrMaterial);
  462. // Glossiess/Reflectivity
  463. DumpGlossinessReflectivity(material, metallic, babylonPbrMaterial);
  464. // Occlusion
  465. babylonPbrMaterial.ambientTexture = DumpTextureFromMaterial(material, "_OcclusionMap");
  466. if (babylonPbrMaterial.ambientTexture != null && material.HasProperty("_OcclusionStrength"))
  467. {
  468. babylonPbrMaterial.ambientTexture.level = material.GetFloat("_OcclusionStrength");
  469. }
  470. // Normal
  471. babylonPbrMaterial.bumpTexture = DumpTextureFromMaterial(material, "_BumpMap");
  472. if (babylonPbrMaterial.bumpTexture != null && material.HasProperty("_BumpScale"))
  473. {
  474. babylonPbrMaterial.bumpTexture.level = material.GetFloat("_BumpScale");
  475. }
  476. // Reflection
  477. babylonPbrMaterial.reflectionTexture = DumpReflectionTexture();
  478. // Lightmapping
  479. bool hasLightmap = (exportationOptions.ExportLightmaps && lightmapIndex >= 0 && lightmapIndex != 65535 && LightmapSettings.lightmaps.Length > lightmapIndex);
  480. if (hasLightmap && babylonPbrMaterial.ambientTexture == null)
  481. {
  482. var lightmap = LightmapSettings.lightmaps[lightmapIndex].lightmapLight;
  483. var texturePath = AssetDatabase.GetAssetPath(lightmap);
  484. if (!String.IsNullOrEmpty(texturePath))
  485. {
  486. ExporterWindow.ReportProgress(1, "Dumping pbr material lightmap: " + lightmap.name);
  487. babylonPbrMaterial.lightmapTexture = DumpTexture(lightmap, isLightmap: true);
  488. babylonPbrMaterial.lightmapTexture.coordinatesIndex = (lightmapCoordIndex >= 0) ? lightmapCoordIndex : exportationOptions.DefaultCoordinatesIndex;
  489. babylonPbrMaterial.useLightmapAsShadowmap = true;
  490. babylonPbrMaterial.lightmapTexture.uScale = lightmapScaleOffset.x;
  491. babylonPbrMaterial.lightmapTexture.vScale = lightmapScaleOffset.y;
  492. babylonPbrMaterial.lightmapTexture.uOffset = lightmapScaleOffset.z;
  493. babylonPbrMaterial.lightmapTexture.vOffset = lightmapScaleOffset.w;
  494. }
  495. }
  496. materialsDictionary.Add(babylonPbrMaterial.name, babylonPbrMaterial);
  497. return babylonPbrMaterial;
  498. }
  499. private void DumpGlossinessReflectivity(Material material, bool metallic, BabylonPBRMaterial babylonPbrMaterial)
  500. {
  501. if (material.HasProperty("_Glossiness"))
  502. {
  503. babylonPbrMaterial.microSurface = material.GetFloat("_Glossiness");
  504. }
  505. if (metallic)
  506. {
  507. if (material.HasProperty("_Metallic"))
  508. {
  509. var metalness = material.GetFloat("_Metallic");
  510. babylonPbrMaterial.reflectivity = new float[] { metalness * babylonPbrMaterial.albedo[0], metalness * babylonPbrMaterial.albedo[1], metalness * babylonPbrMaterial.albedo[2] };
  511. if (babylonPbrMaterial.albedoTexture != null)
  512. {
  513. var albedoTexture = material.GetTexture("_MainTex") as Texture2D;
  514. if (albedoTexture != null)
  515. {
  516. var albedoPixels = GetPixels(albedoTexture);
  517. var reflectivityTexture = new Texture2D(albedoTexture.width, albedoTexture.height, TextureFormat.RGBA32, false);
  518. reflectivityTexture.alphaIsTransparency = true;
  519. babylonPbrMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  520. var metallicTexture = material.GetTexture("_MetallicGlossMap") as Texture2D;
  521. if (metallicTexture == null)
  522. {
  523. for (var i = 0; i < albedoTexture.width; i++)
  524. {
  525. for (var j = 0; j < albedoTexture.height; j++)
  526. {
  527. albedoPixels[j * albedoTexture.width + i].r *= metalness;
  528. albedoPixels[j * albedoTexture.width + i].g *= metalness;
  529. albedoPixels[j * albedoTexture.width + i].b *= metalness;
  530. albedoPixels[j * albedoTexture.width + i].a = babylonPbrMaterial.microSurface;
  531. }
  532. }
  533. }
  534. else
  535. {
  536. var metallicPixels = GetPixels(metallicTexture);
  537. for (var i = 0; i < albedoTexture.width; i++)
  538. {
  539. for (var j = 0; j < albedoTexture.height; j++)
  540. {
  541. var metallicPixel = metallicPixels[j * albedoTexture.width + i];
  542. albedoPixels[j * albedoTexture.width + i].r *= metallicPixel.r;
  543. albedoPixels[j * albedoTexture.width + i].g *= metallicPixel.r;
  544. albedoPixels[j * albedoTexture.width + i].b *= metallicPixel.r;
  545. albedoPixels[j * albedoTexture.width + i].a = metallicPixel.a;
  546. }
  547. }
  548. }
  549. reflectivityTexture.SetPixels(albedoPixels);
  550. reflectivityTexture.Apply();
  551. var textureName = albedoTexture.name + "_MetallicGlossMap.png";
  552. var babylonTexture = new BabylonTexture { name = textureName };
  553. var textureScale = material.GetTextureScale("_MainTex");
  554. babylonTexture.uScale = textureScale.x;
  555. babylonTexture.vScale = textureScale.y;
  556. var textureOffset = material.GetTextureOffset("_MainTex");
  557. babylonTexture.uOffset = textureOffset.x;
  558. babylonTexture.vOffset = textureOffset.y;
  559. var reflectivityTexturePath = Path.Combine(Path.GetTempPath(), textureName);
  560. File.WriteAllBytes(reflectivityTexturePath, reflectivityTexture.EncodeToPNG());
  561. babylonScene.AddTexture(reflectivityTexturePath);
  562. if (File.Exists(reflectivityTexturePath))
  563. {
  564. File.Delete(reflectivityTexturePath);
  565. }
  566. babylonPbrMaterial.reflectivityTexture = babylonTexture;
  567. }
  568. }
  569. //else
  570. //{
  571. // TODO. Manage Albedo Cube Texture.
  572. //}
  573. }
  574. }
  575. else
  576. {
  577. if (material.HasProperty("_SpecColor"))
  578. {
  579. babylonPbrMaterial.reflectivity = material.GetColor("_SpecColor").ToFloat();
  580. }
  581. babylonPbrMaterial.reflectivityTexture = DumpTextureFromMaterial(material, "_SpecGlossMap");
  582. if (babylonPbrMaterial.reflectivityTexture != null && babylonPbrMaterial.reflectivityTexture.hasAlpha)
  583. {
  584. babylonPbrMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  585. }
  586. }
  587. }
  588. private BabylonMaterial DumpShaderMaterial(Material material)
  589. {
  590. if (materialsDictionary.ContainsKey(material.name))
  591. {
  592. return materialsDictionary[material.name];
  593. }
  594. var babylonShaderMaterial = new BabylonShaderMaterial
  595. {
  596. name = material.name,
  597. id = Guid.NewGuid().ToString(),
  598. };
  599. ExporterWindow.ReportProgress(1, "Exporting glsl material: " + material.name);
  600. List<string> tnames = material.GetTextureNames();
  601. foreach (string tname in tnames)
  602. {
  603. BabylonTexture tdata = DumpTextureFromMaterial(material, tname);
  604. if (tdata != null)
  605. {
  606. babylonShaderMaterial.textures.Add(tname, tdata);
  607. }
  608. }
  609. List<string> fnames = material.GetFloatNames();
  610. foreach (string fname in fnames)
  611. {
  612. float fdata = material.GetFloat(fname);
  613. babylonShaderMaterial.floats.Add(fname, fdata);
  614. }
  615. List<string> rnames = material.GetRangeNames();
  616. foreach (string rname in rnames)
  617. {
  618. float rdata = material.GetFloat(rname);
  619. babylonShaderMaterial.floats.Add(rname, rdata);
  620. }
  621. List<string> cnames = material.GetColorNames();
  622. foreach (string cname in cnames)
  623. {
  624. Color cdata = material.GetColor(cname);
  625. babylonShaderMaterial.vectors4.Add(cname, cdata.ToFloat());
  626. }
  627. List<string> vnames = material.GetVectorNames();
  628. foreach (string vname in vnames)
  629. {
  630. Vector4 vdata = material.GetVector(vname);
  631. babylonShaderMaterial.vectors4.Add(vname, vdata.ToFloat());
  632. }
  633. Shader shader = material.shader;
  634. string filename = AssetDatabase.GetAssetPath(shader);
  635. string program = Tools.LoadTextAsset(filename);
  636. string basename = shader.name.Replace("BabylonJS/", "").Replace("/", "_").Replace(" ", "");
  637. string outpath = (!String.IsNullOrEmpty(exportationOptions.DefaultShaderFolder)) ? exportationOptions.DefaultShaderFolder : OutputPath;
  638. var shaderpath = new Dictionary<string, string>();
  639. List<string> attributeList = new List<string>();
  640. List<string> uniformList = new List<string>();
  641. List<string> samplerList = new List<string>();
  642. List<string> defineList = new List<string>();
  643. string babylonOptions = GetShaderProgramSection(basename, program, BabylonProgramSection.Babylon);
  644. string[] babylonLines = babylonOptions.Split('\n');
  645. foreach (string babylonLine in babylonLines)
  646. {
  647. if (babylonLine.IndexOf("attributes", StringComparison.OrdinalIgnoreCase) >= 0)
  648. {
  649. string[] attributes = babylonLine.Split(':');
  650. if (attributes != null && attributes.Length > 1)
  651. {
  652. string abuffer = attributes[1].Replace("[", "").Replace("]", "");
  653. if (!String.IsNullOrEmpty(abuffer))
  654. {
  655. abuffer = abuffer.Trim();
  656. string[] adata = abuffer.Split(',');
  657. if (adata != null && adata.Length > 0)
  658. {
  659. foreach (string aoption in adata)
  660. {
  661. string aoption_buffer = aoption.Trim().Replace("\"", "").Trim();
  662. if (!String.IsNullOrEmpty(aoption_buffer))
  663. {
  664. attributeList.Add(aoption_buffer);
  665. }
  666. }
  667. }
  668. }
  669. }
  670. }
  671. else if (babylonLine.IndexOf("uniforms", StringComparison.OrdinalIgnoreCase) >= 0)
  672. {
  673. string[] uniforms = babylonLine.Split(':');
  674. if (uniforms != null && uniforms.Length > 1)
  675. {
  676. string ubuffer = uniforms[1].Replace("[", "").Replace("]", "");
  677. if (!String.IsNullOrEmpty(ubuffer))
  678. {
  679. ubuffer = ubuffer.Trim();
  680. string[] udata = ubuffer.Split(',');
  681. if (udata != null && udata.Length > 0)
  682. {
  683. foreach (string uoption in udata)
  684. {
  685. string uoption_buffer = uoption.Trim().Replace("\"", "").Trim();
  686. if (!String.IsNullOrEmpty(uoption_buffer))
  687. {
  688. uniformList.Add(uoption_buffer);
  689. }
  690. }
  691. }
  692. }
  693. }
  694. }
  695. else if (babylonLine.IndexOf("samplers", StringComparison.OrdinalIgnoreCase) >= 0)
  696. {
  697. string[] samplers = babylonLine.Split(':');
  698. if (samplers != null && samplers.Length > 1)
  699. {
  700. string sbuffer = samplers[1].Replace("[", "").Replace("]", "");
  701. if (!String.IsNullOrEmpty(sbuffer))
  702. {
  703. sbuffer = sbuffer.Trim();
  704. string[] sdata = sbuffer.Split(',');
  705. if (sdata != null && sdata.Length > 0)
  706. {
  707. foreach (string soption in sdata)
  708. {
  709. string soption_buffer = soption.Trim().Replace("\"", "").Trim();
  710. if (!String.IsNullOrEmpty(soption_buffer))
  711. {
  712. samplerList.Add(soption_buffer);
  713. }
  714. }
  715. }
  716. }
  717. }
  718. }
  719. else if (babylonLine.IndexOf("defines", StringComparison.OrdinalIgnoreCase) >= 0)
  720. {
  721. string[] defines = babylonLine.Split(':');
  722. if (defines != null && defines.Length > 1)
  723. {
  724. string dbuffer = defines[1].Replace("[", "").Replace("]", "");
  725. if (!String.IsNullOrEmpty(dbuffer))
  726. {
  727. dbuffer = dbuffer.Trim();
  728. string[] ddata = dbuffer.Split(',');
  729. if (ddata != null && ddata.Length > 0)
  730. {
  731. foreach (string doption in ddata)
  732. {
  733. string doption_buffer = doption.Trim().Replace("\"", "").Trim();
  734. if (!String.IsNullOrEmpty(doption_buffer))
  735. {
  736. defineList.Add(doption_buffer);
  737. }
  738. }
  739. }
  740. }
  741. }
  742. }
  743. }
  744. babylonShaderMaterial.options = new BabylonShaderOptions();
  745. babylonShaderMaterial.options.attributes = attributeList.ToArray();
  746. babylonShaderMaterial.options.uniforms = uniformList.ToArray();
  747. babylonShaderMaterial.options.samplers = samplerList.ToArray();
  748. babylonShaderMaterial.options.defines = defineList.ToArray();
  749. string vertexProgram = GetShaderProgramSection(basename, program, BabylonProgramSection.Vertex);
  750. var vertextFile = Path.Combine(outpath, basename + ".vertex.fx");
  751. if (exportationOptions.EmbeddedShaders)
  752. {
  753. shaderpath.Add("vertexElement", ("base64:" + Tools.FormatBase64(vertexProgram)));
  754. }
  755. else
  756. {
  757. File.WriteAllText(vertextFile, vertexProgram);
  758. }
  759. string fragmentProgram = GetShaderProgramSection(basename, program, BabylonProgramSection.Fragment);
  760. var fragmentFile = Path.Combine(outpath, basename + ".fragment.fx");
  761. if (exportationOptions.EmbeddedShaders)
  762. {
  763. shaderpath.Add("fragmentElement", ("base64:" + Tools.FormatBase64(fragmentProgram)));
  764. }
  765. else
  766. {
  767. File.WriteAllText(fragmentFile, fragmentProgram);
  768. }
  769. babylonShaderMaterial.shaderPath = (exportationOptions.EmbeddedShaders) ? (object)shaderpath : (object)basename;
  770. materialsDictionary.Add(babylonShaderMaterial.name, babylonShaderMaterial);
  771. return babylonShaderMaterial;
  772. }
  773. private string GetShaderProgramSection(string name, string program, BabylonProgramSection section)
  774. {
  775. string result = String.Empty;
  776. string[] lines = program.Split('\n');
  777. int babylonIndexStart = -1, babylonIndexEnd = -1;
  778. int vertextIndexStart = -1, vertextIndexEnd = -1;
  779. int fragmentIndexStart = -1, fragmentIndexEnd = -1;
  780. for (int ii = 0; ii < lines.Length; ii++)
  781. {
  782. string line = lines[ii];
  783. if (babylonIndexStart < 0 && line.IndexOf("#ifdef BABYLON", StringComparison.OrdinalIgnoreCase) >= 0)
  784. {
  785. babylonIndexStart = ii;
  786. }
  787. if (babylonIndexEnd < 0 && line.IndexOf("#endif //BABYLON-END", StringComparison.OrdinalIgnoreCase) >= 0)
  788. {
  789. babylonIndexEnd = ii;
  790. }
  791. if (vertextIndexStart < 0 && line.IndexOf("#ifdef VERTEX", StringComparison.OrdinalIgnoreCase) >= 0)
  792. {
  793. vertextIndexStart = ii;
  794. }
  795. if (vertextIndexEnd < 0 && line.IndexOf("#endif //VERTEX-END", StringComparison.OrdinalIgnoreCase) >= 0)
  796. {
  797. vertextIndexEnd = ii;
  798. }
  799. if (fragmentIndexStart < 0 && line.IndexOf("#ifdef FRAGMENT", StringComparison.OrdinalIgnoreCase) >= 0)
  800. {
  801. fragmentIndexStart = ii;
  802. }
  803. if (fragmentIndexEnd < 0 && line.IndexOf("#endif //FRAGMENT-END", StringComparison.OrdinalIgnoreCase) >= 0)
  804. {
  805. fragmentIndexEnd = ii;
  806. }
  807. }
  808. // Note: All Babylon Shader Blocks Are Required
  809. if (babylonIndexStart >= 0 && babylonIndexEnd >= 0 && vertextIndexStart >= 0 && vertextIndexEnd >= 0 && fragmentIndexStart >= 0 && fragmentIndexEnd >= 0)
  810. {
  811. int lineStart = -1, lineEnd = -1;
  812. switch (section)
  813. {
  814. case BabylonProgramSection.Babylon:
  815. lineStart = babylonIndexStart;
  816. lineEnd = babylonIndexEnd;
  817. break;
  818. case BabylonProgramSection.Vertex:
  819. lineStart = vertextIndexStart;
  820. lineEnd = vertextIndexEnd;
  821. break;
  822. case BabylonProgramSection.Fragment:
  823. lineStart = fragmentIndexStart;
  824. lineEnd = fragmentIndexEnd;
  825. break;
  826. }
  827. if (lineStart >= 0 && lineEnd >= 0)
  828. {
  829. lineStart++;
  830. for (int xx = lineStart; xx < lineEnd; xx++)
  831. {
  832. string buffer = lines[xx];
  833. buffer = buffer.TrimEnd('\n').TrimEnd('\r');
  834. result += (buffer + "\r\n");
  835. }
  836. }
  837. else
  838. {
  839. Debug.LogError("Invalid Babylon Shader Block Lines: " + name);
  840. }
  841. }
  842. else
  843. {
  844. Debug.LogError("Invalid Babylon Shader Block Format: " + name);
  845. }
  846. return result;
  847. }
  848. private BabylonTexture DumpReflectionTexture()
  849. {
  850. if (sceneReflectionTexture != null)
  851. {
  852. return sceneReflectionTexture;
  853. }
  854. bool png = (exportationOptions.DefaultImageFormat == (int)BabylonImageFormat.PNG);
  855. string fext = (png == true) ? ".png" : ".jpg";
  856. // Take only reflection source currently and not the RenderSettings.ambientMode
  857. if (RenderSettings.defaultReflectionMode == UnityEngine.Rendering.DefaultReflectionMode.Skybox)
  858. {
  859. var skybox = RenderSettings.skybox;
  860. if (SceneController != null && skybox != null)
  861. {
  862. if (skybox.shader.name == "Skybox/Cubemap")
  863. {
  864. var cubeMap = skybox.GetTexture("_Tex") as Cubemap;
  865. if (cubeMap != null)
  866. {
  867. var srcTexturePath = AssetDatabase.GetAssetPath(cubeMap);
  868. if (srcTexturePath.EndsWith(".hdr", StringComparison.OrdinalIgnoreCase))
  869. {
  870. var hdr = new BabylonHDRCubeTexture();
  871. hdr.size = cubeMap.width;
  872. sceneReflectionTexture = hdr;
  873. sceneReflectionTexture.isCube = true;
  874. CopyTextureCube(String.Format("{0}Reflection.hdr", SceneName), cubeMap, sceneReflectionTexture, true);
  875. }
  876. else
  877. {
  878. sceneReflectionTexture = new BabylonTexture();
  879. sceneReflectionTexture.isCube = true;
  880. CopyTextureCube(String.Format("{0}Reflection.hdr", SceneName), cubeMap, sceneReflectionTexture, false);
  881. if (png) (sceneReflectionTexture as BabylonTexture).extensions = new string[] { "_px.png", "_py.png", "_pz.png", "_nx.png", "_ny.png", "_nz.png" };
  882. }
  883. sceneReflectionTexture.level = (SceneController != null) ? SceneController.skyboxOptions.lightIntensity : 1.0f;
  884. }
  885. }
  886. else if (skybox.shader.name == "Skybox/6 Sided")
  887. {
  888. var frontTexture = skybox.GetTexture("_FrontTex") as Texture2D;
  889. var backTexture = skybox.GetTexture("_BackTex") as Texture2D;
  890. var leftTexture = skybox.GetTexture("_LeftTex") as Texture2D;
  891. var rightTexture = skybox.GetTexture("_RightTex") as Texture2D;
  892. var upTexture = skybox.GetTexture("_UpTex") as Texture2D;
  893. var downTexture = skybox.GetTexture("_DownTex") as Texture2D;
  894. if (frontTexture != null && backTexture != null && leftTexture != null && rightTexture != null && upTexture != null && downTexture != null)
  895. {
  896. sceneReflectionTexture = new BabylonTexture();
  897. sceneReflectionTexture.name = String.Format("{0}Reflection", SceneName);
  898. sceneReflectionTexture.isCube = true;
  899. var frontTextureName = String.Format("{0}_pz{1}", sceneReflectionTexture.name, fext);
  900. var frontTexturePath = Path.Combine(babylonScene.OutputPath, frontTextureName);
  901. CopyTextureFace(frontTexturePath, frontTextureName, frontTexture);
  902. var backTextureName = String.Format("{0}_nz{1}", sceneReflectionTexture.name, fext);
  903. var backTexturePath = Path.Combine(babylonScene.OutputPath, backTextureName);
  904. CopyTextureFace(backTexturePath, backTextureName, backTexture);
  905. var leftTextureName = String.Format("{0}_px{1}", sceneReflectionTexture.name, fext);
  906. var leftTexturePath = Path.Combine(babylonScene.OutputPath, leftTextureName);
  907. CopyTextureFace(leftTexturePath, leftTextureName, leftTexture);
  908. var rightTextureName = String.Format("{0}_nx{1}", sceneReflectionTexture.name, fext);
  909. var rightTexturePath = Path.Combine(babylonScene.OutputPath, rightTextureName);
  910. CopyTextureFace(rightTexturePath, rightTextureName, rightTexture);
  911. var upTextureName = String.Format("{0}_py{1}", sceneReflectionTexture.name, fext);
  912. var upTexturePath = Path.Combine(babylonScene.OutputPath, upTextureName);
  913. CopyTextureFace(upTexturePath, upTextureName, upTexture);
  914. var downTextureName = String.Format("{0}_ny{1}", sceneReflectionTexture.name, fext);
  915. var downTexturePath = Path.Combine(babylonScene.OutputPath, downTextureName);
  916. CopyTextureFace(downTexturePath, downTexturePath, downTexture);
  917. if (png) (sceneReflectionTexture as BabylonTexture).extensions = new string[] { "_px.png", "_py.png", "_pz.png", "_nx.png", "_ny.png", "_nz.png" };
  918. sceneReflectionTexture.level = (SceneController != null) ? SceneController.skyboxOptions.lightIntensity : 1.0f;
  919. }
  920. }
  921. }
  922. }
  923. else if (RenderSettings.customReflection != null)
  924. {
  925. var cubeMap = RenderSettings.customReflection;
  926. var srcTexturePath = AssetDatabase.GetAssetPath(cubeMap);
  927. if (srcTexturePath.EndsWith(".hdr", StringComparison.OrdinalIgnoreCase))
  928. {
  929. var hdr = new BabylonHDRCubeTexture();
  930. hdr.size = cubeMap.width;
  931. sceneReflectionTexture = hdr;
  932. sceneReflectionTexture.isCube = true;
  933. CopyTextureCube(String.Format("{0}Reflection.hdr", SceneName), cubeMap, sceneReflectionTexture);
  934. }
  935. else
  936. {
  937. sceneReflectionTexture = new BabylonTexture();
  938. sceneReflectionTexture.isCube = true;
  939. CopyTextureCube(String.Format("{0}Reflection.hdr", SceneName), cubeMap, sceneReflectionTexture);
  940. if (png) (sceneReflectionTexture as BabylonTexture).extensions = new string[] { "_px.png", "_py.png", "_pz.png", "_nx.png", "_ny.png", "_nz.png" };
  941. }
  942. sceneReflectionTexture.level = (SceneController != null) ? SceneController.skyboxOptions.lightIntensity : 1.0f;
  943. }
  944. return sceneReflectionTexture;
  945. }
  946. private BabylonTexture DumpTextureFromMaterial(Material material, string name)
  947. {
  948. if (!material.HasProperty(name))
  949. {
  950. return null;
  951. }
  952. var texture = material.GetTexture(name);
  953. return DumpTexture(texture, material, name);
  954. }
  955. private BabylonTexture DumpTexture(Texture texture, Material material = null, string name = "", bool isLightmap = false)
  956. {
  957. if (texture == null)
  958. {
  959. return null;
  960. }
  961. var texturePath = AssetDatabase.GetAssetPath(texture);
  962. var textureName = Path.GetFileName(texturePath);
  963. var babylonTexture = new BabylonTexture { name = textureName };
  964. if (material != null)
  965. {
  966. var textureScale = material.GetTextureScale(name);
  967. babylonTexture.uScale = textureScale.x;
  968. babylonTexture.vScale = textureScale.y;
  969. var textureOffset = material.GetTextureOffset(name);
  970. babylonTexture.uOffset = textureOffset.x;
  971. babylonTexture.vOffset = textureOffset.y;
  972. }
  973. var texture2D = texture as Texture2D;
  974. if (texture2D)
  975. {
  976. CopyTexture(texturePath, texture2D, babylonTexture, isLightmap);
  977. }
  978. else
  979. {
  980. var cubemap = texture as Cubemap;
  981. if (cubemap != null)
  982. {
  983. CopyTextureCube(texturePath, cubemap, babylonTexture);
  984. }
  985. }
  986. return babylonTexture;
  987. }
  988. private static void DumpTransparency(Material material, BabylonPBRMaterial babylonPbrMaterial)
  989. {
  990. if (material.HasProperty("_Mode"))
  991. {
  992. var mode = material.GetFloat("_Mode");
  993. if (mode >= 2.0f)
  994. {
  995. // Transparent Albedo
  996. if (babylonPbrMaterial.albedoTexture != null && babylonPbrMaterial.albedoTexture.hasAlpha)
  997. {
  998. babylonPbrMaterial.useAlphaFromAlbedoTexture = true;
  999. }
  1000. else
  1001. {
  1002. // Material Alpha
  1003. babylonPbrMaterial.alpha = babylonPbrMaterial.albedo[3];
  1004. }
  1005. }
  1006. else if (mode == 1.0f)
  1007. {
  1008. // Cutout
  1009. // Follow the texture hasAlpha property.
  1010. }
  1011. else
  1012. {
  1013. // Opaque
  1014. if (babylonPbrMaterial.albedoTexture != null)
  1015. {
  1016. babylonPbrMaterial.albedoTexture.hasAlpha = false;
  1017. }
  1018. babylonPbrMaterial.alpha = 1.0f;
  1019. }
  1020. }
  1021. }
  1022. }
  1023. }