BlueGit

blue-star ggj-2020

Files

ggj-2020 / Assets / Oculus / VR / Editor / OVRBuild.cs

OVRBuild.cs

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