OVRBuild.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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. productName = Application.productName;
  208. dataPath = Application.dataPath;
  209. buildThread = new Thread(delegate ()
  210. {
  211. OVRBuildRun();
  212. });
  213. buildThread.Start();
  214. return;
  215. }
  216. else if (buildResult.summary.result == UnityEditor.Build.Reporting.BuildResult.Cancelled)
  217. {
  218. UnityEngine.Debug.Log("Build cancelled.");
  219. }
  220. else
  221. {
  222. UnityEngine.Debug.Log("Build failed.");
  223. }
  224. buildFailed = true;
  225. }
  226. static void OVRBuildRun()
  227. {
  228. // 2. Process gradle project
  229. IncrementProgressBar("Processing gradle project . . .");
  230. if (ProcessGradleProject())
  231. {
  232. // 3. Build gradle project
  233. IncrementProgressBar("Starting gradle build . . .");
  234. if (BuildGradleProject())
  235. {
  236. OVRPlugin.SendEvent("build_complete", totalBuildTime.ToString(), "ovrbuild");
  237. // 4. Deploy and run
  238. if (DeployAPK())
  239. {
  240. return;
  241. }
  242. }
  243. }
  244. buildFailed = true;
  245. }
  246. private static bool BuildGradleProject()
  247. {
  248. gradleBuildProcess = new Process();
  249. string arguments = "-Xmx4096m -classpath \"" + gradlePath +
  250. "\" org.gradle.launcher.GradleMain assembleDebug -x validateSigningDebug";
  251. var gradleProjectPath = Path.Combine(gradleExport, productName);
  252. var processInfo = new System.Diagnostics.ProcessStartInfo
  253. {
  254. WorkingDirectory = gradleProjectPath,
  255. WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal,
  256. FileName = jdkPath,
  257. Arguments = arguments,
  258. RedirectStandardInput = true,
  259. UseShellExecute = false,
  260. CreateNoWindow = true,
  261. RedirectStandardError = true,
  262. RedirectStandardOutput = true,
  263. };
  264. gradleBuildProcess.StartInfo = processInfo;
  265. gradleBuildProcess.EnableRaisingEvents = true;
  266. DateTime gradleStartTime = System.DateTime.Now;
  267. DateTime gradleEndTime = System.DateTime.MinValue;
  268. gradleBuildProcess.Exited += new System.EventHandler(
  269. (s, e) =>
  270. {
  271. UnityEngine.Debug.Log("Gradle: Exited");
  272. }
  273. );
  274. gradleBuildProcess.OutputDataReceived += new DataReceivedEventHandler(
  275. (s, e) =>
  276. {
  277. if (e != null && e.Data != null &&
  278. e.Data.Length != 0 && e.Data.Contains("BUILD"))
  279. {
  280. UnityEngine.Debug.LogFormat("Gradle: {0}", e.Data);
  281. if (e.Data.Contains("SUCCESSFUL"))
  282. {
  283. UnityEngine.Debug.LogFormat("APK Build Completed: {0}",
  284. Path.Combine(Path.Combine(gradleProjectPath, "build\\outputs\\apk\\debug"), productName + "-debug.apk").Replace("/", "\\"));
  285. if (!apkOutputSuccessful.HasValue)
  286. {
  287. apkOutputSuccessful = true;
  288. }
  289. gradleEndTime = System.DateTime.Now;
  290. }
  291. else if (e.Data.Contains("FAILED"))
  292. {
  293. apkOutputSuccessful = false;
  294. }
  295. }
  296. }
  297. );
  298. gradleBuildProcess.ErrorDataReceived += new DataReceivedEventHandler(
  299. (s, e) =>
  300. {
  301. if (e != null && e.Data != null &&
  302. e.Data.Length != 0)
  303. {
  304. UnityEngine.Debug.LogErrorFormat("Gradle: {0}", e.Data);
  305. }
  306. apkOutputSuccessful = false;
  307. }
  308. );
  309. gradleBuildProcess.Start();
  310. gradleBuildProcess.BeginOutputReadLine();
  311. IncrementProgressBar("Building gradle project . . .");
  312. gradleBuildProcess.WaitForExit();
  313. // Add a timeout for if gradle unexpectedlly exits or errors out
  314. Stopwatch timeout = new Stopwatch();
  315. timeout.Start();
  316. while (apkOutputSuccessful == null)
  317. {
  318. if (timeout.ElapsedMilliseconds > 5000)
  319. {
  320. UnityEngine.Debug.LogError("Gradle has exited unexpectedly.");
  321. apkOutputSuccessful = false;
  322. }
  323. System.Threading.Thread.Sleep(100);
  324. }
  325. // Record time it takes to build gradle project only if we had a successful build
  326. double gradleTime = (gradleEndTime - gradleStartTime).TotalSeconds;
  327. if (gradleTime > 0)
  328. {
  329. OVRPlugin.SendEvent("build_step_building_gradle_project", gradleTime.ToString(), "ovrbuild");
  330. totalBuildTime += gradleTime;
  331. }
  332. return apkOutputSuccessful.HasValue && apkOutputSuccessful.Value;
  333. }
  334. private static bool ProcessGradleProject()
  335. {
  336. DateTime syncStartTime = System.DateTime.Now;
  337. DateTime syncEndTime = System.DateTime.MinValue;
  338. try
  339. {
  340. var ps = System.Text.RegularExpressions.Regex.Escape("" + Path.DirectorySeparatorChar);
  341. // ignore files .gradle/** build/** foo/.gradle/** and bar/build/**
  342. var ignorePattern = string.Format("^([^{0}]+{0})?(\\.gradle|build){0}", ps);
  343. var syncer = new DirectorySyncer(gradleTempExport,
  344. gradleExport, ignorePattern);
  345. syncCancelToken = new DirectorySyncer.CancellationTokenSource();
  346. var syncResult = syncer.Synchronize(syncCancelToken.Token);
  347. syncEndTime = System.DateTime.Now;
  348. }
  349. catch (Exception e)
  350. {
  351. UnityEngine.Debug.Log("OVRBuild: Processing gradle project failed with exception: " +
  352. e.Message);
  353. return false;
  354. }
  355. if (syncCancelToken.IsCancellationRequested)
  356. {
  357. return false;
  358. }
  359. // Record time it takes to sync gradle projects only if the sync was successful
  360. double syncTime = (syncEndTime - syncStartTime).TotalSeconds;
  361. if (syncTime > 0)
  362. {
  363. OVRPlugin.SendEvent("build_step_sync_gradle_project", syncTime.ToString(), "ovrbuild");
  364. totalBuildTime += syncTime;
  365. }
  366. return true;
  367. }
  368. private static List<string> GetScenesToBuild()
  369. {
  370. var sceneList = new List<string>();
  371. foreach (var scene in EditorBuildSettings.scenes)
  372. {
  373. // Enumerate scenes in project and check if scene is enabled to build
  374. if (scene.enabled)
  375. {
  376. sceneList.Add(scene.path);
  377. }
  378. }
  379. return sceneList;
  380. }
  381. public static bool DeployAPK()
  382. {
  383. // Create new instance of ADB Tool
  384. var adbTool = new OVRADBTool(androidSdkPath);
  385. if (adbTool.isReady)
  386. {
  387. string apkPathLocal;
  388. string gradleExportFolder = Path.Combine(Path.Combine(gradleExport, productName), "build\\outputs\\apk\\debug");
  389. // Check to see if gradle output directory exists
  390. gradleExportFolder = gradleExportFolder.Replace("/", "\\");
  391. if (!Directory.Exists(gradleExportFolder))
  392. {
  393. UnityEngine.Debug.LogError("Could not find the gradle project at the expected path: " + gradleExportFolder);
  394. return false;
  395. }
  396. // Search for output APK in gradle output directory
  397. apkPathLocal = Path.Combine(gradleExportFolder, productName + "-debug.apk");
  398. if (!System.IO.File.Exists(apkPathLocal))
  399. {
  400. UnityEngine.Debug.LogError(string.Format("Could not find {0} in the gradle project.", productName + "-debug.apk"));
  401. return false;
  402. }
  403. string output, error;
  404. DateTime timerStart;
  405. // Ensure that the Oculus temp directory is on the device by making it
  406. IncrementProgressBar("Making Temp directory on device");
  407. string[] mkdirCommand = { "-d shell", "mkdir -p", REMOTE_APK_PATH };
  408. if (adbTool.RunCommand(mkdirCommand, null, out output, out error) != 0) return false;
  409. // Push APK to device, also time how long it takes
  410. timerStart = System.DateTime.Now;
  411. IncrementProgressBar("Pushing APK to device . . .");
  412. string[] pushCommand = { "-d push", "\"" + apkPathLocal + "\"", REMOTE_APK_PATH };
  413. if (adbTool.RunCommand(pushCommand, null, out output, out error) != 0) return false;
  414. // Calculate the transfer speed and determine if user is using USB 2.0 or 3.0
  415. TimeSpan pushTime = System.DateTime.Now - timerStart;
  416. FileInfo apkInfo = new System.IO.FileInfo(apkPathLocal);
  417. double transferSpeed = (apkInfo.Length / pushTime.TotalSeconds) / BYTES_TO_MEGABYTES;
  418. bool informLog = transferSpeed < USB_TRANSFER_SPEED_THRES;
  419. UnityEngine.Debug.Log("OVRADBTool: Push Success");
  420. // Install the APK package on the device
  421. IncrementProgressBar("Installing APK . . .");
  422. string apkPath = REMOTE_APK_PATH + "/" + productName + "-debug.apk";
  423. apkPath = apkPath.Replace(" ", "\\ ");
  424. string[] installCommand = { "-d shell", "pm install -r", apkPath };
  425. timerStart = System.DateTime.Now;
  426. if (adbTool.RunCommand(installCommand, null, out output, out error) != 0) return false;
  427. TimeSpan installTime = System.DateTime.Now - timerStart;
  428. UnityEngine.Debug.Log("OVRADBTool: Install Success");
  429. // Start the application on the device
  430. IncrementProgressBar("Launching application on device . . .");
  431. string playerActivityName = "\"" + applicationIdentifier + "/" + applicationIdentifier + ".UnityPlayerActivity\"";
  432. string[] appStartCommand = { "-d shell", "am start -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -S -f 0x10200000 -n", playerActivityName };
  433. if (adbTool.RunCommand(appStartCommand, null, out output, out error) != 0) return false;
  434. UnityEngine.Debug.Log("OVRADBTool: Application Start Success");
  435. // Send back metrics on push and install steps
  436. OVRPlugin.AddCustomMetadata("transfer_speed", transferSpeed.ToString());
  437. OVRPlugin.SendEvent("build_step_push_apk", pushTime.TotalSeconds.ToString(), "ovrbuild");
  438. OVRPlugin.SendEvent("build_step_install_apk", installTime.TotalSeconds.ToString(), "ovrbuild");
  439. IncrementProgressBar("Success!");
  440. // If the user is using a USB 2.0 cable, inform them about improved transfer speeds and estimate time saved
  441. if (informLog)
  442. {
  443. var usb3Time = apkInfo.Length / (USB_3_TRANSFER_SPEED * BYTES_TO_MEGABYTES);
  444. 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));
  445. return true;
  446. }
  447. }
  448. else
  449. {
  450. UnityEngine.Debug.LogError("Could not find the ADB executable in the specified Android SDK directory.");
  451. }
  452. return false;
  453. }
  454. private static bool CheckADBDevices()
  455. {
  456. // Check if there are any ADB devices connected before starting the build process
  457. var adbTool = new OVRADBTool(OVRConfig.Instance.GetAndroidSDKPath());
  458. if (adbTool.isReady)
  459. {
  460. List<string> devices = adbTool.GetDevices();
  461. if (devices.Count == 0)
  462. {
  463. OVRPlugin.SendEvent("no_adb_devices", "", "ovrbuild");
  464. UnityEngine.Debug.LogError("No ADB devices connected. Cannot perform OVR Build and Run.");
  465. return false;
  466. }
  467. else if(devices.Count > 1)
  468. {
  469. OVRPlugin.SendEvent("multiple_adb_devices", "", "ovrbuild");
  470. UnityEngine.Debug.LogError("Multiple ADB devices connected. Cannot perform OVR Build and Run.");
  471. return false;
  472. }
  473. }
  474. else
  475. {
  476. OVRPlugin.SendEvent("ovr_adbtool_initialize_failure", "", "ovrbuild");
  477. UnityEngine.Debug.LogError("OVR ADB Tool failed to initialize. Check the Android SDK path in [Edit -> Preferences -> External Tools]");
  478. return false;
  479. }
  480. return true;
  481. }
  482. private static void SetupDirectories()
  483. {
  484. gradleTempExport = Path.Combine(Path.Combine(Application.dataPath, "../Temp"), "OVRGradleTempExport");
  485. gradleExport = Path.Combine(Path.Combine(Application.dataPath, "../Temp"), "OVRGradleExport");
  486. if (!Directory.Exists(gradleExport))
  487. {
  488. Directory.CreateDirectory(gradleExport);
  489. }
  490. }
  491. private static void InitializeProgressBar(int stepCount)
  492. {
  493. currentStep = 0;
  494. totalBuildSteps = stepCount;
  495. }
  496. private static void IncrementProgressBar(string message)
  497. {
  498. currentStep++;
  499. progressMessage = message;
  500. UnityEngine.Debug.Log("OVRBuild: " + message);
  501. }
  502. private static void SetProgressBarMessage(string message)
  503. {
  504. progressMessage = message;
  505. UnityEngine.Debug.Log("OVRBuild: " + message);
  506. }
  507. #endif //UNITY_EDITOR_WIN && UNITY_2018_1_OR_NEWER && UNITY_ANDROID
  508. }