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