Assignment for RMIT Mixed Reality in 2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

430 lines
13 KiB

  1. /************************************************************************************
  2. Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
  3. Licensed under the Oculus SDK License Version 3.4.1 (the "License");
  4. you may not use the Oculus SDK except in compliance with the License,
  5. which is provided at the time of installation or download, or which
  6. otherwise accompanies this software in either electronic or hard copy form.
  7. You may obtain a copy of the License at
  8. https://developer.oculus.com/licenses/sdk-3.4.1
  9. Unless required by applicable law or agreed to in writing, the Oculus SDK
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ************************************************************************************/
  15. //#define BUILDSESSION
  16. #if USING_XR_MANAGEMENT && USING_XR_SDK_OCULUS
  17. #define USING_XR_SDK
  18. #endif
  19. using System;
  20. using System.Collections;
  21. using System.Collections.Generic;
  22. using System.IO;
  23. using System.Xml;
  24. using System.Diagnostics;
  25. using System.Threading;
  26. using UnityEditor;
  27. using UnityEngine;
  28. using UnityEngine.Rendering;
  29. using UnityEditor.Build;
  30. #if UNITY_2018_1_OR_NEWER
  31. using UnityEditor.Build.Reporting;
  32. #endif
  33. #if UNITY_ANDROID
  34. using UnityEditor.Android;
  35. #endif
  36. [InitializeOnLoad]
  37. public class OVRGradleGeneration
  38. #if UNITY_2018_2_OR_NEWER
  39. : IPreprocessBuildWithReport, IPostprocessBuildWithReport
  40. #if UNITY_ANDROID
  41. , IPostGenerateGradleAndroidProject
  42. #endif
  43. {
  44. public OVRADBTool adbTool;
  45. public Process adbProcess;
  46. public int callbackOrder { get { return 3; } }
  47. static private System.DateTime buildStartTime;
  48. static private System.Guid buildGuid;
  49. #if UNITY_ANDROID
  50. private const string prefName = "OVRAutoIncrementVersionCode_Enabled";
  51. private const string menuItemAutoIncVersion = "Oculus/Tools/Auto Increment Version Code";
  52. static bool autoIncrementVersion = false;
  53. #endif
  54. static OVRGradleGeneration()
  55. {
  56. EditorApplication.delayCall += OnDelayCall;
  57. }
  58. static void OnDelayCall()
  59. {
  60. #if UNITY_ANDROID
  61. autoIncrementVersion = PlayerPrefs.GetInt(prefName, 0) != 0;
  62. Menu.SetChecked(menuItemAutoIncVersion, autoIncrementVersion);
  63. #endif
  64. }
  65. #if UNITY_ANDROID
  66. [MenuItem(menuItemAutoIncVersion)]
  67. static void ToggleUtilities()
  68. {
  69. autoIncrementVersion = !autoIncrementVersion;
  70. Menu.SetChecked(menuItemAutoIncVersion, autoIncrementVersion);
  71. int newValue = (autoIncrementVersion) ? 1 : 0;
  72. PlayerPrefs.SetInt(prefName, newValue);
  73. PlayerPrefs.Save();
  74. UnityEngine.Debug.Log("Auto Increment Version Code: " + autoIncrementVersion);
  75. }
  76. #endif
  77. public void OnPreprocessBuild(BuildReport report)
  78. {
  79. #if UNITY_ANDROID && !(USING_XR_SDK && UNITY_2019_3_OR_NEWER)
  80. // Generate error when Vulkan is selected as the perferred graphics API, which is not currently supported in Unity XR
  81. if (!PlayerSettings.GetUseDefaultGraphicsAPIs(BuildTarget.Android))
  82. {
  83. GraphicsDeviceType[] apis = PlayerSettings.GetGraphicsAPIs(BuildTarget.Android);
  84. if (apis.Length >= 1 && apis[0] == GraphicsDeviceType.Vulkan)
  85. {
  86. throw new BuildFailedException("The Vulkan Graphics API does not support XR in your configuration. To use Vulkan, you must use Unity 2019.3 or newer, and the XR Plugin Management.");
  87. }
  88. }
  89. #endif
  90. buildStartTime = System.DateTime.Now;
  91. buildGuid = System.Guid.NewGuid();
  92. if (!report.summary.outputPath.Contains("OVRGradleTempExport"))
  93. {
  94. OVRPlugin.SetDeveloperMode(OVRPlugin.Bool.True);
  95. OVRPlugin.AddCustomMetadata("build_type", "standard");
  96. }
  97. OVRPlugin.AddCustomMetadata("build_guid", buildGuid.ToString());
  98. OVRPlugin.AddCustomMetadata("target_platform", report.summary.platform.ToString());
  99. #if !UNITY_2019_3_OR_NEWER
  100. OVRPlugin.AddCustomMetadata("scripting_runtime_version", UnityEditor.PlayerSettings.scriptingRuntimeVersion.ToString());
  101. #endif
  102. if (report.summary.platform == UnityEditor.BuildTarget.StandaloneWindows
  103. || report.summary.platform == UnityEditor.BuildTarget.StandaloneWindows64)
  104. {
  105. OVRPlugin.AddCustomMetadata("target_oculus_platform", "rift");
  106. }
  107. #if BUILDSESSION
  108. StreamWriter writer = new StreamWriter("build_session", false);
  109. UnityEngine.Debug.LogFormat("Build Session: {0}", buildGuid.ToString());
  110. writer.WriteLine(buildGuid.ToString());
  111. writer.Close();
  112. #endif
  113. }
  114. public void OnPostGenerateGradleAndroidProject(string path)
  115. {
  116. UnityEngine.Debug.Log("OVRGradleGeneration triggered.");
  117. var targetOculusPlatform = new List<string>();
  118. if (OVRDeviceSelector.isTargetDeviceGearVrOrGo)
  119. {
  120. targetOculusPlatform.Add("geargo");
  121. }
  122. if (OVRDeviceSelector.isTargetDeviceQuest)
  123. {
  124. targetOculusPlatform.Add("quest");
  125. }
  126. OVRPlugin.AddCustomMetadata("target_oculus_platform", String.Join("_", targetOculusPlatform.ToArray()));
  127. UnityEngine.Debug.LogFormat(" GearVR or Go = {0} Quest = {1}", OVRDeviceSelector.isTargetDeviceGearVrOrGo, OVRDeviceSelector.isTargetDeviceQuest);
  128. #if UNITY_2019_3_OR_NEWER
  129. string gradleBuildPath = Path.Combine(path, "../launcher/build.gradle");
  130. #else
  131. string gradleBuildPath = Path.Combine(path, "build.gradle");
  132. #endif
  133. //Enable v2signing for Quest only
  134. bool v2SigningEnabled = OVRDeviceSelector.isTargetDeviceQuest && !OVRDeviceSelector.isTargetDeviceGearVrOrGo;
  135. if (File.Exists(gradleBuildPath))
  136. {
  137. try
  138. {
  139. string gradle = File.ReadAllText(gradleBuildPath);
  140. int v2Signingindex = gradle.IndexOf("v2SigningEnabled false");
  141. if (v2Signingindex != -1)
  142. {
  143. //v2 Signing flag found, ensure the correct value is set based on platform.
  144. if (v2SigningEnabled)
  145. {
  146. gradle = gradle.Replace("v2SigningEnabled false", "v2SigningEnabled true");
  147. System.IO.File.WriteAllText(gradleBuildPath, gradle);
  148. }
  149. }
  150. else
  151. {
  152. //v2 Signing flag missing, add it right after the key store password and set the value based on platform.
  153. int keyPassIndex = gradle.IndexOf("keyPassword");
  154. if (keyPassIndex != -1)
  155. {
  156. int v2Index = gradle.IndexOf("\n", keyPassIndex) + 1;
  157. if(v2Index != -1)
  158. {
  159. gradle = gradle.Insert(v2Index, "v2SigningEnabled " + (v2SigningEnabled ? "true" : "false") + "\n");
  160. System.IO.File.WriteAllText(gradleBuildPath, gradle);
  161. }
  162. }
  163. }
  164. }
  165. catch (System.Exception e)
  166. {
  167. UnityEngine.Debug.LogWarningFormat("Unable to overwrite build.gradle, error {0}", e.Message);
  168. }
  169. }
  170. else
  171. {
  172. UnityEngine.Debug.LogWarning("Unable to locate build.gradle");
  173. }
  174. PatchAndroidManifest(path);
  175. }
  176. public void PatchAndroidManifest(string path)
  177. {
  178. string manifestFolder = Path.Combine(path, "src/main");
  179. string file = manifestFolder + "/AndroidManifest.xml";
  180. bool patchedSecurityConfig = false;
  181. // If Enable NSC Config, copy XML file into gradle project
  182. OVRProjectConfig projectConfig = OVRProjectConfig.GetProjectConfig();
  183. if (projectConfig != null)
  184. {
  185. if (projectConfig.enableNSCConfig)
  186. {
  187. string securityConfigFile = GetOculusProjectNetworkSecConfigPath();
  188. string xmlDirectory = Path.Combine(path, "src/main/res/xml");
  189. try
  190. {
  191. if (!Directory.Exists(xmlDirectory))
  192. {
  193. Directory.CreateDirectory(xmlDirectory);
  194. }
  195. File.Copy(securityConfigFile, Path.Combine(xmlDirectory, "network_sec_config.xml"), true);
  196. patchedSecurityConfig = true;
  197. }
  198. catch (Exception e)
  199. {
  200. UnityEngine.Debug.LogError(e.Message);
  201. }
  202. }
  203. }
  204. OVRManifestPreprocessor.PatchAndroidManifest(file, enableSecurity: patchedSecurityConfig);
  205. }
  206. private static string GetOculusProjectNetworkSecConfigPath()
  207. {
  208. var so = ScriptableObject.CreateInstance(typeof(OVRPluginUpdaterStub));
  209. var script = MonoScript.FromScriptableObject(so);
  210. string assetPath = AssetDatabase.GetAssetPath(script);
  211. string editorDir = Directory.GetParent(assetPath).FullName;
  212. string configAssetPath = Path.GetFullPath(Path.Combine(editorDir, "network_sec_config.xml"));
  213. Uri configUri = new Uri(configAssetPath);
  214. Uri projectUri = new Uri(Application.dataPath);
  215. Uri relativeUri = projectUri.MakeRelativeUri(configUri);
  216. return relativeUri.ToString();
  217. }
  218. public void OnPostprocessBuild(BuildReport report)
  219. {
  220. #if UNITY_ANDROID
  221. if(autoIncrementVersion)
  222. {
  223. if((report.summary.options & BuildOptions.Development) == 0)
  224. {
  225. PlayerSettings.Android.bundleVersionCode++;
  226. UnityEngine.Debug.Log("Incrementing version code to " + PlayerSettings.Android.bundleVersionCode);
  227. }
  228. }
  229. bool isExporting = true;
  230. foreach (var step in report.steps)
  231. {
  232. if (step.name.Contains("Compile scripts")
  233. || step.name.Contains("Building scenes")
  234. || step.name.Contains("Writing asset files")
  235. || step.name.Contains("Preparing APK resources")
  236. || step.name.Contains("Creating Android manifest")
  237. || step.name.Contains("Processing plugins")
  238. || step.name.Contains("Exporting project")
  239. || step.name.Contains("Building Gradle project"))
  240. {
  241. OVRPlugin.SendEvent("build_step_" + step.name.ToLower().Replace(' ', '_'),
  242. step.duration.TotalSeconds.ToString(), "ovrbuild");
  243. #if BUILDSESSION
  244. UnityEngine.Debug.LogFormat("build_step_" + step.name.ToLower().Replace(' ', '_') + ": {0}", step.duration.TotalSeconds.ToString());
  245. #endif
  246. if(step.name.Contains("Building Gradle project"))
  247. {
  248. isExporting = false;
  249. }
  250. }
  251. }
  252. OVRPlugin.AddCustomMetadata("build_step_count", report.steps.Length.ToString());
  253. if (report.summary.outputPath.Contains("apk")) // Exclude Gradle Project Output
  254. {
  255. var fileInfo = new System.IO.FileInfo(report.summary.outputPath);
  256. OVRPlugin.AddCustomMetadata("build_output_size", fileInfo.Length.ToString());
  257. }
  258. #endif
  259. if (!report.summary.outputPath.Contains("OVRGradleTempExport"))
  260. {
  261. OVRPlugin.SendEvent("build_complete", (System.DateTime.Now - buildStartTime).TotalSeconds.ToString(), "ovrbuild");
  262. #if BUILDSESSION
  263. UnityEngine.Debug.LogFormat("build_complete: {0}", (System.DateTime.Now - buildStartTime).TotalSeconds.ToString());
  264. #endif
  265. }
  266. #if UNITY_ANDROID
  267. if (!isExporting)
  268. {
  269. // Get the hosts path to Android SDK
  270. if (adbTool == null)
  271. {
  272. adbTool = new OVRADBTool(OVRConfig.Instance.GetAndroidSDKPath(false));
  273. }
  274. if (adbTool.isReady)
  275. {
  276. // Check to see if there are any ADB devices connected before continuing.
  277. List<string> devices = adbTool.GetDevices();
  278. if(devices.Count == 0)
  279. {
  280. return;
  281. }
  282. // Clear current logs on device
  283. Process adbClearProcess;
  284. adbClearProcess = adbTool.RunCommandAsync(new string[] { "logcat --clear" }, null);
  285. // Add a timeout if we cannot get a response from adb logcat --clear in time.
  286. Stopwatch timeout = new Stopwatch();
  287. timeout.Start();
  288. while (!adbClearProcess.WaitForExit(100))
  289. {
  290. if (timeout.ElapsedMilliseconds > 2000)
  291. {
  292. adbClearProcess.Kill();
  293. return;
  294. }
  295. }
  296. // Check if existing ADB process is still running, kill if needed
  297. if (adbProcess != null && !adbProcess.HasExited)
  298. {
  299. adbProcess.Kill();
  300. }
  301. // Begin thread to time upload and install
  302. var thread = new Thread(delegate ()
  303. {
  304. TimeDeploy();
  305. });
  306. thread.Start();
  307. }
  308. }
  309. #endif
  310. }
  311. #if UNITY_ANDROID
  312. public bool WaitForProcess;
  313. public bool TransferStarted;
  314. public DateTime UploadStart;
  315. public DateTime UploadEnd;
  316. public DateTime InstallEnd;
  317. public void TimeDeploy()
  318. {
  319. if (adbTool != null)
  320. {
  321. TransferStarted = false;
  322. DataReceivedEventHandler outputRecieved = new DataReceivedEventHandler(
  323. (s, e) =>
  324. {
  325. if (e.Data != null && e.Data.Length != 0 && !e.Data.Contains("\u001b"))
  326. {
  327. if (e.Data.Contains("free_cache"))
  328. {
  329. // Device recieved install command and is starting upload
  330. UploadStart = System.DateTime.Now;
  331. TransferStarted = true;
  332. }
  333. else if (e.Data.Contains("Running dexopt"))
  334. {
  335. // Upload has finished and Package Manager is starting install
  336. UploadEnd = System.DateTime.Now;
  337. }
  338. else if (e.Data.Contains("dex2oat took"))
  339. {
  340. // Package Manager finished install
  341. InstallEnd = System.DateTime.Now;
  342. WaitForProcess = false;
  343. }
  344. else if (e.Data.Contains("W PackageManager"))
  345. {
  346. // Warning from Package Manager is a failure in the install process
  347. WaitForProcess = false;
  348. }
  349. }
  350. }
  351. );
  352. WaitForProcess = true;
  353. adbProcess = adbTool.RunCommandAsync(new string[] { "logcat" }, outputRecieved);
  354. Stopwatch transferTimeout = new Stopwatch();
  355. transferTimeout.Start();
  356. while (adbProcess != null && !adbProcess.WaitForExit(100))
  357. {
  358. if (!WaitForProcess)
  359. {
  360. adbProcess.Kill();
  361. float UploadTime = (float)(UploadEnd - UploadStart).TotalMilliseconds / 1000f;
  362. float InstallTime = (float)(InstallEnd - UploadEnd).TotalMilliseconds / 1000f;
  363. if (UploadTime > 0f)
  364. {
  365. OVRPlugin.SendEvent("deploy_task", UploadTime.ToString(), "ovrbuild");
  366. }
  367. if (InstallTime > 0f)
  368. {
  369. OVRPlugin.SendEvent("install_task", InstallTime.ToString(), "ovrbuild");
  370. }
  371. }
  372. if (!TransferStarted && transferTimeout.ElapsedMilliseconds > 5000)
  373. {
  374. adbProcess.Kill();
  375. }
  376. }
  377. }
  378. }
  379. #endif
  380. #else
  381. {
  382. #endif
  383. }