Tools.cs 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Reflection;
  6. using System.Diagnostics;
  7. using System.Collections.Generic;
  8. using Microsoft.Ajax.Utilities;
  9. using UnityEngine;
  10. using UnityEditor;
  11. using JsonFx.Json;
  12. using JsonFx.Json.Resolvers;
  13. using JsonFx.Serialization;
  14. using JsonFx.Serialization.Resolvers;
  15. using BabylonExport.Entities;
  16. namespace Unity3D2Babylon
  17. {
  18. public static class Tools
  19. {
  20. public static BindingFlags FullBinding = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty | BindingFlags.SetProperty;
  21. public static float[] ToFloat(this Color color)
  22. {
  23. var result = new float[4];
  24. result[0] = color.r;
  25. result[1] = color.g;
  26. result[2] = color.b;
  27. result[3] = color.a;
  28. return result;
  29. }
  30. public static float[] ToFloat(this Vector3 vector3)
  31. {
  32. var result = new float[3];
  33. result[0] = vector3.x;
  34. result[1] = vector3.y;
  35. result[2] = vector3.z;
  36. return result;
  37. }
  38. public static float[] ToFloat(this Vector4 vector4)
  39. {
  40. var result = new float[4];
  41. result[0] = vector4.x;
  42. result[1] = vector4.y;
  43. result[2] = vector4.z;
  44. result[3] = vector4.w;
  45. return result;
  46. }
  47. public static float[] ToFloat(this SerializableVector3 vector3)
  48. {
  49. var result = new float[3];
  50. result[0] = vector3.X;
  51. result[1] = vector3.Y;
  52. result[2] = vector3.Z;
  53. return result;
  54. }
  55. public static float[] ToFloat(this Quaternion quaternion)
  56. {
  57. var result = new float[4];
  58. result[0] = quaternion.x;
  59. result[1] = quaternion.y;
  60. result[2] = quaternion.z;
  61. result[3] = quaternion.w;
  62. return result;
  63. }
  64. public static Texture2D BlurImage(Texture2D image, int blurSize)
  65. {
  66. Texture2D blurred = new Texture2D(image.width, image.height);
  67. blurred.Apply();
  68. return blurred;
  69. }
  70. public static string FirstUpper(this string value)
  71. {
  72. string result = value;
  73. if (!String.IsNullOrEmpty(value))
  74. {
  75. result = char.ToUpper(result[0]) + result.Substring(1);
  76. }
  77. return result;
  78. }
  79. public static string FirstLower(this string value)
  80. {
  81. string result = value;
  82. if (!String.IsNullOrEmpty(value))
  83. {
  84. result = char.ToLower(result[0]) + result.Substring(1);
  85. }
  86. return result;
  87. }
  88. public static void CopyTo(this Stream source, Stream destination, bool finalFlush = false, int bufferSize = 4096, long maxCount = -1)
  89. {
  90. byte[] buffer = new byte[bufferSize];
  91. long totalBytesWritten = 0;
  92. while (true)
  93. {
  94. int count = buffer.Length;
  95. if (maxCount > 0)
  96. {
  97. if (totalBytesWritten > maxCount - count)
  98. {
  99. count = (int)(maxCount - totalBytesWritten);
  100. if (count <= 0)
  101. {
  102. break;
  103. }
  104. }
  105. }
  106. int read = source.Read(buffer, 0, count);
  107. if (read <= 0)
  108. {
  109. break;
  110. }
  111. destination.Write(buffer, 0, read);
  112. totalBytesWritten += read;
  113. }
  114. if (finalFlush)
  115. {
  116. try { destination.Flush(); } catch { }
  117. }
  118. }
  119. public static string LoadTextAsset(string filename)
  120. {
  121. string apath = Application.dataPath.Replace("/Assets", "");
  122. string asset = Path.Combine(apath, filename);
  123. return File.ReadAllText(asset);
  124. }
  125. public static List<Texture> GetTextures(this Material source)
  126. {
  127. Shader shader = source.shader;
  128. List<Texture> materials = new List<Texture>();
  129. for (int i = 0; i < ShaderUtil.GetPropertyCount(shader); i++)
  130. {
  131. if (ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.TexEnv)
  132. {
  133. materials.Add(source.GetTexture(ShaderUtil.GetPropertyName(shader, i)));
  134. }
  135. }
  136. return materials;
  137. }
  138. public static List<string> GetTextureNames(this Material source)
  139. {
  140. Shader shader = source.shader;
  141. List<string> names = new List<string>();
  142. for (int i = 0; i < ShaderUtil.GetPropertyCount(shader); i++)
  143. {
  144. if (ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.TexEnv)
  145. {
  146. names.Add(ShaderUtil.GetPropertyName(shader, i));
  147. }
  148. }
  149. return names;
  150. }
  151. public static List<string> GetFloatNames(this Material source)
  152. {
  153. Shader shader = source.shader;
  154. List<string> names = new List<string>();
  155. for (int i = 0; i < ShaderUtil.GetPropertyCount(shader); i++)
  156. {
  157. if (ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.Float)
  158. {
  159. names.Add(ShaderUtil.GetPropertyName(shader, i));
  160. }
  161. }
  162. return names;
  163. }
  164. public static List<string> GetRangeNames(this Material source)
  165. {
  166. Shader shader = source.shader;
  167. List<string> names = new List<string>();
  168. for (int i = 0; i < ShaderUtil.GetPropertyCount(shader); i++)
  169. {
  170. if (ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.Range)
  171. {
  172. names.Add(ShaderUtil.GetPropertyName(shader, i));
  173. }
  174. }
  175. return names;
  176. }
  177. public static List<string> GetColorNames(this Material source)
  178. {
  179. Shader shader = source.shader;
  180. List<string> names = new List<string>();
  181. for (int i = 0; i < ShaderUtil.GetPropertyCount(shader); i++)
  182. {
  183. if (ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.Color)
  184. {
  185. names.Add(ShaderUtil.GetPropertyName(shader, i));
  186. }
  187. }
  188. return names;
  189. }
  190. public static List<string> GetVectorNames(this Material source)
  191. {
  192. Shader shader = source.shader;
  193. List<string> names = new List<string>();
  194. for (int i = 0; i < ShaderUtil.GetPropertyCount(shader); i++)
  195. {
  196. if (ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.Vector)
  197. {
  198. names.Add(ShaderUtil.GetPropertyName(shader, i));
  199. }
  200. }
  201. return names;
  202. }
  203. public static object GetInstanceField(Type type, object instance, string fieldName)
  204. {
  205. BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetField | BindingFlags.GetProperty;
  206. FieldInfo field = type.GetField(fieldName, bindFlags);
  207. return field.GetValue(instance);
  208. }
  209. public static bool DownloadFile(string url, string dest)
  210. {
  211. bool result = false;
  212. string tempfile = Path.GetTempFileName();
  213. try
  214. {
  215. using (var webClient = new System.Net.WebClient())
  216. {
  217. webClient.DownloadFile(url, tempfile);
  218. }
  219. }
  220. catch (System.Exception ex)
  221. {
  222. string msg = System.String.Format("Failed to download: {0} - {1}", url, ex.Message);
  223. UnityEngine.Debug.LogWarning(msg);
  224. }
  225. finally
  226. {
  227. FileInfo info = new FileInfo(tempfile);
  228. result = (info.Exists && info.Length > 0);
  229. if (result == true)
  230. {
  231. File.Copy(tempfile, dest, true);
  232. }
  233. try { info.Delete(); } catch { }
  234. }
  235. return result;
  236. }
  237. public static BabylonSceneController GetSceneController()
  238. {
  239. BabylonSceneController result = null;
  240. var gameObjects = UnityEngine.Object.FindObjectsOfType<GameObject>();
  241. if (gameObjects != null && gameObjects.Length > 0)
  242. {
  243. foreach (var gameObject in gameObjects)
  244. {
  245. var controller = gameObject.GetComponent<BabylonSceneController>();
  246. if (controller != null)
  247. {
  248. result = controller;
  249. break;
  250. }
  251. }
  252. }
  253. return result;
  254. }
  255. public static string FormatBase64(string text)
  256. {
  257. return Convert.ToBase64String(Encoding.UTF8.GetBytes(text));
  258. }
  259. public static string FormatSafePath(string path)
  260. {
  261. return path.Replace("\\", "/");
  262. }
  263. public static string MakeRelativePath(string filePath, string referencePath)
  264. {
  265. var fileUri = new Uri(filePath);
  266. var referenceUri = new Uri(referencePath);
  267. return referenceUri.MakeRelativeUri(fileUri).ToString();
  268. }
  269. public static string MinifyJavascriptCode(string script)
  270. {
  271. var minifier = new Minifier();
  272. var settings = new CodeSettings();
  273. settings.EvalTreatment = EvalTreatment.MakeAllSafe;
  274. string min_script = minifier.MinifyJavaScript(script, settings);
  275. if (minifier.Errors.Count > 0)
  276. {
  277. foreach (string error in minifier.Errors)
  278. {
  279. if (!String.IsNullOrEmpty(error))
  280. {
  281. UnityEngine.Debug.LogError("Javascript Minifier: " + error);
  282. }
  283. }
  284. }
  285. return min_script;
  286. }
  287. public static List<I> FindObjectsOfInterface<I>() where I : class
  288. {
  289. MonoBehaviour[] monoBehaviours = UnityEngine.Object.FindObjectsOfType<MonoBehaviour>();
  290. List<I> list = new List<I>();
  291. foreach (MonoBehaviour behaviour in monoBehaviours)
  292. {
  293. I component = behaviour.GetComponent(typeof(I)) as I;
  294. if (component != null)
  295. {
  296. list.Add(component);
  297. }
  298. }
  299. return list;
  300. }
  301. public static T[] GetAssetsOfType<T>(string fileExtension) where T : UnityEngine.Object
  302. {
  303. List<T> tempObjects = new List<T>();
  304. DirectoryInfo directory = new DirectoryInfo(Application.dataPath);
  305. FileInfo[] goFileInfo = directory.GetFiles("*" + fileExtension, SearchOption.AllDirectories);
  306. int i = 0; int goFileInfoLength = goFileInfo.Length;
  307. FileInfo tempGoFileInfo; string tempFilePath;
  308. T tempGO;
  309. for (; i < goFileInfoLength; i++)
  310. {
  311. tempGoFileInfo = goFileInfo[i];
  312. if (tempGoFileInfo == null)
  313. continue;
  314. tempFilePath = tempGoFileInfo.FullName;
  315. tempFilePath = tempFilePath.Replace(@"\", "/").Replace(Application.dataPath, "Assets");
  316. tempGO = AssetDatabase.LoadAssetAtPath(tempFilePath, typeof(T)) as T;
  317. if (tempGO == null)
  318. {
  319. continue;
  320. }
  321. else if (!(tempGO is T))
  322. {
  323. continue;
  324. }
  325. tempObjects.Add(tempGO);
  326. }
  327. return tempObjects.ToArray();
  328. }
  329. public static T GetReflectionField<T>(object source, string name)
  330. {
  331. object result = null;
  332. var field = source.GetType().GetField(name, Tools.FullBinding);
  333. if (field != null)
  334. {
  335. result = field.GetValue(source);
  336. }
  337. return (T)result;
  338. }
  339. public static T GetReflectionProperty<T>(object source, string name)
  340. {
  341. object result = null;
  342. var property = source.GetType().GetProperty(name, Tools.FullBinding);
  343. if (property != null)
  344. {
  345. result = property.GetGetMethod(true).Invoke(source, null);
  346. }
  347. return (T)result;
  348. }
  349. public static void SetReflectionField(object source, string name, object value)
  350. {
  351. var field = source.GetType().GetField(name, Tools.FullBinding);
  352. if (field != null)
  353. {
  354. field.SetValue(source, value);
  355. }
  356. }
  357. public static void SetReflectionProperty(object source, string name, object value)
  358. {
  359. var property = source.GetType().GetProperty(name, Tools.FullBinding);
  360. if (property != null)
  361. {
  362. property.GetSetMethod(true).Invoke(source, new object[] { value });
  363. }
  364. }
  365. public static void CallReflectionMethod(object source, string method, params object[] args)
  366. {
  367. Tools.CallReflectionMethod<object>(source, method, args);
  368. }
  369. public static T CallReflectionMethod<T>(object source, string method, params object[] args)
  370. {
  371. object result = null;
  372. var caller = source.GetType().GetMethod(method, Tools.FullBinding);
  373. if (caller != null)
  374. {
  375. result = caller.Invoke(source, args);
  376. }
  377. return (T)result;
  378. }
  379. public static T GetStaticReflectionField<T>(Type type, string name)
  380. {
  381. object result = null;
  382. var field = type.GetField(name, Tools.FullBinding);
  383. if (field != null)
  384. {
  385. result = field.GetValue(null);
  386. }
  387. return (T)result;
  388. }
  389. public static T GetStaticReflectionProperty<T>(Type type, string name)
  390. {
  391. object result = null;
  392. var property = type.GetProperty(name, Tools.FullBinding);
  393. if (property != null)
  394. {
  395. result = property.GetGetMethod(true).Invoke(null, null);
  396. }
  397. return (T)result;
  398. }
  399. public static void SetStaticReflectionField(Type type, string name, object value)
  400. {
  401. var field = type.GetField(name, Tools.FullBinding);
  402. if (field != null)
  403. {
  404. field.SetValue(null, value);
  405. }
  406. }
  407. public static void SetStaticReflectionProperty(Type type, string name, object value)
  408. {
  409. var property = type.GetProperty(name, Tools.FullBinding);
  410. if (property != null)
  411. {
  412. property.GetSetMethod(true).Invoke(null, new object[] { value });
  413. }
  414. }
  415. public static void CallStaticReflectionMethod(Type type, string method, params object[] args)
  416. {
  417. Tools.CallStaticReflectionMethod<object>(type, method, args);
  418. }
  419. public static T CallStaticReflectionMethod<T>(Type type, string method, params object[] args)
  420. {
  421. object result = null;
  422. var caller = type.GetMethod(method, Tools.FullBinding);
  423. if (caller != null)
  424. {
  425. result = caller.Invoke(null, args);
  426. }
  427. return (T)result;
  428. }
  429. public static Type GetTypeFromAllAssemblies(string typeName)
  430. {
  431. Assembly[] assemblies = System.AppDomain.CurrentDomain.GetAssemblies();
  432. foreach (Assembly assembly in assemblies)
  433. {
  434. Type[] types = assembly.GetTypes();
  435. foreach (Type type in types)
  436. {
  437. if (type.Name.Equals(typeName, StringComparison.CurrentCultureIgnoreCase) || type.Name.Contains('+' + typeName)) //+ check for inline classes
  438. return type;
  439. }
  440. }
  441. return null;
  442. }
  443. public static Mesh CreateBoxMesh(float x = 1f, float y = 1f, float z = 1f)
  444. {
  445. Mesh result = new Mesh();
  446. float length = x;
  447. float width = y;
  448. float height = z;
  449. // Vertices
  450. Vector3 p0 = new Vector3(-length * .5f, -width * .5f, height * .5f);
  451. Vector3 p1 = new Vector3(length * .5f, -width * .5f, height * .5f);
  452. Vector3 p2 = new Vector3(length * .5f, -width * .5f, -height * .5f);
  453. Vector3 p3 = new Vector3(-length * .5f, -width * .5f, -height * .5f);
  454. Vector3 p4 = new Vector3(-length * .5f, width * .5f, height * .5f);
  455. Vector3 p5 = new Vector3(length * .5f, width * .5f, height * .5f);
  456. Vector3 p6 = new Vector3(length * .5f, width * .5f, -height * .5f);
  457. Vector3 p7 = new Vector3(-length * .5f, width * .5f, -height * .5f);
  458. Vector3[] vertices = new Vector3[] {
  459. // Bottom
  460. p0, p1, p2, p3,
  461. // Left
  462. p7, p4, p0, p3,
  463. // Front
  464. p4, p5, p1, p0,
  465. // Back
  466. p6, p7, p3, p2,
  467. // Right
  468. p5, p6, p2, p1,
  469. // Top
  470. p7, p6, p5, p4
  471. };
  472. // Normales
  473. Vector3 up = Vector3.up;
  474. Vector3 down = Vector3.down;
  475. Vector3 front = Vector3.forward;
  476. Vector3 back = Vector3.back;
  477. Vector3 left = Vector3.left;
  478. Vector3 right = Vector3.right;
  479. Vector3[] normales = new Vector3[] {
  480. // Bottom
  481. down, down, down, down,
  482. // Left
  483. left, left, left, left,
  484. // Front
  485. front, front, front, front,
  486. // Back
  487. back, back, back, back,
  488. // Right
  489. right, right, right, right,
  490. // Top
  491. up, up, up, up
  492. };
  493. // UVs
  494. Vector2 _00 = new Vector2(0f, 0f);
  495. Vector2 _10 = new Vector2(1f, 0f);
  496. Vector2 _01 = new Vector2(0f, 1f);
  497. Vector2 _11 = new Vector2(1f, 1f);
  498. Vector2[] uvs = new Vector2[] {
  499. // Bottom
  500. _11, _01, _00, _10,
  501. // Left
  502. _11, _01, _00, _10,
  503. // Front
  504. _11, _01, _00, _10,
  505. // Back
  506. _11, _01, _00, _10,
  507. // Right
  508. _11, _01, _00, _10,
  509. // Top
  510. _11, _01, _00, _10,
  511. };
  512. // Triangles
  513. int[] triangles = new int[] {
  514. // Bottom
  515. 3, 1, 0,
  516. 3, 2, 1,
  517. // Left
  518. 3 + 4 * 1, 1 + 4 * 1, 0 + 4 * 1,
  519. 3 + 4 * 1, 2 + 4 * 1, 1 + 4 * 1,
  520. // Front
  521. 3 + 4 * 2, 1 + 4 * 2, 0 + 4 * 2,
  522. 3 + 4 * 2, 2 + 4 * 2, 1 + 4 * 2,
  523. // Back
  524. 3 + 4 * 3, 1 + 4 * 3, 0 + 4 * 3,
  525. 3 + 4 * 3, 2 + 4 * 3, 1 + 4 * 3,
  526. // Right
  527. 3 + 4 * 4, 1 + 4 * 4, 0 + 4 * 4,
  528. 3 + 4 * 4, 2 + 4 * 4, 1 + 4 * 4,
  529. // Top
  530. 3 + 4 * 5, 1 + 4 * 5, 0 + 4 * 5,
  531. 3 + 4 * 5, 2 + 4 * 5, 1 + 4 * 5,
  532. };
  533. // Mesh Result
  534. result.vertices = vertices;
  535. result.normals = normales;
  536. result.uv = uvs;
  537. result.triangles = triangles;
  538. result.RecalculateBounds();
  539. return result;
  540. }
  541. public static Mesh CreateWheelMesh(float height = 1f, float radius = 0.5f, int segments = 24)
  542. {
  543. Mesh result = new Mesh();
  544. float topRadius = radius;
  545. float bottomRadius = radius;
  546. int nbSides = segments;
  547. int nbHeightSeg = 1; // Not implemented yet
  548. int nbVerticesCap = nbSides + 1;
  549. // Vertices
  550. // bottom + top + sides
  551. Vector3[] vertices = new Vector3[nbVerticesCap + nbVerticesCap + nbSides * nbHeightSeg * 2 + 2];
  552. int vert = 0;
  553. float _2pi = Mathf.PI * 2f;
  554. // Bottom cap
  555. vertices[vert++] = new Vector3(0f, 0f, 0f);
  556. while (vert <= nbSides)
  557. {
  558. float rad = (float)vert / nbSides * _2pi;
  559. vertices[vert] = new Vector3(Mathf.Cos(rad) * bottomRadius, 0f, Mathf.Sin(rad) * bottomRadius);
  560. vert++;
  561. }
  562. // Top cap
  563. vertices[vert++] = new Vector3(0f, height, 0f);
  564. while (vert <= nbSides * 2 + 1)
  565. {
  566. float rad = (float)(vert - nbSides - 1) / nbSides * _2pi;
  567. vertices[vert] = new Vector3(Mathf.Cos(rad) * topRadius, height, Mathf.Sin(rad) * topRadius);
  568. vert++;
  569. }
  570. // Sides
  571. int v = 0;
  572. while (vert <= vertices.Length - 4)
  573. {
  574. float rad = (float)v / nbSides * _2pi;
  575. vertices[vert] = new Vector3(Mathf.Cos(rad) * topRadius, height, Mathf.Sin(rad) * topRadius);
  576. vertices[vert + 1] = new Vector3(Mathf.Cos(rad) * bottomRadius, 0, Mathf.Sin(rad) * bottomRadius);
  577. vert += 2;
  578. v++;
  579. }
  580. vertices[vert] = vertices[nbSides * 2 + 2];
  581. vertices[vert + 1] = vertices[nbSides * 2 + 3];
  582. // Normales
  583. // bottom + top + sides
  584. Vector3[] normales = new Vector3[vertices.Length];
  585. vert = 0;
  586. // Bottom cap
  587. while (vert <= nbSides)
  588. {
  589. normales[vert++] = Vector3.down;
  590. }
  591. // Top cap
  592. while (vert <= nbSides * 2 + 1)
  593. {
  594. normales[vert++] = Vector3.up;
  595. }
  596. // Sides
  597. v = 0;
  598. while (vert <= vertices.Length - 4)
  599. {
  600. float rad = (float)v / nbSides * _2pi;
  601. float cos = Mathf.Cos(rad);
  602. float sin = Mathf.Sin(rad);
  603. normales[vert] = new Vector3(cos, 0f, sin);
  604. normales[vert + 1] = normales[vert];
  605. vert += 2;
  606. v++;
  607. }
  608. normales[vert] = normales[nbSides * 2 + 2];
  609. normales[vert + 1] = normales[nbSides * 2 + 3];
  610. // UVs
  611. Vector2[] uvs = new Vector2[vertices.Length];
  612. // Bottom cap
  613. int u = 0;
  614. uvs[u++] = new Vector2(0.5f, 0.5f);
  615. while (u <= nbSides)
  616. {
  617. float rad = (float)u / nbSides * _2pi;
  618. uvs[u] = new Vector2(Mathf.Cos(rad) * .5f + .5f, Mathf.Sin(rad) * .5f + .5f);
  619. u++;
  620. }
  621. // Top cap
  622. uvs[u++] = new Vector2(0.5f, 0.5f);
  623. while (u <= nbSides * 2 + 1)
  624. {
  625. float rad = (float)u / nbSides * _2pi;
  626. uvs[u] = new Vector2(Mathf.Cos(rad) * .5f + .5f, Mathf.Sin(rad) * .5f + .5f);
  627. u++;
  628. }
  629. // Sides
  630. int u_sides = 0;
  631. while (u <= uvs.Length - 4)
  632. {
  633. float t = (float)u_sides / nbSides;
  634. uvs[u] = new Vector3(t, 1f);
  635. uvs[u + 1] = new Vector3(t, 0f);
  636. u += 2;
  637. u_sides++;
  638. }
  639. uvs[u] = new Vector2(1f, 1f);
  640. uvs[u + 1] = new Vector2(1f, 0f);
  641. // Triangles
  642. int nbTriangles = nbSides + nbSides + nbSides * 2;
  643. int[] triangles = new int[nbTriangles * 3 + 3];
  644. // Bottom cap
  645. int tri = 0;
  646. int i = 0;
  647. while (tri < nbSides - 1)
  648. {
  649. triangles[i] = 0;
  650. triangles[i + 1] = tri + 1;
  651. triangles[i + 2] = tri + 2;
  652. tri++;
  653. i += 3;
  654. }
  655. triangles[i] = 0;
  656. triangles[i + 1] = tri + 1;
  657. triangles[i + 2] = 1;
  658. tri++;
  659. i += 3;
  660. // Top cap
  661. //tri++;
  662. while (tri < nbSides * 2)
  663. {
  664. triangles[i] = tri + 2;
  665. triangles[i + 1] = tri + 1;
  666. triangles[i + 2] = nbVerticesCap;
  667. tri++;
  668. i += 3;
  669. }
  670. triangles[i] = nbVerticesCap + 1;
  671. triangles[i + 1] = tri + 1;
  672. triangles[i + 2] = nbVerticesCap;
  673. tri++;
  674. i += 3;
  675. tri++;
  676. // Sides
  677. while (tri <= nbTriangles)
  678. {
  679. triangles[i] = tri + 2;
  680. triangles[i + 1] = tri + 1;
  681. triangles[i + 2] = tri + 0;
  682. tri++;
  683. i += 3;
  684. triangles[i] = tri + 1;
  685. triangles[i + 1] = tri + 2;
  686. triangles[i + 2] = tri + 0;
  687. tri++;
  688. i += 3;
  689. }
  690. // Mesh Result
  691. result.vertices = vertices;
  692. result.normals = normales;
  693. result.uv = uvs;
  694. result.triangles = triangles;
  695. result.RecalculateBounds();
  696. return result;
  697. }
  698. public static Mesh CreateSphereMesh(float radius = 0.5f, int segments = 24)
  699. {
  700. Mesh result = new Mesh();
  701. // Longitude |||
  702. int nbLong = segments; //24;
  703. // Latitude ---
  704. int nbLat = segments; //16;
  705. // Vertices
  706. Vector3[] vertices = new Vector3[(nbLong + 1) * nbLat + 2];
  707. float _pi = Mathf.PI;
  708. float _2pi = _pi * 2f;
  709. vertices[0] = Vector3.up * radius;
  710. for (int lat = 0; lat < nbLat; lat++)
  711. {
  712. float a1 = _pi * (float)(lat + 1) / (nbLat + 1);
  713. float sin1 = Mathf.Sin(a1);
  714. float cos1 = Mathf.Cos(a1);
  715. for (int lon = 0; lon <= nbLong; lon++)
  716. {
  717. float a2 = _2pi * (float)(lon == nbLong ? 0 : lon) / nbLong;
  718. float sin2 = Mathf.Sin(a2);
  719. float cos2 = Mathf.Cos(a2);
  720. vertices[lon + lat * (nbLong + 1) + 1] = new Vector3(sin1 * cos2, cos1, sin1 * sin2) * radius;
  721. }
  722. }
  723. vertices[vertices.Length - 1] = Vector3.up * -radius;
  724. // Normales
  725. Vector3[] normales = new Vector3[vertices.Length];
  726. for (int n = 0; n < vertices.Length; n++)
  727. {
  728. normales[n] = vertices[n].normalized;
  729. }
  730. // UVs
  731. Vector2[] uvs = new Vector2[vertices.Length];
  732. uvs[0] = Vector2.up;
  733. uvs[uvs.Length - 1] = Vector2.zero;
  734. for (int lat = 0; lat < nbLat; lat++)
  735. {
  736. for (int lon = 0; lon <= nbLong; lon++)
  737. {
  738. uvs[lon + lat * (nbLong + 1) + 1] = new Vector2((float)lon / nbLong, 1f - (float)(lat + 1) / (nbLat + 1));
  739. }
  740. }
  741. // Triangles
  742. int nbFaces = vertices.Length;
  743. int nbTriangles = nbFaces * 2;
  744. int nbIndexes = nbTriangles * 3;
  745. int[] triangles = new int[nbIndexes];
  746. // Top Cap
  747. int i = 0;
  748. for (int lon = 0; lon < nbLong; lon++)
  749. {
  750. triangles[i++] = lon + 2;
  751. triangles[i++] = lon + 1;
  752. triangles[i++] = 0;
  753. }
  754. // Middle
  755. for (int lat = 0; lat < nbLat - 1; lat++)
  756. {
  757. for (int lon = 0; lon < nbLong; lon++)
  758. {
  759. int current = lon + lat * (nbLong + 1) + 1;
  760. int next = current + nbLong + 1;
  761. triangles[i++] = current;
  762. triangles[i++] = current + 1;
  763. triangles[i++] = next + 1;
  764. triangles[i++] = current;
  765. triangles[i++] = next + 1;
  766. triangles[i++] = next;
  767. }
  768. }
  769. //Bottom Cap
  770. for (int lon = 0; lon < nbLong; lon++)
  771. {
  772. triangles[i++] = vertices.Length - 1;
  773. triangles[i++] = vertices.Length - (lon + 2) - 1;
  774. triangles[i++] = vertices.Length - (lon + 1) - 1;
  775. }
  776. // Mesh Result
  777. result.vertices = vertices;
  778. result.normals = normales;
  779. result.uv = uvs;
  780. result.triangles = triangles;
  781. result.RecalculateBounds();
  782. return result;
  783. }
  784. public static Mesh CreateCapsuleMesh(float height = 2f, float radius = 0.5f, int segments = 24)
  785. {
  786. Mesh result = new Mesh();
  787. // Make segments an even number
  788. if (segments % 2 != 0)
  789. {
  790. segments++;
  791. }
  792. // Extra vertex on the seam
  793. int points = segments + 1;
  794. // Calculate points around a circle
  795. float[] pX = new float[points];
  796. float[] pZ = new float[points];
  797. float[] pY = new float[points];
  798. float[] pR = new float[points];
  799. float calcH = 0f;
  800. float calcV = 0f;
  801. for (int i = 0; i < points; i++)
  802. {
  803. pX[i] = Mathf.Sin(calcH * Mathf.Deg2Rad);
  804. pZ[i] = Mathf.Cos(calcH * Mathf.Deg2Rad);
  805. pY[i] = Mathf.Cos(calcV * Mathf.Deg2Rad);
  806. pR[i] = Mathf.Sin(calcV * Mathf.Deg2Rad);
  807. calcH += 360f / (float)segments;
  808. calcV += 180f / (float)segments;
  809. }
  810. // Vertices and UVs
  811. Vector3[] vertices = new Vector3[points * (points + 1)];
  812. Vector2[] uvs = new Vector2[vertices.Length];
  813. int ind = 0;
  814. // Y-Offset is half the height minus the diameter
  815. float yOff = (height - (radius * 2f)) * 0.5f;
  816. if (yOff < 0) yOff = 0;
  817. // UV Calculations
  818. float stepX = 1f / ((float)(points - 1));
  819. float uvX, uvY;
  820. // Top Hemisphere
  821. int top = Mathf.CeilToInt((float)points * 0.5f);
  822. for (int y = 0; y < top; y++)
  823. {
  824. for (int x = 0; x < points; x++)
  825. {
  826. vertices[ind] = new Vector3(pX[x] * pR[y], pY[y], pZ[x] * pR[y]) * radius;
  827. vertices[ind].y = yOff + vertices[ind].y;
  828. uvX = 1f - (stepX * (float)x);
  829. uvY = (vertices[ind].y + (height * 0.5f)) / height;
  830. uvs[ind] = new Vector2(uvX, uvY);
  831. ind++;
  832. }
  833. }
  834. // Bottom Hemisphere
  835. int btm = Mathf.FloorToInt((float)points * 0.5f);
  836. for (int y = btm; y < points; y++)
  837. {
  838. for (int x = 0; x < points; x++)
  839. {
  840. vertices[ind] = new Vector3(pX[x] * pR[y], pY[y], pZ[x] * pR[y]) * radius;
  841. vertices[ind].y = -yOff + vertices[ind].y;
  842. uvX = 1f - (stepX * (float)x);
  843. uvY = (vertices[ind].y + (height * 0.5f)) / height;
  844. uvs[ind] = new Vector2(uvX, uvY);
  845. ind++;
  846. }
  847. }
  848. // Triangles
  849. int[] triangles = new int[(segments * (segments + 1) * 2 * 3)];
  850. for (int y = 0, t = 0; y < segments + 1; y++)
  851. {
  852. for (int x = 0; x < segments; x++, t += 6)
  853. {
  854. triangles[t + 0] = ((y + 0) * (segments + 1)) + x + 0;
  855. triangles[t + 1] = ((y + 1) * (segments + 1)) + x + 0;
  856. triangles[t + 2] = ((y + 1) * (segments + 1)) + x + 1;
  857. triangles[t + 3] = ((y + 0) * (segments + 1)) + x + 1;
  858. triangles[t + 4] = ((y + 0) * (segments + 1)) + x + 0;
  859. triangles[t + 5] = ((y + 1) * (segments + 1)) + x + 1;
  860. }
  861. }
  862. // Mesh Result
  863. result.vertices = vertices;
  864. result.uv = uvs;
  865. result.triangles = triangles;
  866. result.RecalculateBounds();
  867. result.RecalculateNormals();
  868. return result;
  869. }
  870. public static BabylonTerrainData CreateTerrainData(TerrainData terrain, int resolution, Vector3 position, bool invert = false)
  871. {
  872. BabylonTerrainData result = new BabylonTerrainData();
  873. int w = terrain.heightmapWidth;
  874. int h = terrain.heightmapHeight;
  875. Vector3 meshScale = terrain.size;
  876. int tRes = (int)Mathf.Pow(2, resolution);
  877. meshScale = new Vector3(meshScale.x / (w - 1) * tRes, meshScale.y, meshScale.z / (h - 1) * tRes);
  878. Vector2 uvScale = new Vector2(1.0f / (w - 1), 1.0f / (h - 1));
  879. float[,] tData = terrain.GetHeights(0, 0, w, h);
  880. w = (w - 1) / tRes + 1;
  881. h = (h - 1) / tRes + 1;
  882. result.vertices = new Vector3[w * h];
  883. result.normals = new Vector3[w * h];
  884. result.uvs = new Vector2[w * h];
  885. result.triangles = new int[(w - 1) * (h - 1) * 6];
  886. // Build vertices and UVs
  887. for (int y = 0; y < h; y++)
  888. {
  889. for (int x = 0; x < w; x++)
  890. {
  891. if (invert)
  892. {
  893. result.vertices[x * w + y] = Vector3.Scale(meshScale, new Vector3(y, tData[x * tRes, y * tRes], x)) + position;
  894. result.normals[x * w + y] = new Vector3(0, 0, 0);
  895. result.uvs[x * w + y] = Vector2.Scale(new Vector2(x * tRes, y * tRes), uvScale);
  896. }
  897. else
  898. {
  899. result.vertices[y * w + x] = Vector3.Scale(meshScale, new Vector3(-y, tData[x * tRes, y * tRes], x)) + position;
  900. result.normals[y * w + x] = new Vector3(0, 0, 0);
  901. result.uvs[y * w + x] = Vector2.Scale(new Vector2(x * tRes, y * tRes), uvScale);
  902. }
  903. }
  904. }
  905. int index = 0;
  906. // Build triangle indices: 3 indices into vertex array for each triangle
  907. for (int y = 0; y < h - 1; y++)
  908. {
  909. for (int x = 0; x < w - 1; x++)
  910. {
  911. // For each grid cell output two triangles
  912. result.triangles[index++] = (y * w) + x;
  913. result.triangles[index++] = ((y + 1) * w) + x;
  914. result.triangles[index++] = (y * w) + x + 1;
  915. result.triangles[index++] = ((y + 1) * w) + x;
  916. result.triangles[index++] = ((y + 1) * w) + x + 1;
  917. result.triangles[index++] = (y * w) + x + 1;
  918. }
  919. }
  920. return result;
  921. }
  922. public static void GenerateBabylonMeshData(Mesh mesh, BabylonMesh babylonMesh, BabylonScene babylonScene = null, Transform transform = null)
  923. {
  924. int index = 0;
  925. babylonMesh.positions = new float[mesh.vertexCount * 3];
  926. foreach (Vector3 vv in mesh.vertices)
  927. {
  928. babylonMesh.positions[index * 3] = vv.x;
  929. babylonMesh.positions[(index * 3) + 1] = vv.y;
  930. babylonMesh.positions[(index * 3) + 2] = vv.z;
  931. if (babylonScene != null && transform != null)
  932. {
  933. // Computing world extends
  934. Vector3 worldPosition = transform.TransformPoint(vv);
  935. if (worldPosition.x > babylonScene.MaxVector.X)
  936. {
  937. babylonScene.MaxVector.X = worldPosition.x;
  938. }
  939. if (worldPosition.y > babylonScene.MaxVector.Y)
  940. {
  941. babylonScene.MaxVector.Y = worldPosition.y;
  942. }
  943. if (worldPosition.z > babylonScene.MaxVector.Z)
  944. {
  945. babylonScene.MaxVector.Z = worldPosition.z;
  946. }
  947. if (worldPosition.x < babylonScene.MinVector.X)
  948. {
  949. babylonScene.MinVector.X = worldPosition.x;
  950. }
  951. if (worldPosition.y < babylonScene.MinVector.Y)
  952. {
  953. babylonScene.MinVector.Y = worldPosition.y;
  954. }
  955. if (worldPosition.z < babylonScene.MinVector.Z)
  956. {
  957. babylonScene.MinVector.Z = worldPosition.z;
  958. }
  959. }
  960. index++;
  961. }
  962. index = 0;
  963. babylonMesh.normals = new float[mesh.vertexCount * 3];
  964. foreach (Vector3 nn in mesh.normals)
  965. {
  966. babylonMesh.normals[index * 3] = nn.x;
  967. babylonMesh.normals[(index * 3) + 1] = nn.y;
  968. babylonMesh.normals[(index * 3) + 2] = nn.z;
  969. index++;
  970. }
  971. index = 0;
  972. babylonMesh.uvs = new float[mesh.vertexCount * 2];
  973. foreach (Vector3 v in mesh.uv)
  974. {
  975. babylonMesh.uvs[index * 2] = v.x;
  976. babylonMesh.uvs[(index * 2) + 1] = v.y;
  977. index++;
  978. }
  979. index = 0;
  980. babylonMesh.uvs2 = new float[mesh.vertexCount * 2];
  981. if (mesh.uv2 != null && mesh.uv2.Length > 0)
  982. {
  983. index = 0;
  984. foreach (Vector3 v in mesh.uv2)
  985. {
  986. babylonMesh.uvs2[index * 2] = v.x;
  987. babylonMesh.uvs2[(index * 2) + 1] = v.y;
  988. index++;
  989. }
  990. }
  991. else
  992. {
  993. index = 0;
  994. foreach (Vector3 v in mesh.uv)
  995. {
  996. babylonMesh.uvs2[index * 2] = v.x;
  997. babylonMesh.uvs2[(index * 2) + 1] = v.y;
  998. index++;
  999. }
  1000. }
  1001. index = 0;
  1002. int loop = 0;
  1003. babylonMesh.indices = new int[mesh.triangles.Length];
  1004. List<Vector3> vectors = new List<Vector3>();
  1005. Vector3 vector = new Vector3(0, 0, 0);
  1006. foreach (int poly in mesh.triangles)
  1007. {
  1008. if (loop == 0)
  1009. {
  1010. vector = new Vector3(0, 0, 0);
  1011. vector.z = poly;
  1012. }
  1013. else if (loop == 1)
  1014. {
  1015. vector.y = poly;
  1016. }
  1017. else if (loop == 2)
  1018. {
  1019. vector.x = poly;
  1020. vectors.Add(vector);
  1021. }
  1022. loop++;
  1023. if (loop >= 3) loop = 0;
  1024. }
  1025. index = 0;
  1026. foreach (Vector3 vvv in vectors)
  1027. {
  1028. babylonMesh.indices[index * 3] = (int)vvv.x;
  1029. babylonMesh.indices[(index * 3) + 1] = (int)vvv.y;
  1030. babylonMesh.indices[(index * 3) + 2] = (int)vvv.z;
  1031. index++;
  1032. }
  1033. }
  1034. public static void GenerateBabylonMeshTerrainData(BabylonTerrainData terrainData, BabylonMesh babylonMesh, bool reverseNormals = false, BabylonScene babylonScene = null, Transform transform = null)
  1035. {
  1036. int index = 0;
  1037. babylonMesh.positions = new float[terrainData.vertices.Length * 3];
  1038. foreach (Vector3 vv in terrainData.vertices)
  1039. {
  1040. babylonMesh.positions[index * 3] = vv.x;
  1041. babylonMesh.positions[(index * 3) + 1] = vv.y;
  1042. babylonMesh.positions[(index * 3) + 2] = vv.z;
  1043. if (babylonScene != null && transform != null)
  1044. {
  1045. // Computing world extends
  1046. Vector3 worldPosition = transform.TransformPoint(vv);
  1047. if (worldPosition.x > babylonScene.MaxVector.X)
  1048. {
  1049. babylonScene.MaxVector.X = worldPosition.x;
  1050. }
  1051. if (worldPosition.y > babylonScene.MaxVector.Y)
  1052. {
  1053. babylonScene.MaxVector.Y = worldPosition.y;
  1054. }
  1055. if (worldPosition.z > babylonScene.MaxVector.Z)
  1056. {
  1057. babylonScene.MaxVector.Z = worldPosition.z;
  1058. }
  1059. if (worldPosition.x < babylonScene.MinVector.X)
  1060. {
  1061. babylonScene.MinVector.X = worldPosition.x;
  1062. }
  1063. if (worldPosition.y < babylonScene.MinVector.Y)
  1064. {
  1065. babylonScene.MinVector.Y = worldPosition.y;
  1066. }
  1067. if (worldPosition.z < babylonScene.MinVector.Z)
  1068. {
  1069. babylonScene.MinVector.Z = worldPosition.z;
  1070. }
  1071. }
  1072. index++;
  1073. }
  1074. index = 0;
  1075. babylonMesh.normals = new float[terrainData.vertices.Length * 3];
  1076. foreach (Vector3 nn in terrainData.normals)
  1077. {
  1078. babylonMesh.normals[index * 3] = nn.x;
  1079. babylonMesh.normals[(index * 3) + 1] = nn.y;
  1080. babylonMesh.normals[(index * 3) + 2] = nn.z;
  1081. index++;
  1082. }
  1083. index = 0;
  1084. babylonMesh.uvs = new float[terrainData.vertices.Length * 2];
  1085. foreach (Vector3 v in terrainData.uvs)
  1086. {
  1087. babylonMesh.uvs[index * 2] = v.x;
  1088. babylonMesh.uvs[(index * 2) + 1] = v.y;
  1089. index++;
  1090. }
  1091. index = 0;
  1092. babylonMesh.uvs2 = new float[terrainData.vertices.Length * 2];
  1093. foreach (Vector3 v in terrainData.uvs)
  1094. {
  1095. babylonMesh.uvs2[index * 2] = v.x;
  1096. babylonMesh.uvs2[(index * 2) + 1] = v.y;
  1097. index++;
  1098. }
  1099. index = 0;
  1100. int loop = 0;
  1101. babylonMesh.indices = new int[terrainData.triangles.Length];
  1102. List<Vector3> vectors = new List<Vector3>();
  1103. Vector3 vector = new Vector3(0, 0, 0);
  1104. foreach (int poly in terrainData.triangles)
  1105. {
  1106. if (loop == 0)
  1107. {
  1108. vector = new Vector3(0, 0, 0);
  1109. vector.z = poly;
  1110. }
  1111. else if (loop == 1)
  1112. {
  1113. vector.y = poly;
  1114. }
  1115. else if (loop == 2)
  1116. {
  1117. vector.x = poly;
  1118. vectors.Add(vector);
  1119. }
  1120. loop++;
  1121. if (loop >= 3) loop = 0;
  1122. }
  1123. index = 0;
  1124. foreach (Vector3 vvv in vectors)
  1125. {
  1126. babylonMesh.indices[index * 3] = (int)vvv.x;
  1127. babylonMesh.indices[(index * 3) + 1] = (int)vvv.y;
  1128. babylonMesh.indices[(index * 3) + 2] = (int)vvv.z;
  1129. index++;
  1130. }
  1131. Tools.RecalculateMeshNormals(babylonMesh, reverseNormals);
  1132. }
  1133. public static void RecalculateMeshNormals(BabylonMesh mesh, bool flip = false)
  1134. {
  1135. int index = 0;
  1136. float p1p2x = 0.0f;
  1137. float p1p2y = 0.0f;
  1138. float p1p2z = 0.0f;
  1139. float p3p2x = 0.0f;
  1140. float p3p2y = 0.0f;
  1141. float p3p2z = 0.0f;
  1142. float faceNormalx = 0.0f;
  1143. float faceNormaly = 0.0f;
  1144. float faceNormalz = 0.0f;
  1145. float length = 0.0f;
  1146. int i1 = 0;
  1147. int i2 = 0;
  1148. int i3 = 0;
  1149. // indice triplet = 1 face
  1150. var nbFaces = mesh.indices.Length / 3;
  1151. for (index = 0; index < nbFaces; index++)
  1152. {
  1153. i1 = mesh.indices[index * 3]; // get the indexes of each vertex of the face
  1154. i2 = mesh.indices[index * 3 + 1];
  1155. i3 = mesh.indices[index * 3 + 2];
  1156. p1p2x = mesh.positions[i1 * 3] - mesh.positions[i2 * 3]; // compute two vectors per face
  1157. p1p2y = mesh.positions[i1 * 3 + 1] - mesh.positions[i2 * 3 + 1];
  1158. p1p2z = mesh.positions[i1 * 3 + 2] - mesh.positions[i2 * 3 + 2];
  1159. p3p2x = mesh.positions[i3 * 3] - mesh.positions[i2 * 3];
  1160. p3p2y = mesh.positions[i3 * 3 + 1] - mesh.positions[i2 * 3 + 1];
  1161. p3p2z = mesh.positions[i3 * 3 + 2] - mesh.positions[i2 * 3 + 2];
  1162. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  1163. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  1164. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  1165. length = (float)Math.Sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  1166. length = (length == 0) ? 1.0f : length;
  1167. faceNormalx /= length; // normalize this normal
  1168. faceNormaly /= length;
  1169. faceNormalz /= length;
  1170. mesh.normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  1171. mesh.normals[i1 * 3 + 1] += faceNormaly;
  1172. mesh.normals[i1 * 3 + 2] += faceNormalz;
  1173. mesh.normals[i2 * 3] += faceNormalx;
  1174. mesh.normals[i2 * 3 + 1] += faceNormaly;
  1175. mesh.normals[i2 * 3 + 2] += faceNormalz;
  1176. mesh.normals[i3 * 3] += faceNormalx;
  1177. mesh.normals[i3 * 3 + 1] += faceNormaly;
  1178. mesh.normals[i3 * 3 + 2] += faceNormalz;
  1179. }
  1180. // last normalization of each normal
  1181. float flipValue = (flip) ? -1.0f : 1.0f;
  1182. for (index = 0; index < mesh.normals.Length / 3; index++)
  1183. {
  1184. faceNormalx = mesh.normals[index * 3];
  1185. faceNormaly = mesh.normals[index * 3 + 1];
  1186. faceNormalz = mesh.normals[index * 3 + 2];
  1187. length = (float)Math.Sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  1188. length = (length == 0) ? 1.0f : length;
  1189. faceNormalx /= length;
  1190. faceNormaly /= length;
  1191. faceNormalz /= length;
  1192. mesh.normals[index * 3] = (faceNormalx * flipValue);
  1193. mesh.normals[index * 3 + 1] = (faceNormaly * flipValue);
  1194. mesh.normals[index * 3 + 2] = (faceNormalz * flipValue);
  1195. }
  1196. // flip triangles for all normals
  1197. if (flip)
  1198. {
  1199. int[] triangles = mesh.indices;
  1200. for (int i = 0; i < triangles.Length; i += 3)
  1201. {
  1202. int temp = triangles[i + 0];
  1203. triangles[i + 0] = triangles[i + 1];
  1204. triangles[i + 1] = temp;
  1205. }
  1206. mesh.indices = triangles;
  1207. }
  1208. }
  1209. public static EditorWindow GetAssetStoreWindow()
  1210. {
  1211. EditorWindow result = null;
  1212. Type AssetWindowType = typeof(EditorWindow).Assembly.GetType("UnityEditor.AssetStoreWindow");
  1213. if (AssetWindowType != null)
  1214. {
  1215. result = (EditorWindow)AssetWindowType.GetMethod("Init", Tools.FullBinding).Invoke(null, null);
  1216. }
  1217. return result;
  1218. }
  1219. public static EditorWindow AttachToAssetStoreWindow(string title, string url)
  1220. {
  1221. EditorWindow result = null;
  1222. EditorWindow assetStore = GetAssetStoreWindow();
  1223. if (assetStore != null)
  1224. {
  1225. object webView = Unity3D2Babylon.Tools.GetInstanceField(assetStore.GetType(), assetStore, "webView");
  1226. if (webView != null)
  1227. {
  1228. if (!String.IsNullOrEmpty(url))
  1229. {
  1230. webView.GetType().GetMethod("LoadURL", Tools.FullBinding).Invoke(webView, new object[] { url });
  1231. result = assetStore;
  1232. if (!String.IsNullOrEmpty(title))
  1233. {
  1234. assetStore.titleContent.text = title;
  1235. }
  1236. }
  1237. }
  1238. assetStore.Show();
  1239. }
  1240. return result;
  1241. }
  1242. public static string GetDefaultTypeScriptPath()
  1243. {
  1244. string result = "tsc";
  1245. if (Application.platform == RuntimePlatform.OSXEditor)
  1246. {
  1247. result = "/usr/local/bin/tsc";
  1248. }
  1249. else if (Application.platform == RuntimePlatform.WindowsEditor)
  1250. {
  1251. result = "C:/Program Files/nodejs/node_modules/typescript/bin/tsc";
  1252. }
  1253. return result;
  1254. }
  1255. public static string GetDefaultNodeRuntimePath()
  1256. {
  1257. string result = "node";
  1258. if (Application.platform == RuntimePlatform.OSXEditor)
  1259. {
  1260. result = "/usr/local/bin/node";
  1261. }
  1262. else if (Application.platform == RuntimePlatform.WindowsEditor)
  1263. {
  1264. result = "C:/Program Files/nodejs/node.exe";
  1265. }
  1266. return result;
  1267. }
  1268. public static string FormatProjectJavaScript(string buildFolder, string outputFile)
  1269. {
  1270. string javascriptFile = outputFile + ".js";
  1271. if (File.Exists(javascriptFile))
  1272. {
  1273. try
  1274. {
  1275. File.Delete(javascriptFile);
  1276. }
  1277. catch (Exception ex1)
  1278. {
  1279. UnityEngine.Debug.LogException(ex1);
  1280. }
  1281. }
  1282. if (File.Exists(javascriptFile))
  1283. {
  1284. UnityEngine.Debug.LogError("Failed to clear build file: " + javascriptFile);
  1285. }
  1286. return javascriptFile;
  1287. }
  1288. public static void GenerateProjectIndexPage(string project, bool debug, string scenePath, string sceneFilename, string scriptPath, string projectScript)
  1289. {
  1290. string responseText = String.Empty;
  1291. string previewLibrary = Path.Combine(Application.dataPath, "Babylon/Library/");
  1292. string previewTemplate = Path.Combine(Application.dataPath, "Babylon/Templates/Config/Index.html");
  1293. if (!String.IsNullOrEmpty(previewTemplate) && File.Exists(previewTemplate))
  1294. {
  1295. responseText = File.ReadAllText(previewTemplate);
  1296. }
  1297. string scripts = Path.Combine(project, scriptPath);
  1298. string[] libs = Directory.GetFiles(previewLibrary, "*.bjs");
  1299. if (libs != null && libs.Length > 0)
  1300. {
  1301. foreach (string lib in libs)
  1302. {
  1303. string script = Path.Combine(scripts, (Path.GetFileNameWithoutExtension(lib) + ".js"));
  1304. try
  1305. {
  1306. File.Copy(lib, script, true);
  1307. }
  1308. catch (Exception ex0)
  1309. {
  1310. UnityEngine.Debug.LogException(ex0);
  1311. }
  1312. }
  1313. }
  1314. responseText = responseText.Replace("###PROJECT###", projectScript);
  1315. responseText = responseText.Replace("###TITLE###", Application.productName);
  1316. responseText = responseText.Replace("###SCENE###", sceneFilename);
  1317. responseText = responseText.Replace("###DEBUG###", debug.ToString().ToLower());
  1318. responseText = responseText.Replace("###SCRIPT###", scriptPath.TrimStart('/').TrimEnd('/').ToLower());
  1319. responseText = responseText.Replace("###PATH###", scenePath.TrimStart('/').TrimEnd('/').ToLower());
  1320. string page = Path.Combine(project, "Index.html");
  1321. File.WriteAllText(page, responseText);
  1322. }
  1323. public static void BuildProjectJavaScript(string buildFolder, string outputFile, string javascriptFile)
  1324. {
  1325. StreamWriter streamWriter = new StreamWriter(new FileStream(javascriptFile, FileMode.Create, FileAccess.Write));
  1326. try
  1327. {
  1328. DefaultAsset[] assets = Tools.GetAssetsOfType<DefaultAsset>(".bjs");
  1329. if (assets != null && assets.Length > 0)
  1330. {
  1331. foreach (var asset in assets)
  1332. {
  1333. string path = AssetDatabase.GetAssetPath(asset);
  1334. if (!String.IsNullOrEmpty(path) && File.Exists(path))
  1335. {
  1336. if (path.IndexOf("/Babylon/Library/", StringComparison.OrdinalIgnoreCase) < 0)
  1337. {
  1338. string javascript = File.ReadAllText(path);
  1339. if (!String.IsNullOrEmpty(javascript))
  1340. {
  1341. string name = Path.GetFileName(path).Replace(".bjs", ".js");
  1342. string work = Path.Combine(buildFolder, name);
  1343. File.WriteAllText(work, javascript);
  1344. string jsminify = Tools.MinifyJavascriptCode(javascript);
  1345. if (!String.IsNullOrEmpty(jsminify))
  1346. {
  1347. streamWriter.Write(String.Format("// {0}\r\n", name));
  1348. streamWriter.Write(jsminify);
  1349. streamWriter.Write("\r\n\r\n");
  1350. }
  1351. }
  1352. }
  1353. }
  1354. }
  1355. }
  1356. }
  1357. catch (Exception ex2)
  1358. {
  1359. UnityEngine.Debug.LogException(ex2);
  1360. }
  1361. finally
  1362. {
  1363. streamWriter.Close();
  1364. }
  1365. }
  1366. public static int BuildProjectTypeScript(string nodePath, string tscPath, string buildFolder, string javascriptFile, string tsconfigJson = null)
  1367. {
  1368. int result = -1;
  1369. bool tscExists = (!String.IsNullOrEmpty(tscPath) && File.Exists(tscPath));
  1370. bool nodeExists = (!String.IsNullOrEmpty(nodePath) && File.Exists(nodePath));
  1371. if (nodeExists && tscExists)
  1372. {
  1373. string work = Path.Combine(buildFolder, Path.GetFileName(javascriptFile.Replace(".babylon", "")));
  1374. string root = Application.dataPath.Replace("/Assets", "");
  1375. string json = Path.Combine(root, "tsconfig.json");
  1376. string config = @" {
  1377. ""compilerOptions"": {
  1378. ""target"": ""ES5"",
  1379. ""module"": ""system"",
  1380. ""allowJs"": false,
  1381. ""declaration"": true,
  1382. ""outFile"": ""###OUTFILE###"",
  1383. ""sourceMap"": false
  1384. }
  1385. }";
  1386. if (String.IsNullOrEmpty(tsconfigJson))
  1387. {
  1388. tsconfigJson = config;
  1389. }
  1390. tsconfigJson = tsconfigJson.Replace("###OUTFILE###", Tools.FormatSafePath(work));
  1391. tsconfigJson = tsconfigJson.Replace("###OUTDIR###", Tools.FormatSafePath(buildFolder));
  1392. File.WriteAllText(json, tsconfigJson);
  1393. //* Execute typescript compiler
  1394. Process process = new Process();
  1395. process.StartInfo.FileName = nodePath;
  1396. process.StartInfo.Arguments = String.Format("{0} -p .", tscPath);
  1397. process.StartInfo.CreateNoWindow = true;
  1398. process.StartInfo.WorkingDirectory = root;
  1399. process.StartInfo.UseShellExecute = false;
  1400. process.StartInfo.RedirectStandardOutput = true;
  1401. process.StartInfo.RedirectStandardError = true;
  1402. //* Set ONLY ONE handler here.
  1403. process.ErrorDataReceived += new DataReceivedEventHandler(OnBuildProjectTypeScriptError);
  1404. //* Start process
  1405. process.Start();
  1406. //* Read one element asynchronously
  1407. process.BeginErrorReadLine();
  1408. //* Read the other one synchronously
  1409. string output = process.StandardOutput.ReadToEnd();
  1410. //* Log compiler output issues
  1411. if (!String.IsNullOrEmpty(output))
  1412. {
  1413. if (output.IndexOf("): error", StringComparison.OrdinalIgnoreCase) >= 0)
  1414. {
  1415. UnityEngine.Debug.LogError(output);
  1416. }
  1417. else
  1418. {
  1419. UnityEngine.Debug.LogWarning(output);
  1420. }
  1421. }
  1422. process.WaitForExit();
  1423. result = process.ExitCode;
  1424. if (result == 0)
  1425. {
  1426. //* Parse compiled output files
  1427. if (File.Exists(work))
  1428. {
  1429. string javascript = File.ReadAllText(work);
  1430. if (!String.IsNullOrEmpty(javascript))
  1431. {
  1432. UnityEngine.Debug.Log("Project typescript build successful.");
  1433. StreamWriter streamWriter = new StreamWriter(new FileStream(javascriptFile, FileMode.Append, FileAccess.Write));
  1434. try
  1435. {
  1436. string jsminify = Tools.MinifyJavascriptCode(javascript);
  1437. if (!String.IsNullOrEmpty(jsminify))
  1438. {
  1439. streamWriter.Write(String.Format("// {0}.ts\r\n", Path.GetFileNameWithoutExtension(javascriptFile).Replace(".babylon", "")));
  1440. streamWriter.Write(jsminify);
  1441. streamWriter.Write("\r\n\r\n");
  1442. }
  1443. }
  1444. catch (Exception ex)
  1445. {
  1446. UnityEngine.Debug.LogException(ex);
  1447. }
  1448. finally
  1449. {
  1450. streamWriter.Close();
  1451. }
  1452. }
  1453. else
  1454. {
  1455. UnityEngine.Debug.LogError("Failed to parse output work script");
  1456. }
  1457. }
  1458. }
  1459. else
  1460. {
  1461. UnityEngine.Debug.LogError("Failed to compile project script files");
  1462. }
  1463. }
  1464. else
  1465. {
  1466. UnityEngine.Debug.LogWarning("Typescript files not compiled. Failed to locate typescript compilers.");
  1467. }
  1468. return result;
  1469. }
  1470. private static void OnBuildProjectTypeScriptError(object sendingProcess, DataReceivedEventArgs outLine)
  1471. {
  1472. // * Log process output error
  1473. if (!String.IsNullOrEmpty(outLine.Data))
  1474. {
  1475. UnityEngine.Debug.LogError(outLine.Data);
  1476. }
  1477. }
  1478. }
  1479. public class BabylonSceneContractResolver : DataContractResolverStrategy
  1480. {
  1481. public BabylonSceneContractResolver()
  1482. {
  1483. // TODO: Append BabylonClassAttribute And BabylonPropertyAttribute To DataContract And DataMember Checks
  1484. }
  1485. }
  1486. }