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.

606 lines
19 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. using UnityEngine;
  16. using UnityEditor;
  17. using System;
  18. using System.IO;
  19. using System.Diagnostics;
  20. using System.Collections.Generic;
  21. using System.Threading;
  22. /// <summary>
  23. /// Allows Oculus to build apps from the command line.
  24. /// </summary>
  25. partial class OculusBuildApp : EditorWindow
  26. {
  27. static void SetPCTarget()
  28. {
  29. if (EditorUserBuildSettings.activeBuildTarget != BuildTarget.StandaloneWindows)
  30. {
  31. EditorUserBuildSettings.SwitchActiveBuildTarget (BuildTargetGroup.Standalone, BuildTarget.StandaloneWindows);
  32. }
  33. UnityEditorInternal.VR.VREditor.SetVREnabledOnTargetGroup(BuildTargetGroup.Standalone, true);
  34. PlayerSettings.virtualRealitySupported = true;
  35. AssetDatabase.SaveAssets();
  36. }
  37. static void SetAndroidTarget()
  38. {
  39. EditorUserBuildSettings.androidBuildSubtarget = MobileTextureSubtarget.ASTC;
  40. EditorUserBuildSettings.androidBuildSystem = AndroidBuildSystem.Gradle;
  41. if (EditorUserBuildSettings.activeBuildTarget != BuildTarget.Android)
  42. {
  43. EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTargetGroup.Android, BuildTarget.Android);
  44. }
  45. UnityEditorInternal.VR.VREditor.SetVREnabledOnTargetGroup(BuildTargetGroup.Standalone, true);
  46. PlayerSettings.virtualRealitySupported = true;
  47. AssetDatabase.SaveAssets();
  48. }
  49. #if UNITY_EDITOR_WIN && UNITY_2018_3_OR_NEWER && UNITY_ANDROID
  50. // Build setting constants
  51. const string REMOTE_APK_PATH = "/sdcard/Oculus/Temp";
  52. const float USB_TRANSFER_SPEED_THRES = 25.0f;
  53. const float USB_3_TRANSFER_SPEED = 32.0f;
  54. const int NUM_BUILD_AND_RUN_STEPS = 9;
  55. const int BYTES_TO_MEGABYTES = 1048576;
  56. // Progress bar variables
  57. static int totalBuildSteps;
  58. static int currentStep;
  59. static string progressMessage;
  60. // Build setting varaibles
  61. static string gradlePath;
  62. static string jdkPath;
  63. static string androidSdkPath;
  64. static string applicationIdentifier;
  65. static string productName;
  66. static string dataPath;
  67. static string gradleTempExport;
  68. static string gradleExport;
  69. static bool showCancel;
  70. static bool buildFailed;
  71. static double totalBuildTime;
  72. static DirectorySyncer.CancellationTokenSource syncCancelToken;
  73. static Process gradleBuildProcess;
  74. static Thread buildThread;
  75. static bool? apkOutputSuccessful;
  76. private void OnGUI()
  77. {
  78. // Fix progress bar window size
  79. minSize = new Vector2(500, 170);
  80. maxSize = new Vector2(500, 170);
  81. // Show progress bar
  82. Rect progressRect = EditorGUILayout.BeginVertical();
  83. progressRect.height = 25.0f;
  84. float progress = currentStep / (float)totalBuildSteps;
  85. EditorGUI.ProgressBar(progressRect, progress, progressMessage);
  86. // Show cancel button only after Unity export has finished.
  87. if (showCancel)
  88. {
  89. GUIContent btnTxt = new GUIContent("Cancel");
  90. var rt = GUILayoutUtility.GetRect(btnTxt, GUI.skin.button, GUILayout.ExpandWidth(false));
  91. rt.center = new Vector2(EditorGUIUtility.currentViewWidth / 2, progressRect.height * 2);
  92. if (GUI.Button(rt, btnTxt, GUI.skin.button))
  93. {
  94. CancelBuild();
  95. }
  96. }
  97. EditorGUILayout.EndVertical();
  98. // Close window if progress has completed or Unity export failed
  99. if (progress >= 1.0f || buildFailed)
  100. {
  101. Close();
  102. }
  103. }
  104. void Update()
  105. {
  106. // Force window update if not in focus to ensure progress bar still updates
  107. var window = EditorWindow.focusedWindow;
  108. if (window != null && window.ToString().Contains("OculusBuildApp"))
  109. {
  110. Repaint();
  111. }
  112. }
  113. void CancelBuild()
  114. {
  115. SetProgressBarMessage("Canceling . . .");
  116. if (syncCancelToken != null)
  117. {
  118. syncCancelToken.Cancel();
  119. }
  120. if (apkOutputSuccessful.HasValue && apkOutputSuccessful.Value)
  121. {
  122. buildThread.Abort();
  123. buildFailed = true;
  124. }
  125. if (gradleBuildProcess != null && !gradleBuildProcess.HasExited)
  126. {
  127. var cancelThread = new Thread(delegate ()
  128. {
  129. CancelGradleBuild();
  130. });
  131. cancelThread.Start();
  132. }
  133. }
  134. void CancelGradleBuild()
  135. {
  136. Process cancelGradleProcess = new Process();
  137. string arguments = "-Xmx1024m -classpath \"" + gradlePath +
  138. "\" org.gradle.launcher.GradleMain --stop";
  139. var processInfo = new System.Diagnostics.ProcessStartInfo
  140. {
  141. WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal,
  142. FileName = jdkPath,
  143. Arguments = arguments,
  144. RedirectStandardInput = true,
  145. UseShellExecute = false,
  146. CreateNoWindow = true,
  147. RedirectStandardError = true,
  148. RedirectStandardOutput = true,
  149. };
  150. cancelGradleProcess.StartInfo = processInfo;
  151. cancelGradleProcess.EnableRaisingEvents = true;
  152. cancelGradleProcess.OutputDataReceived += new DataReceivedEventHandler(
  153. (s, e) =>
  154. {
  155. if (e != null && e.Data != null && e.Data.Length != 0)
  156. {
  157. UnityEngine.Debug.LogFormat("Gradle: {0}", e.Data);
  158. }
  159. }
  160. );
  161. apkOutputSuccessful = false;
  162. cancelGradleProcess.Start();
  163. cancelGradleProcess.BeginOutputReadLine();
  164. cancelGradleProcess.WaitForExit();
  165. buildFailed = true;
  166. }
  167. [MenuItem("Oculus/OVR Build/OVR Build APK And Run %k", false, 20)]
  168. static void StartBuildAndRun()
  169. {
  170. EditorWindow.GetWindow(typeof(OculusBuildApp));
  171. showCancel = false;
  172. buildFailed = false;
  173. totalBuildTime = 0;
  174. InitializeProgressBar(NUM_BUILD_AND_RUN_STEPS);
  175. IncrementProgressBar("Exporting Unity Project . . .");
  176. OVRPlugin.SetDeveloperMode(OVRPlugin.Bool.True);
  177. OVRPlugin.AddCustomMetadata("build_type", "ovr_build_and_run");
  178. if (!CheckADBDevices())
  179. {
  180. return;
  181. }
  182. // Record OVR Build and Run start event
  183. OVRPlugin.SendEvent("ovr_build_and_run_start", "", "ovrbuild");
  184. apkOutputSuccessful = null;
  185. syncCancelToken = null;
  186. gradleBuildProcess = null;
  187. UnityEngine.Debug.Log("OVRBuild: Starting Unity build ...");
  188. SetupDirectories();
  189. // 1. Get scenes to build in Unity, and export gradle project
  190. List<string> sceneList = GetScenesToBuild();
  191. DateTime unityExportStart = DateTime.Now;
  192. var buildResult = BuildPipeline.BuildPlayer(sceneList.ToArray(), gradleTempExport, BuildTarget.Android,
  193. BuildOptions.AcceptExternalModificationsToPlayer |
  194. BuildOptions.Development |
  195. BuildOptions.AllowDebugging);
  196. if (buildResult.summary.result == UnityEditor.Build.Reporting.BuildResult.Succeeded)
  197. {
  198. double unityExportTime = (DateTime.Now - unityExportStart).TotalSeconds;
  199. OVRPlugin.SendEvent("build_step_unity_export", unityExportTime.ToString(), "ovrbuild");
  200. totalBuildTime += unityExportTime;
  201. // Set static variables so build thread has updated data
  202. showCancel = true;
  203. gradlePath = OVRConfig.Instance.GetGradlePath();
  204. jdkPath = OVRConfig.Instance.GetJDKPath();
  205. androidSdkPath = OVRConfig.Instance.GetAndroidSDKPath();
  206. applicationIdentifier = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android);
  207. #if UNITY_2019_3_OR_NEWER
  208. productName = "launcher";
  209. #else
  210. productName = Application.productName;
  211. #endif
  212. dataPath = Application.dataPath;
  213. buildThread = new Thread(delegate ()
  214. {
  215. OVRBuildRun();
  216. });
  217. buildThread.Start();
  218. return;
  219. }
  220. else if (buildResult.summary.result == UnityEditor.Build.Reporting.BuildResult.Cancelled)
  221. {
  222. UnityEngine.Debug.Log("Build cancelled.");
  223. }
  224. else
  225. {
  226. UnityEngine.Debug.Log("Build failed.");
  227. }
  228. buildFailed = true;
  229. }
  230. static void OVRBuildRun()
  231. {
  232. // 2. Process gradle project
  233. IncrementProgressBar("Processing gradle project . . .");
  234. if (ProcessGradleProject())
  235. {
  236. // 3. Build gradle project
  237. IncrementProgressBar("Starting gradle build . . .");
  238. if (BuildGradleProject())
  239. {
  240. OVRPlugin.SendEvent("build_complete", totalBuildTime.ToString(), "ovrbuild");
  241. // 4. Deploy and run
  242. if (DeployAPK())
  243. {
  244. return;
  245. }
  246. }
  247. }
  248. buildFailed = true;
  249. }
  250. private static bool BuildGradleProject()
  251. {
  252. gradleBuildProcess = new Process();
  253. string arguments = "-Xmx4096m -classpath \"" + gradlePath +
  254. "\" org.gradle.launcher.GradleMain assembleDebug -x validateSigningDebug";
  255. #if UNITY_2019_3_OR_NEWER
  256. var gradleProjectPath = gradleExport;
  257. #else
  258. var gradleProjectPath = Path.Combine(gradleExport, productName);
  259. #endif
  260. var processInfo = new System.Diagnostics.ProcessStartInfo
  261. {
  262. WorkingDirectory = gradleProjectPath,
  263. WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal,
  264. FileName = jdkPath,
  265. Arguments = arguments,
  266. RedirectStandardInput = true,
  267. UseShellExecute = false,
  268. CreateNoWindow = true,
  269. RedirectStandardError = true,
  270. RedirectStandardOutput = true,
  271. };
  272. gradleBuildProcess.StartInfo = processInfo;
  273. gradleBuildProcess.EnableRaisingEvents = true;
  274. DateTime gradleStartTime = System.DateTime.Now;
  275. DateTime gradleEndTime = System.DateTime.MinValue;
  276. gradleBuildProcess.Exited += new System.EventHandler(
  277. (s, e) =>
  278. {
  279. UnityEngine.Debug.Log("Gradle: Exited");
  280. }
  281. );
  282. gradleBuildProcess.OutputDataReceived += new DataReceivedEventHandler(
  283. (s, e) =>
  284. {
  285. if (e != null && e.Data != null &&
  286. e.Data.Length != 0 && e.Data.Contains("BUILD"))
  287. {
  288. UnityEngine.Debug.LogFormat("Gradle: {0}", e.Data);
  289. if (e.Data.Contains("SUCCESSFUL"))
  290. {
  291. UnityEngine.Debug.LogFormat("APK Build Completed: {0}",
  292. Path.Combine(Path.Combine(gradleProjectPath, "build\\outputs\\apk\\debug"), productName + "-debug.apk").Replace("/", "\\"));
  293. if (!apkOutputSuccessful.HasValue)
  294. {
  295. apkOutputSuccessful = true;
  296. }
  297. gradleEndTime = System.DateTime.Now;
  298. }
  299. else if (e.Data.Contains("FAILED"))
  300. {
  301. apkOutputSuccessful = false;
  302. }
  303. }
  304. }
  305. );
  306. gradleBuildProcess.ErrorDataReceived += new DataReceivedEventHandler(
  307. (s, e) =>
  308. {
  309. if (e != null && e.Data != null &&
  310. e.Data.Length != 0)
  311. {
  312. UnityEngine.Debug.LogErrorFormat("Gradle: {0}", e.Data);
  313. }
  314. apkOutputSuccessful = false;
  315. }
  316. );
  317. gradleBuildProcess.Start();
  318. gradleBuildProcess.BeginOutputReadLine();
  319. IncrementProgressBar("Building gradle project . . .");
  320. gradleBuildProcess.WaitForExit();
  321. // Add a timeout for if gradle unexpectedlly exits or errors out
  322. Stopwatch timeout = new Stopwatch();
  323. timeout.Start();
  324. while (apkOutputSuccessful == null)
  325. {
  326. if (timeout.ElapsedMilliseconds > 5000)
  327. {
  328. UnityEngine.Debug.LogError("Gradle has exited unexpectedly.");
  329. apkOutputSuccessful = false;
  330. }
  331. System.Threading.Thread.Sleep(100);
  332. }
  333. // Record time it takes to build gradle project only if we had a successful build
  334. double gradleTime = (gradleEndTime - gradleStartTime).TotalSeconds;
  335. if (gradleTime > 0)
  336. {
  337. OVRPlugin.SendEvent("build_step_building_gradle_project", gradleTime.ToString(), "ovrbuild");
  338. totalBuildTime += gradleTime;
  339. }
  340. return apkOutputSuccessful.HasValue && apkOutputSuccessful.Value;
  341. }
  342. private static bool ProcessGradleProject()
  343. {
  344. DateTime syncStartTime = System.DateTime.Now;
  345. DateTime syncEndTime = System.DateTime.MinValue;
  346. try
  347. {
  348. var ps = System.Text.RegularExpressions.Regex.Escape("" + Path.DirectorySeparatorChar);
  349. // ignore files .gradle/** build/** foo/.gradle/** and bar/build/**
  350. var ignorePattern = string.Format("^([^{0}]+{0})?(\\.gradle|build){0}", ps);
  351. var syncer = new DirectorySyncer(gradleTempExport,
  352. gradleExport, ignorePattern);
  353. syncCancelToken = new DirectorySyncer.CancellationTokenSource();
  354. var syncResult = syncer.Synchronize(syncCancelToken.Token);
  355. syncEndTime = System.DateTime.Now;
  356. }
  357. catch (Exception e)
  358. {
  359. UnityEngine.Debug.Log("OVRBuild: Processing gradle project failed with exception: " +
  360. e.Message);
  361. return false;
  362. }
  363. if (syncCancelToken.IsCancellationRequested)
  364. {
  365. return false;
  366. }
  367. // Record time it takes to sync gradle projects only if the sync was successful
  368. double syncTime = (syncEndTime - syncStartTime).TotalSeconds;
  369. if (syncTime > 0)
  370. {
  371. OVRPlugin.SendEvent("build_step_sync_gradle_project", syncTime.ToString(), "ovrbuild");
  372. totalBuildTime += syncTime;
  373. }
  374. return true;
  375. }
  376. private static List<string> GetScenesToBuild()
  377. {
  378. var sceneList = new List<string>();
  379. foreach (var scene in EditorBuildSettings.scenes)
  380. {
  381. // Enumerate scenes in project and check if scene is enabled to build
  382. if (scene.enabled)
  383. {
  384. sceneList.Add(scene.path);
  385. }
  386. }
  387. return sceneList;
  388. }
  389. public static bool DeployAPK()
  390. {
  391. // Create new instance of ADB Tool
  392. var adbTool = new OVRADBTool(androidSdkPath);
  393. if (adbTool.isReady)
  394. {
  395. string apkPathLocal;
  396. string gradleExportFolder = Path.Combine(Path.Combine(gradleExport, productName), "build\\outputs\\apk\\debug");
  397. // Check to see if gradle output directory exists
  398. gradleExportFolder = gradleExportFolder.Replace("/", "\\");
  399. if (!Directory.Exists(gradleExportFolder))
  400. {
  401. UnityEngine.Debug.LogError("Could not find the gradle project at the expected path: " + gradleExportFolder);
  402. return false;
  403. }
  404. // Search for output APK in gradle output directory
  405. apkPathLocal = Path.Combine(gradleExportFolder, productName + "-debug.apk");
  406. if (!System.IO.File.Exists(apkPathLocal))
  407. {
  408. UnityEngine.Debug.LogError(string.Format("Could not find {0} in the gradle project.", productName + "-debug.apk"));
  409. return false;
  410. }
  411. string output, error;
  412. DateTime timerStart;
  413. // Ensure that the Oculus temp directory is on the device by making it
  414. IncrementProgressBar("Making Temp directory on device");
  415. string[] mkdirCommand = { "-d shell", "mkdir -p", REMOTE_APK_PATH };
  416. if (adbTool.RunCommand(mkdirCommand, null, out output, out error) != 0) return false;
  417. // Push APK to device, also time how long it takes
  418. timerStart = System.DateTime.Now;
  419. IncrementProgressBar("Pushing APK to device . . .");
  420. string[] pushCommand = { "-d push", "\"" + apkPathLocal + "\"", REMOTE_APK_PATH };
  421. if (adbTool.RunCommand(pushCommand, null, out output, out error) != 0) return false;
  422. // Calculate the transfer speed and determine if user is using USB 2.0 or 3.0
  423. TimeSpan pushTime = System.DateTime.Now - timerStart;
  424. FileInfo apkInfo = new System.IO.FileInfo(apkPathLocal);
  425. double transferSpeed = (apkInfo.Length / pushTime.TotalSeconds) / BYTES_TO_MEGABYTES;
  426. bool informLog = transferSpeed < USB_TRANSFER_SPEED_THRES;
  427. UnityEngine.Debug.Log("OVRADBTool: Push Success");
  428. // Install the APK package on the device
  429. IncrementProgressBar("Installing APK . . .");
  430. string apkPath = REMOTE_APK_PATH + "/" + productName + "-debug.apk";
  431. apkPath = apkPath.Replace(" ", "\\ ");
  432. string[] installCommand = { "-d shell", "pm install -r", apkPath };
  433. timerStart = System.DateTime.Now;
  434. if (adbTool.RunCommand(installCommand, null, out output, out error) != 0) return false;
  435. TimeSpan installTime = System.DateTime.Now - timerStart;
  436. UnityEngine.Debug.Log("OVRADBTool: Install Success");
  437. // Start the application on the device
  438. IncrementProgressBar("Launching application on device . . .");
  439. #if UNITY_2019_3_OR_NEWER
  440. string playerActivityName = "\"" + applicationIdentifier + "/com.unity3d.player.UnityPlayerActivity\"";
  441. #else
  442. string playerActivityName = "\"" + applicationIdentifier + "/" + applicationIdentifier + ".UnityPlayerActivity\"";
  443. #endif
  444. string[] appStartCommand = { "-d shell", "am start -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -S -f 0x10200000 -n", playerActivityName };
  445. if (adbTool.RunCommand(appStartCommand, null, out output, out error) != 0) return false;
  446. UnityEngine.Debug.Log("OVRADBTool: Application Start Success");
  447. // Send back metrics on push and install steps
  448. OVRPlugin.AddCustomMetadata("transfer_speed", transferSpeed.ToString());
  449. OVRPlugin.SendEvent("build_step_push_apk", pushTime.TotalSeconds.ToString(), "ovrbuild");
  450. OVRPlugin.SendEvent("build_step_install_apk", installTime.TotalSeconds.ToString(), "ovrbuild");
  451. IncrementProgressBar("Success!");
  452. // If the user is using a USB 2.0 cable, inform them about improved transfer speeds and estimate time saved
  453. if (informLog)
  454. {
  455. var usb3Time = apkInfo.Length / (USB_3_TRANSFER_SPEED * BYTES_TO_MEGABYTES);
  456. UnityEngine.Debug.Log(string.Format("OVRBuild has detected slow transfer speeds. A USB 3.0 cable is recommended to reduce the time it takes to deploy your project by approximatly {0:0.0} seconds", pushTime.TotalSeconds - usb3Time));
  457. return true;
  458. }
  459. }
  460. else
  461. {
  462. UnityEngine.Debug.LogError("Could not find the ADB executable in the specified Android SDK directory.");
  463. }
  464. return false;
  465. }
  466. private static bool CheckADBDevices()
  467. {
  468. // Check if there are any ADB devices connected before starting the build process
  469. var adbTool = new OVRADBTool(OVRConfig.Instance.GetAndroidSDKPath());
  470. if (adbTool.isReady)
  471. {
  472. List<string> devices = adbTool.GetDevices();
  473. if (devices.Count == 0)
  474. {
  475. OVRPlugin.SendEvent("no_adb_devices", "", "ovrbuild");
  476. UnityEngine.Debug.LogError("No ADB devices connected. Cannot perform OVR Build and Run.");
  477. return false;
  478. }
  479. else if(devices.Count > 1)
  480. {
  481. OVRPlugin.SendEvent("multiple_adb_devices", "", "ovrbuild");
  482. UnityEngine.Debug.LogError("Multiple ADB devices connected. Cannot perform OVR Build and Run.");
  483. return false;
  484. }
  485. }
  486. else
  487. {
  488. OVRPlugin.SendEvent("ovr_adbtool_initialize_failure", "", "ovrbuild");
  489. UnityEngine.Debug.LogError("OVR ADB Tool failed to initialize. Check the Android SDK path in [Edit -> Preferences -> External Tools]");
  490. return false;
  491. }
  492. return true;
  493. }
  494. private static void SetupDirectories()
  495. {
  496. gradleTempExport = Path.Combine(Path.Combine(Application.dataPath, "../Temp"), "OVRGradleTempExport");
  497. gradleExport = Path.Combine(Path.Combine(Application.dataPath, "../Temp"), "OVRGradleExport");
  498. if (!Directory.Exists(gradleExport))
  499. {
  500. Directory.CreateDirectory(gradleExport);
  501. }
  502. }
  503. private static void InitializeProgressBar(int stepCount)
  504. {
  505. currentStep = 0;
  506. totalBuildSteps = stepCount;
  507. }
  508. private static void IncrementProgressBar(string message)
  509. {
  510. currentStep++;
  511. progressMessage = message;
  512. UnityEngine.Debug.Log("OVRBuild: " + message);
  513. }
  514. private static void SetProgressBarMessage(string message)
  515. {
  516. progressMessage = message;
  517. UnityEngine.Debug.Log("OVRBuild: " + message);
  518. }
  519. #endif //UNITY_EDITOR_WIN && UNITY_2018_1_OR_NEWER && UNITY_ANDROID
  520. }