SceneBuilder.Materials.cs 54 KB

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