Tools.cs 62 KB

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